diff --git a/CMakeLists.txt b/CMakeLists.txt index 5fca6534ca79f00854bcc7b1fade998f2411b775..c25322d91181e8e9bc5dcd249e54d1edc0c48120 100755 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -280,6 +280,15 @@ INCLUDE("OvDelayLoad") # Sets the PROJECT_VERSION variable to something, depending on overriding OvSetProjectVersion.cmake files OV_SET_PROJECT_VERSION() +# Sort target into directories for better visualization in IDE +SET_PROPERTY(GLOBAL PROPERTY USE_FOLDERS ON) +SET(APP_FOLDER Applications) +SET(KERNEL_FOLDER Kernel) +SET(MODULES_FOLDER Modules) +SET(PLUGINS_FOLDER Plugins) +SET(TESTS_FOLDER Unit-Tests) +SET(VALIDATION_FOLDER Validation-Tests) + # Traverse these directories and build their components ADD_SUBDIRECTORY("build-tool/") diff --git a/applications/developer-tools/id-generator/CMakeLists.txt b/applications/developer-tools/id-generator/CMakeLists.txt index db67d4142fe8606a265cb9255b8606b5c2dc7fd0..b7b70ee21e4b9f166dd239b95ca0591e2afe0eb1 100644 --- a/applications/developer-tools/id-generator/CMakeLists.txt +++ b/applications/developer-tools/id-generator/CMakeLists.txt @@ -7,12 +7,11 @@ SET(PROJECT_VERSION ${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}.${PROJECT_ FILE(GLOB_RECURSE SRC_FILES src/*.cpp src/*.h src/*.inl) ADD_EXECUTABLE(${PROJECT_NAME} ${SRC_FILES}) +SET_PROPERTY(TARGET ${PROJECT_NAME} PROPERTY FOLDER ${APP_FOLDER}) # --------------------------------- # Target macros -# Defines target operating system -# Defines target architecture -# Defines target compiler +# Defines target operating system, architecture and compiler # --------------------------------- SET_BUILD_PLATFORM() diff --git a/applications/developer-tools/plugin-inspector/CMakeLists.txt b/applications/developer-tools/plugin-inspector/CMakeLists.txt index 46f05a504a79be4167dfbfb2ca59035bd4d61c23..63053b794fcbe8fe0f61586133d3709641f90804 100644 --- a/applications/developer-tools/plugin-inspector/CMakeLists.txt +++ b/applications/developer-tools/plugin-inspector/CMakeLists.txt @@ -22,8 +22,8 @@ PROJECT(openvibe-plugin-inspector) FILE(GLOB_RECURSE SRC_FILES src/*.cpp src/*.h) - ADD_EXECUTABLE(${PROJECT_NAME} ${SRC_FILES}) +SET_PROPERTY(TARGET ${PROJECT_NAME} PROPERTY FOLDER ${APP_FOLDER}) INCLUDE("FindOpenViBE") INCLUDE("FindOpenViBECommon") @@ -34,9 +34,7 @@ INCLUDE("FindThirdPartyBoost") # --------------------------------- # Target macros -# Defines target operating system -# Defines target architecture -# Defines target compiler +# Defines target operating system, architecture and compiler # --------------------------------- SET_BUILD_PLATFORM() diff --git a/applications/developer-tools/plugin-inspector/src/ovpiCPluginObjectDescEnumBoxTemplateGenerator.cpp b/applications/developer-tools/plugin-inspector/src/ovpiCPluginObjectDescEnumBoxTemplateGenerator.cpp index 502c3a1b53f6958a3090e69a028823cf6f59e143..7121a39b4cd825161a0d0a9fe715a2fcec0b2189 100644 --- a/applications/developer-tools/plugin-inspector/src/ovpiCPluginObjectDescEnumBoxTemplateGenerator.cpp +++ b/applications/developer-tools/plugin-inspector/src/ovpiCPluginObjectDescEnumBoxTemplateGenerator.cpp @@ -14,11 +14,10 @@ using namespace OpenViBE; using namespace /*OpenViBE::*/Kernel; using namespace /*OpenViBE::*/Plugins; -namespace -{ - std::map<int, char> indentCharacters = { { 0, '=' }, { 1, '-' }, { 2, '~' }, { 3, '+' } }; +namespace { +std::map<int, char> indentCharacters = { { 0, '=' }, { 1, '-' }, { 2, '~' }, { 3, '+' } }; - std::string generateRstTitle(const std::string& title, const int level) { return title + "\n" + std::string(title.size(), indentCharacters[level]) + "\n"; } +std::string generateRstTitle(const std::string& title, const int level) { return title + "\n" + std::string(title.size(), indentCharacters[level]) + "\n"; } } // ------------------------------------------------------------------------------------------------------------------------------------ diff --git a/applications/developer-tools/scenario-player/CMakeLists.txt b/applications/developer-tools/scenario-player/CMakeLists.txt index 4d058b779cf05f66b8d2dd94e92c211b04abf7f8..a250f6af940076c2890298534f2c8c3e7bdb549a 100755 --- a/applications/developer-tools/scenario-player/CMakeLists.txt +++ b/applications/developer-tools/scenario-player/CMakeLists.txt @@ -35,6 +35,7 @@ SET(PROJECT_VERSION ${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}.${PROJECT_ ADD_DEFINITIONS( -DPROJECT_VERSION="${PROJECT_VERSION}" ) FILE(GLOB_RECURSE SRC_FILES src/*.cpp src/*.h src/*.hpp) ADD_EXECUTABLE(${PROJECT_NAME} ${SRC_FILES}) +SET_PROPERTY(TARGET ${PROJECT_NAME} PROPERTY FOLDER ${APP_FOLDER}) # ---------------------- # External dependecies @@ -50,9 +51,7 @@ INCLUDE("FindThirdPartyBoost") # --------------------------------- # Target macros -# Defines target operating system -# Defines target architecture -# Defines target compiler +# Defines target operating system, architecture and compiler # --------------------------------- SET_BUILD_PLATFORM() diff --git a/applications/developer-tools/scenario-player/src/ovspCCommand.cpp b/applications/developer-tools/scenario-player/src/ovspCCommand.cpp index 04f60d79c181f702a67851b08e8052210d676cee..801b1bc8ac70f202796f09b5ec1071a6d30e8be2 100644 --- a/applications/developer-tools/scenario-player/src/ovspCCommand.cpp +++ b/applications/developer-tools/scenario-player/src/ovspCCommand.cpp @@ -22,137 +22,136 @@ #include "ovspCKernelFacade.h" #include "ovspCCommand.h" -namespace OpenViBE +namespace OpenViBE { +EPlayerReturnCodes SInitCmd::execute(CKernelFacade& kernelFacade) const { - EPlayerReturnCodes SInitCmd::execute(CKernelFacade& kernelFacade) const - { - std::cout << "About to execute:" << std::endl << *this << std::endl; - return kernelFacade.initialize(); - } + std::cout << "About to execute:" << std::endl << *this << std::endl; + return kernelFacade.initialize(); +} - void SInitCmd::doPrint(std::ostream& os) const - { - os << "command name: InitCommand" << std::endl; - os << "Benchmark: " << (this->benchmark ? std::to_string(this->benchmark.get()) : "not set") << std::endl; - } +void SInitCmd::doPrint(std::ostream& os) const +{ + os << "command name: InitCommand" << std::endl; + os << "Benchmark: " << (this->benchmark ? std::to_string(this->benchmark.get()) : "not set") << std::endl; +} - EPlayerReturnCodes SLoadKernelCmd::execute(CKernelFacade& kernelFacade) const - { - std::cout << "About to execute:" << std::endl << *this << std::endl; - // default config file is an empty one so it is not problem to give it directly as param - return kernelFacade.loadKernel(*this); - } +EPlayerReturnCodes SLoadKernelCmd::execute(CKernelFacade& kernelFacade) const +{ + std::cout << "About to execute:" << std::endl << *this << std::endl; + // default config file is an empty one so it is not problem to give it directly as param + return kernelFacade.loadKernel(*this); +} - void SLoadKernelCmd::doPrint(std::ostream& os) const +void SLoadKernelCmd::doPrint(std::ostream& os) const +{ + os << "command name: LoadKernelCommand" << std::endl; + os << "ConfigurationFile: " << (this->configFile ? this->configFile.get() : "not set") << std::endl; +} + +EPlayerReturnCodes SLoadScenarioCmd::execute(CKernelFacade& kernelFacade) const +{ + std::cout << "About to execute:" << std::endl << *this << std::endl; + + if (!this->scenarioName || !this->scenarioFile) { - os << "command name: LoadKernelCommand" << std::endl; - os << "ConfigurationFile: " << (this->configFile ? this->configFile.get() : "not set") << std::endl; + std::cerr << "Missing required arguments for command" << std::endl; + return EPlayerReturnCodes::MissingMandatoryArgument; } - EPlayerReturnCodes SLoadScenarioCmd::execute(CKernelFacade& kernelFacade) const - { - std::cout << "About to execute:" << std::endl << *this << std::endl; + return kernelFacade.loadScenario(*this); +} - if (!this->scenarioName || !this->scenarioFile) - { - std::cerr << "Missing required arguments for command" << std::endl; - return EPlayerReturnCodes::MissingMandatoryArgument; - } +void SLoadScenarioCmd::doPrint(std::ostream& os) const +{ + os << "command name: LoadScenarioCommand" << std::endl; + os << "ScenarioName: " << (this->scenarioName ? this->scenarioName.get() : "not set") << std::endl; + os << "ScenarioFile: " << (this->scenarioFile ? this->scenarioFile.get() : "not set") << std::endl; +} - return kernelFacade.loadScenario(*this); - } +EPlayerReturnCodes SUpdateScenarioCmd::execute(CKernelFacade& kernelFacade) const +{ + std::cout << "About to execute:" << std::endl << *this << std::endl; - void SLoadScenarioCmd::doPrint(std::ostream& os) const + if (!this->scenarioName || !this->scenarioFile) { - os << "command name: LoadScenarioCommand" << std::endl; - os << "ScenarioName: " << (this->scenarioName ? this->scenarioName.get() : "not set") << std::endl; - os << "ScenarioFile: " << (this->scenarioFile ? this->scenarioFile.get() : "not set") << std::endl; + std::cerr << "Missing required arguments for command" << std::endl; + return EPlayerReturnCodes::MissingMandatoryArgument; } - EPlayerReturnCodes SUpdateScenarioCmd::execute(CKernelFacade& kernelFacade) const - { - std::cout << "About to execute:" << std::endl << *this << std::endl; + return kernelFacade.updateScenario(*this); +} - if (!this->scenarioName || !this->scenarioFile) - { - std::cerr << "Missing required arguments for command" << std::endl; - return EPlayerReturnCodes::MissingMandatoryArgument; - } +void SUpdateScenarioCmd::doPrint(std::ostream& os) const +{ + os << "command name: UpdateScenarioCommand" << std::endl; + os << "ScenarioName: " << (this->scenarioName ? this->scenarioName.get() : "not set") << std::endl; + os << "ScenarioFile: " << (this->scenarioFile ? this->scenarioFile.get() : "not set") << std::endl; +} - return kernelFacade.updateScenario(*this); - } +EPlayerReturnCodes SResetCmd::execute(CKernelFacade& /*kernelFacade*/) const +{ + // to be implemented + std::cout << "About to execute:" << std::endl << *this << std::endl << "Not implemented yet" << std::endl; + return EPlayerReturnCodes::Success; +} - void SUpdateScenarioCmd::doPrint(std::ostream& os) const - { - os << "command name: UpdateScenarioCommand" << std::endl; - os << "ScenarioName: " << (this->scenarioName ? this->scenarioName.get() : "not set") << std::endl; - os << "ScenarioFile: " << (this->scenarioFile ? this->scenarioFile.get() : "not set") << std::endl; - } +void SResetCmd::doPrint(std::ostream& os) const { os << "command name: ResetCommand" << std::endl; } - EPlayerReturnCodes SResetCmd::execute(CKernelFacade& /*kernelFacade*/) const +EPlayerReturnCodes SRunScenarioCmd::execute(CKernelFacade& kernelFacade) const +{ + std::cout << "About to execute:" << std::endl << *this << std::endl; + if (!this->scenarioList) { - // to be implemented - std::cout << "About to execute:" << std::endl << *this << std::endl << "Not implemented yet" << std::endl; - return EPlayerReturnCodes::Success; + std::cerr << "Missing required arguments for command: ScenarioList" << std::endl; + return EPlayerReturnCodes::MissingMandatoryArgument; } + return kernelFacade.runScenarioList(*this); +} + +void SRunScenarioCmd::doPrint(std::ostream& os) const +{ + os << "command name: SRunScenarioCmd" << std::endl; - void SResetCmd::doPrint(std::ostream& os) const { os << "command name: ResetCommand" << std::endl; } + os << "ScenarioList:"; + if (this->scenarioList) { for (auto& scenario : this->scenarioList.get()) { os << " " << scenario; } } + else { os << " not set"; } + os << std::endl; - EPlayerReturnCodes SRunScenarioCmd::execute(CKernelFacade& kernelFacade) const + os << "PlayMode: "; + if (this->playMode) { - std::cout << "About to execute:" << std::endl << *this << std::endl; - if (!this->scenarioList) - { - std::cerr << "Missing required arguments for command: ScenarioList" << std::endl; - return EPlayerReturnCodes::MissingMandatoryArgument; - } - return kernelFacade.runScenarioList(*this); + const std::string modeAsString = (this->playMode == EPlayerPlayMode::Fastfoward) ? "fastforward" : "standard"; + os << modeAsString; } + else { os << "not set"; } + os << std::endl; - void SRunScenarioCmd::doPrint(std::ostream& os) const - { - os << "command name: SRunScenarioCmd" << std::endl; - - os << "ScenarioList:"; - if (this->scenarioList) { for (auto& scenario : this->scenarioList.get()) { os << " " << scenario; } } - else { os << " not set"; } - os << std::endl; - - os << "PlayMode: "; - if (this->playMode) - { - const std::string modeAsString = (this->playMode == EPlayerPlayMode::Fastfoward) ? "fastforward" : "standard"; - os << modeAsString; - } - else { os << "not set"; } - os << std::endl; - - os << "MaximumExecutionTime: " << (this->maximumExecutionTime ? std::to_string(this->maximumExecutionTime.get()) : "not set") << std::endl; - - os << "TokenList:"; - if (this->tokenList) { for (auto& token : this->tokenList.get()) { os << " (" << token.first << "," << token.second << ")"; } } - else { os << " not set"; } - os << std::endl; - } + os << "MaximumExecutionTime: " << (this->maximumExecutionTime ? std::to_string(this->maximumExecutionTime.get()) : "not set") << std::endl; - EPlayerReturnCodes SSetupScenarioCmd::execute(CKernelFacade& kernelFacade) const - { - std::cout << "About to execute:" << std::endl << *this << std::endl; - if (!this->scenarioName) - { - std::cerr << "Missing required arguments for command" << std::endl; - return EPlayerReturnCodes::MissingMandatoryArgument; - } - return kernelFacade.setupScenario(*this); - } + os << "TokenList:"; + if (this->tokenList) { for (auto& token : this->tokenList.get()) { os << " (" << token.first << "," << token.second << ")"; } } + else { os << " not set"; } + os << std::endl; +} - void SSetupScenarioCmd::doPrint(std::ostream& os) const +EPlayerReturnCodes SSetupScenarioCmd::execute(CKernelFacade& kernelFacade) const +{ + std::cout << "About to execute:" << std::endl << *this << std::endl; + if (!this->scenarioName) { - os << "command name: SSetupScenarioCmd" << std::endl; - os << "ScenarioName: " << (this->scenarioName ? this->scenarioName.get() : "not set") << std::endl; - os << "TokenList:"; - if (this->tokenList) { for (auto& token : this->tokenList.get()) { os << " (" << token.first << "," << token.second << ")"; } } - else { os << " not set"; } - os << std::endl; + std::cerr << "Missing required arguments for command" << std::endl; + return EPlayerReturnCodes::MissingMandatoryArgument; } + return kernelFacade.setupScenario(*this); +} + +void SSetupScenarioCmd::doPrint(std::ostream& os) const +{ + os << "command name: SSetupScenarioCmd" << std::endl; + os << "ScenarioName: " << (this->scenarioName ? this->scenarioName.get() : "not set") << std::endl; + os << "TokenList:"; + if (this->tokenList) { for (auto& token : this->tokenList.get()) { os << " (" << token.first << "," << token.second << ")"; } } + else { os << " not set"; } + os << std::endl; +} } // namespace OpenViBE diff --git a/applications/developer-tools/scenario-player/src/ovspCCommand.h b/applications/developer-tools/scenario-player/src/ovspCCommand.h index 6289f7952c7af94d32202923c28395c593f446ca..b9b0efaf7e5bebde5ff3d997f7a37e02d7c70432 100644 --- a/applications/developer-tools/scenario-player/src/ovspCCommand.h +++ b/applications/developer-tools/scenario-player/src/ovspCCommand.h @@ -25,183 +25,182 @@ #include <boost/optional.hpp> #include <string> -namespace OpenViBE +namespace OpenViBE { +/** +* \struct SInitCmd +* \author cgarraud (INRIA) +* \date 2016-01-26 +* \brief Command that drives the initialization of the tool +* \ingroup ScenarioPlayer +* +* InitCommand class contains the following properties: +* - Benchmark: Flag to enable benchmark on execute command (optional). +* +*/ +struct SInitCmd final : SCommand +{ + // List of properties + boost::optional<bool> benchmark; + + EPlayerReturnCodes execute(CKernelFacade& kernelFacade) const override; + +protected: + void doPrint(std::ostream& os) const override; +}; + + +/** +* \struct SLoadKernelCmd +* \author cgarraud (INRIA) +* \date 2016-01-26 +* \brief Command that drives kernel loading +* \ingroup ScenarioPlayer +* +* LoadKernelCommand contains the following properties: +* - ConfigurationFile: Path to kernel configuration file (optional) +* . +* +*/ +struct SLoadKernelCmd final : SCommand +{ + // List of properties + boost::optional<std::string> configFile; + + EPlayerReturnCodes execute(CKernelFacade& kernelFacade) const override; + +protected: + + void doPrint(std::ostream& os) const override; +}; + +/** +* \struct SLoadScenarioCmd +* \author cgarraud (INRIA) +* \date 2016-01-26 +* \brief Command that drives scenario loading +* \ingroup ScenarioPlayer +* +* LoadScenarioCommand contains the following properties: +* - ScenarioFile: Path to xml scenario file (mandatory) +* - ScenarioName: Name of the scenario (mandatory) +* . +* +*/ +struct SLoadScenarioCmd final : SCommand +{ + // List of properties + boost::optional<std::string> scenarioFile; + boost::optional<std::string> scenarioName; + + EPlayerReturnCodes execute(CKernelFacade& kernelFacade) const override; + +protected: + + void doPrint(std::ostream& os) const override; +}; + +/** +* \struct SUpdateScenarioCmd +* \author criou (INRIA) +* \date 2018-04-16 +* \brief Command that drives scenario update and export +* \ingroup ScenarioPlayer +* +* UpdateScenarioCommand contains the following properties: +* - ScenarioFile: Path to xml scenario file (mandatory) +* . +* +*/ +struct SUpdateScenarioCmd final : SCommand { - /** - * \struct SInitCmd - * \author cgarraud (INRIA) - * \date 2016-01-26 - * \brief Command that drives the initialization of the tool - * \ingroup ScenarioPlayer - * - * InitCommand class contains the following properties: - * - Benchmark: Flag to enable benchmark on execute command (optional). - * - */ - struct SInitCmd final : SCommand - { - // List of properties - boost::optional<bool> benchmark; - - EPlayerReturnCodes execute(CKernelFacade& kernelFacade) const override; - - protected: - void doPrint(std::ostream& os) const override; - }; - - - /** - * \struct SLoadKernelCmd - * \author cgarraud (INRIA) - * \date 2016-01-26 - * \brief Command that drives kernel loading - * \ingroup ScenarioPlayer - * - * LoadKernelCommand contains the following properties: - * - ConfigurationFile: Path to kernel configuration file (optional) - * . - * - */ - struct SLoadKernelCmd final : SCommand - { - // List of properties - boost::optional<std::string> configFile; - - EPlayerReturnCodes execute(CKernelFacade& kernelFacade) const override; - - protected: - - void doPrint(std::ostream& os) const override; - }; - - /** - * \struct SLoadScenarioCmd - * \author cgarraud (INRIA) - * \date 2016-01-26 - * \brief Command that drives scenario loading - * \ingroup ScenarioPlayer - * - * LoadScenarioCommand contains the following properties: - * - ScenarioFile: Path to xml scenario file (mandatory) - * - ScenarioName: Name of the scenario (mandatory) - * . - * - */ - struct SLoadScenarioCmd final : SCommand - { - // List of properties - boost::optional<std::string> scenarioFile; - boost::optional<std::string> scenarioName; - - EPlayerReturnCodes execute(CKernelFacade& kernelFacade) const override; - - protected: - - void doPrint(std::ostream& os) const override; - }; - - /** - * \struct SUpdateScenarioCmd - * \author criou (INRIA) - * \date 2018-04-16 - * \brief Command that drives scenario update and export - * \ingroup ScenarioPlayer - * - * UpdateScenarioCommand contains the following properties: - * - ScenarioFile: Path to xml scenario file (mandatory) - * . - * - */ - struct SUpdateScenarioCmd final : SCommand - { - // List of properties - boost::optional<std::string> scenarioFile; - boost::optional<std::string> scenarioName; - - EPlayerReturnCodes execute(CKernelFacade& kernelFacade) const override; - - protected: - - void doPrint(std::ostream& os) const override; - }; - - /** - * \struct SResetCmd - * \author cgarraud (INRIA) - * \date 2016-01-26 - * \brief Command that drives tool reset to its initial state - * \ingroup ScenarioPlayer - */ - struct SResetCmd final : SCommand - { - EPlayerReturnCodes execute(CKernelFacade& kernelFacade) const override; - - protected: - - void doPrint(std::ostream& os) const override; - }; - - /** - * \struct SRunScenarioCmd - * \author cgarraud (INRIA) - * \date 2016-01-26 - * \brief Command that drives the execution of a list of scenarios - * \ingroup ScenarioPlayer - * - * SRunScenarioCmd contains the following properties: - * - ScenarioList: Names of scenario that must be executed (mandatory) - * - PlayMode: 0 for standard, 1 for fastforward (optional) - * - MaximumExecutionTime: Scenarios playing execution time limit (optional) - * - TokenList: List of global (token,value) pairs (optional) - * . - * - */ - struct SRunScenarioCmd final : SCommand - { - using Token = std::pair<std::string, std::string>; - - // List of properties - boost::optional<std::vector<std::string>> scenarioList; - boost::optional<EPlayerPlayMode> playMode; - boost::optional<double> maximumExecutionTime; - boost::optional<std::vector<Token>> tokenList; - - EPlayerReturnCodes execute(CKernelFacade& kernelFacade) const override; - - protected: - - void doPrint(std::ostream& os) const override; - }; - - /** - * \struct SSetupScenarioCmd - * \author cgarraud (INRIA) - * \date 2016-01-26 - * \brief Command that drives the setup of a scenario - * \ingroup ScenarioPlayer - * - * SSetupScenarioCmd contains the following properties: - * - ScenarioName: name of the scenario to setup (mandatory) - * - TokenList: List of scenario specific tokens (optional) - * . - * - * The token list overwrites the previous token list if the command was already - * called on the same scenario (note that an empty token list is allowed). - * - */ - struct SSetupScenarioCmd final : SCommand - { - using Token = std::pair<std::string, std::string>; - - // List of properties - boost::optional<std::string> scenarioName; - boost::optional<std::vector<Token>> tokenList; - - - EPlayerReturnCodes execute(CKernelFacade& kernelFacade) const override; - - protected: - - void doPrint(std::ostream& os) const override; - }; + // List of properties + boost::optional<std::string> scenarioFile; + boost::optional<std::string> scenarioName; + + EPlayerReturnCodes execute(CKernelFacade& kernelFacade) const override; + +protected: + + void doPrint(std::ostream& os) const override; +}; + +/** +* \struct SResetCmd +* \author cgarraud (INRIA) +* \date 2016-01-26 +* \brief Command that drives tool reset to its initial state +* \ingroup ScenarioPlayer +*/ +struct SResetCmd final : SCommand +{ + EPlayerReturnCodes execute(CKernelFacade& kernelFacade) const override; + +protected: + + void doPrint(std::ostream& os) const override; +}; + +/** +* \struct SRunScenarioCmd +* \author cgarraud (INRIA) +* \date 2016-01-26 +* \brief Command that drives the execution of a list of scenarios +* \ingroup ScenarioPlayer +* +* SRunScenarioCmd contains the following properties: +* - ScenarioList: Names of scenario that must be executed (mandatory) +* - PlayMode: 0 for standard, 1 for fastforward (optional) +* - MaximumExecutionTime: Scenarios playing execution time limit (optional) +* - TokenList: List of global (token,value) pairs (optional) +* . +* +*/ +struct SRunScenarioCmd final : SCommand +{ + using Token = std::pair<std::string, std::string>; + + // List of properties + boost::optional<std::vector<std::string>> scenarioList; + boost::optional<EPlayerPlayMode> playMode; + boost::optional<double> maximumExecutionTime; + boost::optional<std::vector<Token>> tokenList; + + EPlayerReturnCodes execute(CKernelFacade& kernelFacade) const override; + +protected: + + void doPrint(std::ostream& os) const override; +}; + +/** +* \struct SSetupScenarioCmd +* \author cgarraud (INRIA) +* \date 2016-01-26 +* \brief Command that drives the setup of a scenario +* \ingroup ScenarioPlayer +* +* SSetupScenarioCmd contains the following properties: +* - ScenarioName: name of the scenario to setup (mandatory) +* - TokenList: List of scenario specific tokens (optional) +* . +* +* The token list overwrites the previous token list if the command was already +* called on the same scenario (note that an empty token list is allowed). +* +*/ +struct SSetupScenarioCmd final : SCommand +{ + using Token = std::pair<std::string, std::string>; + + // List of properties + boost::optional<std::string> scenarioName; + boost::optional<std::vector<Token>> tokenList; + + + EPlayerReturnCodes execute(CKernelFacade& kernelFacade) const override; + +protected: + + void doPrint(std::ostream& os) const override; +}; } // namespace OpenViBE diff --git a/applications/developer-tools/scenario-player/src/ovspCCommandFileParser.cpp b/applications/developer-tools/scenario-player/src/ovspCCommandFileParser.cpp index ad63a7d757df1b36a008379ede5eafd6ef22c710..3a0f2cbfe53842385ba62f19f4a8618635692c82 100644 --- a/applications/developer-tools/scenario-player/src/ovspCCommandFileParser.cpp +++ b/applications/developer-tools/scenario-player/src/ovspCCommandFileParser.cpp @@ -22,317 +22,316 @@ #include "ovspCCommand.h" #include "ovspCCommandFileParser.h" -namespace OpenViBE +namespace OpenViBE { +using namespace std::placeholders; + +// should be moved in a utility class/file +std::string CommandFileParser::trim(const std::string& str) +{ + // remove leading and trailing space + // no use of regex here cause it might be too slow + auto begin = str.find_first_not_of(" \t"), end = str.find_last_not_of(" \t"); + if (begin == std::string::npos) { begin = 0; } + if (end == std::string::npos) { end = str.size() - 1; } + return str.substr(begin, end - begin + 1); +} + +// should be moved in a utility class/file +std::pair<std::string, std::string> CommandFileParser::tokenize(const std::string& str) { - using namespace std::placeholders; + // given a string of type "token : value", return a pair of (token,value) + // split method is not used because only the first delimiter is of interest + const auto split = str.find_first_of(':'); - // should be moved in a utility class/file - std::string CommandFileParser::trim(const std::string& str) - { - // remove leading and trailing space - // no use of regex here cause it might be too slow - auto begin = str.find_first_not_of(" \t"), end = str.find_last_not_of(" \t"); - if (begin == std::string::npos) { begin = 0; } - if (end == std::string::npos) { end = str.size() - 1; } - return str.substr(begin, end - begin + 1); - } + if (split == std::string::npos) { throw std::runtime_error("Impossible to convert " + str + " to token/value pair"); } - // should be moved in a utility class/file - std::pair<std::string, std::string> CommandFileParser::tokenize(const std::string& str) - { - // given a string of type "token : value", return a pair of (token,value) - // split method is not used because only the first delimiter is of interest - const auto split = str.find_first_of(':'); + auto token = trim(str.substr(0, split)); + auto val = trim(str.substr(split + 1, str.size() - split - 1)); - if (split == std::string::npos) { throw std::runtime_error("Impossible to convert " + str + " to token/value pair"); } + return std::make_pair(token, val); +} - auto token = trim(str.substr(0, split)); - auto val = trim(str.substr(split + 1, str.size() - split - 1)); +// should be moved in a utility class/file +std::vector<std::string> CommandFileParser::split(const std::string& str, const char delimiter) +{ + std::vector<std::string> vec; + size_t currentIdx = 0; + size_t delimiterIdx = str.find(delimiter); - return std::make_pair(token, val); - } + auto trimmed = trim(str.substr(currentIdx, delimiterIdx)); + if (!trimmed.empty()) { vec.push_back(trimmed); } - // should be moved in a utility class/file - std::vector<std::string> CommandFileParser::split(const std::string& str, const char delimiter) + while (delimiterIdx != std::string::npos) { - std::vector<std::string> vec; - size_t currentIdx = 0; - size_t delimiterIdx = str.find(delimiter); + // abc,cde,fgh + // ^ -> current index points to the first element after a match + // ^ -> delimiter index points to next match + currentIdx = delimiterIdx + 1; + delimiterIdx = str.find(delimiter, currentIdx); - auto trimmed = trim(str.substr(currentIdx, delimiterIdx)); - if (!trimmed.empty()) { vec.push_back(trimmed); } - - while (delimiterIdx != std::string::npos) - { - // abc,cde,fgh - // ^ -> current index points to the first element after a match - // ^ -> delimiter index points to next match - currentIdx = delimiterIdx + 1; - delimiterIdx = str.find(delimiter, currentIdx); + trimmed = trim(str.substr(currentIdx, delimiterIdx - currentIdx)); - trimmed = trim(str.substr(currentIdx, delimiterIdx - currentIdx)); - - if (!trimmed.empty()) { vec.push_back(trimmed); } - } - return vec; + if (!trimmed.empty()) { vec.push_back(trimmed); } } + return vec; +} - // should be moved in a utility class/file - bool CommandFileParser::toBool(const std::string& str) - { - // try to keep same behavior as stoi or stol +// should be moved in a utility class/file +bool CommandFileParser::toBool(const std::string& str) +{ + // try to keep same behavior as stoi or stol + + std::string lowerStr; + lowerStr.reserve(str.size()); + std::transform(str.begin(), str.end(), lowerStr.begin(), tolower); + + bool result; + if (str == "false" || str == "0") { result = false; } + else if (str == "true" || str == "1") { result = true; } + else { throw std::runtime_error("Impossible to convert " + str + " to bool"); } + return result; +} + +// should be moved in a utility class/file +// input is expected to be trimmed (by a call to tolenize for example) +std::vector<std::string> CommandFileParser::toList(const std::string& str) +{ + std::vector<std::string> vec; + // {token1, token2, token3 ...} pattern expected + if (str.size() >= 3 && str[0] == '{' && str[str.size() - 1] == '}') { vec = split(str.substr(1, str.length() - 2), ','); } + else { throw std::runtime_error("Impossible to convert " + str + " to list"); } - std::string lowerStr; - lowerStr.reserve(str.size()); - std::transform(str.begin(), str.end(), lowerStr.begin(), tolower); + return vec; +} - bool result; - if (str == "false" || str == "0") { result = false; } - else if (str == "true" || str == "1") { result = true; } - else { throw std::runtime_error("Impossible to convert " + str + " to bool"); } - return result; - } +// should be moved in a utility class/file +// part of this function duplicates code from ProgramOptions.hpp +std::vector<CommandFileParser::Token> CommandFileParser::toTokenList(const std::string& str) +{ + std::vector<Token> vec; - // should be moved in a utility class/file - // input is expected to be trimmed (by a call to tolenize for example) - std::vector<std::string> CommandFileParser::toList(const std::string& str) + for (auto& rawToken : toList(str)) { - std::vector<std::string> vec; - // {token1, token2, token3 ...} pattern expected - if (str.size() >= 3 && str[0] == '{' && str[str.size() - 1] == '}') { vec = split(str.substr(1, str.length() - 2), ','); } - else { throw std::runtime_error("Impossible to convert " + str + " to list"); } - - return vec; - } + // rawToken is expected to be trimmed - // should be moved in a utility class/file - // part of this function duplicates code from ProgramOptions.hpp - std::vector<CommandFileParser::Token> CommandFileParser::toTokenList(const std::string& str) - { - std::vector<Token> vec; + const auto split = rawToken.find_first_of(':'); + const auto size = rawToken.size(); - for (auto& rawToken : toList(str)) + // (a:b) pattern expected + // minimal regex std::regex("\\(.+:.+\\)") + if (!(size >= 5 && rawToken[0] == '(' && rawToken[size - 1] == ')') || split == std::string::npos) { - // rawToken is expected to be trimmed + throw std::runtime_error("Failed to parse token pair from value: " + rawToken); + } - const auto split = rawToken.find_first_of(':'); - const auto size = rawToken.size(); + Token token; + token.first = trim(rawToken.substr(1, split - 1)); - // (a:b) pattern expected - // minimal regex std::regex("\\(.+:.+\\)") - if (!(size >= 5 && rawToken[0] == '(' && rawToken[size - 1] == ')') || split == std::string::npos) - { - throw std::runtime_error("Failed to parse token pair from value: " + rawToken); - } + // magic 2 numbers is because substr takes a length as second parameter + // 2 = remove the last ) + account for the first one + token.second = trim(rawToken.substr(split + 1, size - split - 2)); - Token token; - token.first = trim(rawToken.substr(1, split - 1)); + vec.push_back(token); + } - // magic 2 numbers is because substr takes a length as second parameter - // 2 = remove the last ) + account for the first one - token.second = trim(rawToken.substr(split + 1, size - split - 2)); + return vec; +} - vec.push_back(token); - } +void CommandFileParser::initialize() +{ + // using a callback mechanism allows us to implement the core parse() method + // very easily (no need to put some if/else blocks everywhere depending on which command is encountered) + m_callbacks["Init"] = std::bind(&CommandFileParser::initCommandCb, this, _1); + m_callbacks["Reset"] = std::bind(&CommandFileParser::resetCommandCb, this, _1); + m_callbacks["LoadKernel"] = std::bind(&CommandFileParser::loadKernelCommandCb, this, _1); + m_callbacks["LoadScenario"] = std::bind(&CommandFileParser::loadScenarioCommandCb, this, _1); + m_callbacks["SetupScenario"] = std::bind(&CommandFileParser::setupScenarioCommandCb, this, _1); + m_callbacks["RunScenario"] = std::bind(&CommandFileParser::runScenarioCommandCb, this, _1); +} + +void CommandFileParser::uninitialize() +{ + m_callbacks.clear(); + m_cmdList.clear(); +} - return vec; - } +EPlayerReturnCodes CommandFileParser::parse() +{ + std::ifstream fileStream(m_cmdFile); - void CommandFileParser::initialize() + if (!fileStream.is_open()) { - // using a callback mechanism allows us to implement the core parse() method - // very easily (no need to put some if/else blocks everywhere depending on which command is encountered) - m_callbacks["Init"] = std::bind(&CommandFileParser::initCommandCb, this, _1); - m_callbacks["Reset"] = std::bind(&CommandFileParser::resetCommandCb, this, _1); - m_callbacks["LoadKernel"] = std::bind(&CommandFileParser::loadKernelCommandCb, this, _1); - m_callbacks["LoadScenario"] = std::bind(&CommandFileParser::loadScenarioCommandCb, this, _1); - m_callbacks["SetupScenario"] = std::bind(&CommandFileParser::setupScenarioCommandCb, this, _1); - m_callbacks["RunScenario"] = std::bind(&CommandFileParser::runScenarioCommandCb, this, _1); + std::cerr << "ERROR: impossible to open file at location: " << m_cmdFile << std::endl; + return EPlayerReturnCodes::OpeningFileFailure; } - void CommandFileParser::uninitialize() - { - m_callbacks.clear(); - m_cmdList.clear(); - } + std::string line; + bool isFillingSection{ false }; + std::vector<std::string> sectionContent; + std::string sectionTag; - EPlayerReturnCodes CommandFileParser::parse() + while (std::getline(fileStream, line)) { - std::ifstream fileStream(m_cmdFile); + auto trimmedLine = trim(line); + const auto size = trimmedLine.size(); - if (!fileStream.is_open()) + // [a] pattern expected + // minimal regex std::regex("^(?!\\#)\\[.+\\])") + if (size >= 3 && trimmedLine[0] == '[' + && trimmedLine[size - 1] == ']') { - std::cerr << "ERROR: impossible to open file at location: " << m_cmdFile << std::endl; - return EPlayerReturnCodes::OpeningFileFailure; - } - - std::string line; - bool isFillingSection{ false }; - std::vector<std::string> sectionContent; - std::string sectionTag; + if (isFillingSection) // flush the section that was beeing filled + { + const auto errorCode = this->flush(sectionTag, sectionContent); + if (errorCode != EPlayerReturnCodes::Success) { return errorCode; } + } - while (std::getline(fileStream, line)) - { - auto trimmedLine = trim(line); - const auto size = trimmedLine.size(); + // use of regex to be confident on tag structure + // magic 2 numbers is because substr takes length as second parameter + // 2 = remove the last ] + account for the first one + sectionTag = trimmedLine.substr(1, size - 2); - // [a] pattern expected - // minimal regex std::regex("^(?!\\#)\\[.+\\])") - if (size >= 3 && trimmedLine[0] == '[' - && trimmedLine[size - 1] == ']') + if (m_callbacks.find(sectionTag) == m_callbacks.end()) { - if (isFillingSection) // flush the section that was beeing filled - { - const auto errorCode = this->flush(sectionTag, sectionContent); - if (errorCode != EPlayerReturnCodes::Success) { return errorCode; } - } - - // use of regex to be confident on tag structure - // magic 2 numbers is because substr takes length as second parameter - // 2 = remove the last ] + account for the first one - sectionTag = trimmedLine.substr(1, size - 2); - - if (m_callbacks.find(sectionTag) == m_callbacks.end()) - { - std::cerr << "ERROR: Unknown command = " << sectionTag << std::endl; - return EPlayerReturnCodes::ParsingCommandFailure; - } - - isFillingSection = true; - sectionContent.clear(); + std::cerr << "ERROR: Unknown command = " << sectionTag << std::endl; + return EPlayerReturnCodes::ParsingCommandFailure; } - else { sectionContent.push_back(trimmedLine); } - } - if (isFillingSection) - { - const auto errorCode = this->flush(sectionTag, sectionContent); - if (errorCode != EPlayerReturnCodes::Success) { return errorCode; } + isFillingSection = true; + sectionContent.clear(); } - return EPlayerReturnCodes::Success; + else { sectionContent.push_back(trimmedLine); } } - EPlayerReturnCodes CommandFileParser::flush(const std::string& sectionTag, const std::vector<std::string>& sectionContent) + if (isFillingSection) { - try // try block here as some conversions are made with the stl in the callback and might throw - { - const auto returnCode = m_callbacks[sectionTag](sectionContent); - if (returnCode != EPlayerReturnCodes::Success) { return returnCode; } - } - catch (const std::exception& e) - { - std::cerr << "ERROR: Caught exception while parsing command = " << sectionTag << std::endl; - std::cerr << "ERROR: Exception: " << e.what() << std::endl; - return EPlayerReturnCodes::ParsingCommandFailure; - } - return EPlayerReturnCodes::Success; + const auto errorCode = this->flush(sectionTag, sectionContent); + if (errorCode != EPlayerReturnCodes::Success) { return errorCode; } } + return EPlayerReturnCodes::Success; +} - EPlayerReturnCodes CommandFileParser::initCommandCb(const std::vector<std::string>& sectionContent) +EPlayerReturnCodes CommandFileParser::flush(const std::string& sectionTag, const std::vector<std::string>& sectionContent) +{ + try // try block here as some conversions are made with the stl in the callback and might throw + { + const auto returnCode = m_callbacks[sectionTag](sectionContent); + if (returnCode != EPlayerReturnCodes::Success) { return returnCode; } + } + catch (const std::exception& e) { - std::shared_ptr<SInitCmd> command = std::make_shared<SInitCmd>(); + std::cerr << "ERROR: Caught exception while parsing command = " << sectionTag << std::endl; + std::cerr << "ERROR: Exception: " << e.what() << std::endl; + return EPlayerReturnCodes::ParsingCommandFailure; + } + return EPlayerReturnCodes::Success; +} - for (auto& line : sectionContent) +EPlayerReturnCodes CommandFileParser::initCommandCb(const std::vector<std::string>& sectionContent) +{ + std::shared_ptr<SInitCmd> command = std::make_shared<SInitCmd>(); + + for (auto& line : sectionContent) + { + // lines are expected to be trimmed + // a:b pattern expected + // minimal regex std::regex("^(?!\\#).+:.+") + if (!line.empty() && line[0] != '#') { - // lines are expected to be trimmed - // a:b pattern expected - // minimal regex std::regex("^(?!\\#).+:.+") - if (!line.empty() && line[0] != '#') - { - auto param = tokenize(line); + auto param = tokenize(line); - if (param.first == "Benchmark") { command->benchmark = toBool(param.second); } - else { std::cout << "WARNING: Unknown parameter for Init command: " << param.first << std::endl; } - } + if (param.first == "Benchmark") { command->benchmark = toBool(param.second); } + else { std::cout << "WARNING: Unknown parameter for Init command: " << param.first << std::endl; } } - m_cmdList.push_back(command); - return EPlayerReturnCodes::Success; } + m_cmdList.push_back(command); + return EPlayerReturnCodes::Success; +} - EPlayerReturnCodes CommandFileParser::resetCommandCb(const std::vector<std::string>& /*sectionContent*/) - { - const std::shared_ptr<SResetCmd> command = std::make_shared<SResetCmd>(); - m_cmdList.push_back(command); - return EPlayerReturnCodes::Success; - } +EPlayerReturnCodes CommandFileParser::resetCommandCb(const std::vector<std::string>& /*sectionContent*/) +{ + const std::shared_ptr<SResetCmd> command = std::make_shared<SResetCmd>(); + m_cmdList.push_back(command); + return EPlayerReturnCodes::Success; +} - EPlayerReturnCodes CommandFileParser::loadKernelCommandCb(const std::vector<std::string>& sectionContent) - { - std::shared_ptr<SLoadKernelCmd> command = std::make_shared<SLoadKernelCmd>(); +EPlayerReturnCodes CommandFileParser::loadKernelCommandCb(const std::vector<std::string>& sectionContent) +{ + std::shared_ptr<SLoadKernelCmd> command = std::make_shared<SLoadKernelCmd>(); - // cf. initCommandCb - for (auto& line : sectionContent) + // cf. initCommandCb + for (auto& line : sectionContent) + { + if (!line.empty() && line[0] != '#') { - if (!line.empty() && line[0] != '#') - { - auto param = tokenize(line); - if (param.first == "ConfigurationFile") { command->configFile = param.second; } - else { std::cout << "WARNING: Unknown parameter for LoadKernel command: " << param.first << std::endl; } - } + auto param = tokenize(line); + if (param.first == "ConfigurationFile") { command->configFile = param.second; } + else { std::cout << "WARNING: Unknown parameter for LoadKernel command: " << param.first << std::endl; } } - m_cmdList.push_back(command); - return EPlayerReturnCodes::Success; } + m_cmdList.push_back(command); + return EPlayerReturnCodes::Success; +} - EPlayerReturnCodes CommandFileParser::loadScenarioCommandCb(const std::vector<std::string>& sectionContent) - { - std::shared_ptr<SLoadScenarioCmd> command = std::make_shared<SLoadScenarioCmd>(); +EPlayerReturnCodes CommandFileParser::loadScenarioCommandCb(const std::vector<std::string>& sectionContent) +{ + std::shared_ptr<SLoadScenarioCmd> command = std::make_shared<SLoadScenarioCmd>(); - // cf. initCommandCb - for (auto& line : sectionContent) + // cf. initCommandCb + for (auto& line : sectionContent) + { + if (!line.empty() && line[0] != '#') { - if (!line.empty() && line[0] != '#') - { - auto param = tokenize(line); + auto param = tokenize(line); - if (param.first == "ScenarioName") { command->scenarioName = param.second; } - else if (param.first == "ScenarioFile") { command->scenarioFile = param.second; } - else { std::cout << "WARNING: Unknown parameter for LoadScenario command: " << param.first << std::endl; } - } + if (param.first == "ScenarioName") { command->scenarioName = param.second; } + else if (param.first == "ScenarioFile") { command->scenarioFile = param.second; } + else { std::cout << "WARNING: Unknown parameter for LoadScenario command: " << param.first << std::endl; } } - m_cmdList.push_back(command); - return EPlayerReturnCodes::Success; } + m_cmdList.push_back(command); + return EPlayerReturnCodes::Success; +} - EPlayerReturnCodes CommandFileParser::setupScenarioCommandCb(const std::vector<std::string>& sectionContent) - { - std::shared_ptr<SSetupScenarioCmd> command = std::make_shared<SSetupScenarioCmd>(); +EPlayerReturnCodes CommandFileParser::setupScenarioCommandCb(const std::vector<std::string>& sectionContent) +{ + std::shared_ptr<SSetupScenarioCmd> command = std::make_shared<SSetupScenarioCmd>(); - // cf. initCommandCb - for (auto& line : sectionContent) + // cf. initCommandCb + for (auto& line : sectionContent) + { + if (!line.empty() && line[0] != '#') { - if (!line.empty() && line[0] != '#') - { - auto param = tokenize(line); + auto param = tokenize(line); - if (param.first == "ScenarioName") { command->scenarioName = param.second; } - else if (param.first == "TokenList") { command->tokenList = toTokenList(param.second); } - else { std::cout << "WARNING: Unknown parameter for SetupScenario command: " << param.first << std::endl; } - } + if (param.first == "ScenarioName") { command->scenarioName = param.second; } + else if (param.first == "TokenList") { command->tokenList = toTokenList(param.second); } + else { std::cout << "WARNING: Unknown parameter for SetupScenario command: " << param.first << std::endl; } } - m_cmdList.push_back(command); - return EPlayerReturnCodes::Success; } + m_cmdList.push_back(command); + return EPlayerReturnCodes::Success; +} - EPlayerReturnCodes CommandFileParser::runScenarioCommandCb(const std::vector<std::string>& sectionContent) - { - std::shared_ptr<SRunScenarioCmd> command = std::make_shared<SRunScenarioCmd>(); +EPlayerReturnCodes CommandFileParser::runScenarioCommandCb(const std::vector<std::string>& sectionContent) +{ + std::shared_ptr<SRunScenarioCmd> command = std::make_shared<SRunScenarioCmd>(); - // cf. initCommandCb - for (auto& line : sectionContent) + // cf. initCommandCb + for (auto& line : sectionContent) + { + if (!line.empty() && line[0] != '#') { - if (!line.empty() && line[0] != '#') - { - auto param = tokenize(line); + auto param = tokenize(line); - if (param.first == "ScenarioList") { command->scenarioList = toList(param.second); } - else if (param.first == "PlayMode") { command->playMode = EPlayerPlayMode(std::stoi(param.second)); } - else if (param.first == "MaximumExecutionTime") { command->maximumExecutionTime = std::stod(param.second); } - else if (param.first == "TokenList") { command->tokenList = (toTokenList(param.second)); } - else { std::cout << "WARNING: Unknown parameter for RunScenario command: " << param.first << std::endl; } - } + if (param.first == "ScenarioList") { command->scenarioList = toList(param.second); } + else if (param.first == "PlayMode") { command->playMode = EPlayerPlayMode(std::stoi(param.second)); } + else if (param.first == "MaximumExecutionTime") { command->maximumExecutionTime = std::stod(param.second); } + else if (param.first == "TokenList") { command->tokenList = (toTokenList(param.second)); } + else { std::cout << "WARNING: Unknown parameter for RunScenario command: " << param.first << std::endl; } } - m_cmdList.push_back(command); - return EPlayerReturnCodes::Success; } + m_cmdList.push_back(command); + return EPlayerReturnCodes::Success; +} } // namespace OpenViBE diff --git a/applications/developer-tools/scenario-player/src/ovspCCommandFileParser.h b/applications/developer-tools/scenario-player/src/ovspCCommandFileParser.h index 5188ffe817c267911dc813344c7aa2eda347171d..7c906108a4688275dacf76e54f51a0ee70f49f6f 100644 --- a/applications/developer-tools/scenario-player/src/ovspCCommandFileParser.h +++ b/applications/developer-tools/scenario-player/src/ovspCCommandFileParser.h @@ -30,74 +30,73 @@ #include <map> -namespace OpenViBE +namespace OpenViBE { +/** +* \class CommandFileParser +* \author cgarraud (INRIA) +* \date 2016-01-27 +* \brief Parser implementation that parses command a file +* \ingroup ScenarioPlayer +* +* The current implementation retrieves the list of commands from a file. +* +* Input file format requirements: +* - Command names are defined within brackets [InitCommand] on a single line +* - Each command parameter is defined on a single line below the command name: +* + Single value parameters are defined as: parameterName: value +* + Simple list parameters are defined as: parameterName: {val1,val2,...} +* + Token list parameters are defined as: parameterName: { (token1:val1),(token2:val2) } (no ',' authorized in (token, value) pair) +* . +* . +* +* \todo The implementation uses a lot of string utility functions that need more +* testing +* +* \note Use of regex would simplify the implementation but boost::regex is not header-only and std::regex not implemented in gcc 4.8 +* +*/ +class CommandFileParser final : public ICommandParser { +public: + /** - * \class CommandFileParser - * \author cgarraud (INRIA) - * \date 2016-01-27 - * \brief Parser implementation that parses command a file - * \ingroup ScenarioPlayer - * - * The current implementation retrieves the list of commands from a file. - * - * Input file format requirements: - * - Command names are defined within brackets [InitCommand] on a single line - * - Each command parameter is defined on a single line below the command name: - * + Single value parameters are defined as: parameterName: value - * + Simple list parameters are defined as: parameterName: {val1,val2,...} - * + Token list parameters are defined as: parameterName: { (token1:val1),(token2:val2) } (no ',' authorized in (token, value) pair) - * . - * . * - * \todo The implementation uses a lot of string utility functions that need more - * testing - * - * \note Use of regex would simplify the implementation but boost::regex is not header-only and std::regex not implemented in gcc 4.8 + * \brief Constructor + * \param[in] file path to the command file * */ - class CommandFileParser final : public ICommandParser - { - public: - - /** - * - * \brief Constructor - * \param[in] file path to the command file - * - */ - explicit CommandFileParser(const std::string& file) : m_cmdFile(file) { } + explicit CommandFileParser(const std::string& file) : m_cmdFile(file) { } - void initialize() override; - void uninitialize() override; + void initialize() override; + void uninitialize() override; - std::vector<std::shared_ptr<SCommand>> getCommandList() const override { return m_cmdList; } + std::vector<std::shared_ptr<SCommand>> getCommandList() const override { return m_cmdList; } - EPlayerReturnCodes parse() override; + EPlayerReturnCodes parse() override; - private: +private: - using CallbackType = std::function<EPlayerReturnCodes(std::vector<std::string>)>; - using Token = std::pair<std::string, std::string>; + using CallbackType = std::function<EPlayerReturnCodes(std::vector<std::string>)>; + using Token = std::pair<std::string, std::string>; - static std::string trim(const std::string& str); - static std::pair<std::string, std::string> tokenize(const std::string& str); - static std::vector<std::string> split(const std::string& str, char delimiter); - static bool toBool(const std::string& str); - static std::vector<std::string> toList(const std::string& str); - static std::vector<Token> toTokenList(const std::string& str); + static std::string trim(const std::string& str); + static std::pair<std::string, std::string> tokenize(const std::string& str); + static std::vector<std::string> split(const std::string& str, char delimiter); + static bool toBool(const std::string& str); + static std::vector<std::string> toList(const std::string& str); + static std::vector<Token> toTokenList(const std::string& str); - EPlayerReturnCodes flush(const std::string& sectionTag, const std::vector<std::string>& sectionContent); + EPlayerReturnCodes flush(const std::string& sectionTag, const std::vector<std::string>& sectionContent); - EPlayerReturnCodes initCommandCb(const std::vector<std::string>& sectionContent); - EPlayerReturnCodes resetCommandCb(const std::vector<std::string>& sectionContent); - EPlayerReturnCodes loadKernelCommandCb(const std::vector<std::string>& sectionContent); - EPlayerReturnCodes loadScenarioCommandCb(const std::vector<std::string>& sectionContent); - EPlayerReturnCodes setupScenarioCommandCb(const std::vector<std::string>& sectionContent); - EPlayerReturnCodes runScenarioCommandCb(const std::vector<std::string>& sectionContent); + EPlayerReturnCodes initCommandCb(const std::vector<std::string>& sectionContent); + EPlayerReturnCodes resetCommandCb(const std::vector<std::string>& sectionContent); + EPlayerReturnCodes loadKernelCommandCb(const std::vector<std::string>& sectionContent); + EPlayerReturnCodes loadScenarioCommandCb(const std::vector<std::string>& sectionContent); + EPlayerReturnCodes setupScenarioCommandCb(const std::vector<std::string>& sectionContent); + EPlayerReturnCodes runScenarioCommandCb(const std::vector<std::string>& sectionContent); - std::string m_cmdFile; - std::vector<std::shared_ptr<SCommand>> m_cmdList; - std::map<std::string, CallbackType> m_callbacks; - }; -} // namespace OpenViBE + std::string m_cmdFile; + std::vector<std::shared_ptr<SCommand>> m_cmdList; + std::map<std::string, CallbackType> m_callbacks; +}; +} // namespace OpenViBE diff --git a/applications/developer-tools/scenario-player/src/ovspCCommandLineOptionParser.cpp b/applications/developer-tools/scenario-player/src/ovspCCommandLineOptionParser.cpp index 54a3edb1eafc958d693b6712f31fbaaaa5f4366a..efa1ebdec332a83776dd7fc36e8f55dabaa36532 100644 --- a/applications/developer-tools/scenario-player/src/ovspCCommandLineOptionParser.cpp +++ b/applications/developer-tools/scenario-player/src/ovspCCommandLineOptionParser.cpp @@ -22,108 +22,107 @@ #include "ovspCCommand.h" #include "ovspCCommandLineOptionParser.h" -namespace OpenViBE +namespace OpenViBE { +CommandLineOptionParser::CommandLineOptionParser(ProgramOptionParser& parser) : m_parser(parser) { } + +void CommandLineOptionParser::initialize() { } // nothing to do +void CommandLineOptionParser::uninitialize() { m_cmdList.clear(); } + +std::vector<std::shared_ptr<SCommand>> CommandLineOptionParser::getCommandList() const { return m_cmdList; } + +EPlayerReturnCodes CommandLineOptionParser::parse() { - CommandLineOptionParser::CommandLineOptionParser(ProgramOptionParser& parser) : m_parser(parser) { } + // parsing consists of building a straightfoward command workflow according to command-line + // options. - void CommandLineOptionParser::initialize() { } // nothing to do - void CommandLineOptionParser::uninitialize() { m_cmdList.clear(); } + // commands have to be pushed in the right order - std::vector<std::shared_ptr<SCommand>> CommandLineOptionParser::getCommandList() const { return m_cmdList; } + // choose a dumb name for the scenario + std::string scenarioName = "express-scenario"; - EPlayerReturnCodes CommandLineOptionParser::parse() - { - // parsing consists of building a straightfoward command workflow according to command-line - // options. + // an init command is always needed + m_cmdList.push_back(std::make_shared<SInitCmd>()); - // commands have to be pushed in the right order - // choose a dumb name for the scenario - std::string scenarioName = "express-scenario"; + // workflow must at least load the kernel + std::shared_ptr<SLoadKernelCmd> kernelCmd = std::make_shared<SLoadKernelCmd>(); - // an init command is always needed - m_cmdList.push_back(std::make_shared<SInitCmd>()); + if (m_parser.hasOption("config-file")) // optional + { + kernelCmd->configFile = m_parser.getOptionValue<std::string>("config-file"); + } + m_cmdList.push_back(kernelCmd); - // workflow must at least load the kernel - std::shared_ptr<SLoadKernelCmd> kernelCmd = std::make_shared<SLoadKernelCmd>(); + // scenario loading is a mandatory step + std::shared_ptr<SLoadScenarioCmd> scenarioCmd = std::make_shared<SLoadScenarioCmd>(); - if (m_parser.hasOption("config-file")) // optional - { - kernelCmd->configFile = m_parser.getOptionValue<std::string>("config-file"); - } + if (m_parser.hasOption("scenario-file")) // mandatory option + { + scenarioCmd->scenarioFile = m_parser.getOptionValue<std::string>("scenario-file"); - m_cmdList.push_back(kernelCmd); + // set dumb name as it used to recognize scenario in the application + scenarioCmd->scenarioName = scenarioName; + } + else + { + std::cerr << "ERROR: mandatory option 'scenario-file' not set" << std::endl; + return EPlayerReturnCodes::MissingMandatoryArgument; + } - // scenario loading is a mandatory step - std::shared_ptr<SLoadScenarioCmd> scenarioCmd = std::make_shared<SLoadScenarioCmd>(); + m_cmdList.push_back(scenarioCmd); - if (m_parser.hasOption("scenario-file")) // mandatory option - { - scenarioCmd->scenarioFile = m_parser.getOptionValue<std::string>("scenario-file"); - // set dumb name as it used to recognize scenario in the application - scenarioCmd->scenarioName = scenarioName; - } - else - { - std::cerr << "ERROR: mandatory option 'scenario-file' not set" << std::endl; - return EPlayerReturnCodes::MissingMandatoryArgument; - } + // scenario update option + std::shared_ptr<SUpdateScenarioCmd> updateScenarioCmd = std::make_shared<SUpdateScenarioCmd>(); - m_cmdList.push_back(scenarioCmd); + if (m_parser.hasOption("updated-scenario-file")) + { + // do not play scenario, just update it. + updateScenarioCmd->scenarioFile = m_parser.getOptionValue<std::string>("updated-scenario-file"); - - // scenario update option - std::shared_ptr<SUpdateScenarioCmd> updateScenarioCmd = std::make_shared<SUpdateScenarioCmd>(); + // set dumb name as it used to recognize scenario in the application + updateScenarioCmd->scenarioName = scenarioName; - if (m_parser.hasOption("updated-scenario-file")) + m_cmdList.push_back(updateScenarioCmd); + } + else + { + // check if some scenario setup information has been set + if (m_parser.hasOption("ds")) { - // do not play scenario, just update it. - updateScenarioCmd->scenarioFile = m_parser.getOptionValue<std::string>("updated-scenario-file"); - - // set dumb name as it used to recognize scenario in the application - updateScenarioCmd->scenarioName = scenarioName; + std::shared_ptr<SSetupScenarioCmd> setupCmd = std::make_shared<SSetupScenarioCmd>(); + setupCmd->scenarioName = scenarioName; + setupCmd->tokenList = m_parser.getOptionValue<std::vector<SSetupScenarioCmd::Token>>("ds"); - m_cmdList.push_back(updateScenarioCmd); + m_cmdList.push_back(setupCmd); } - else - { - // check if some scenario setup information has been set - if (m_parser.hasOption("ds")) - { - std::shared_ptr<SSetupScenarioCmd> setupCmd = std::make_shared<SSetupScenarioCmd>(); - setupCmd->scenarioName = scenarioName; - setupCmd->tokenList = m_parser.getOptionValue<std::vector<SSetupScenarioCmd::Token>>("ds"); - m_cmdList.push_back(setupCmd); - } - - // last command in the workflow is the run command - std::shared_ptr<SRunScenarioCmd> runCmd = std::make_shared<SRunScenarioCmd>(); - runCmd->scenarioList = std::vector<std::string>{ scenarioName }; + // last command in the workflow is the run command + std::shared_ptr<SRunScenarioCmd> runCmd = std::make_shared<SRunScenarioCmd>(); + runCmd->scenarioList = std::vector<std::string>{ scenarioName }; + + if (m_parser.hasOption("play-mode")) + { + const auto playMode = m_parser.getOptionValue<std::string>("play-mode"); - if (m_parser.hasOption("play-mode")) + if (playMode != "ff" && playMode != "std") { - const auto playMode = m_parser.getOptionValue<std::string>("play-mode"); - - if (playMode != "ff" && playMode != "std") - { - std::cerr << "ERROR: option 'play-mode' must be ff or std" << std::endl; - return EPlayerReturnCodes::BadArg; - } - - // permissive code here - // any other entry than ff leads to standard mode... - runCmd->playMode = ((playMode == "ff") ? EPlayerPlayMode::Fastfoward : EPlayerPlayMode::Standard); + std::cerr << "ERROR: option 'play-mode' must be ff or std" << std::endl; + return EPlayerReturnCodes::BadArg; } - if (m_parser.hasOption("max-time")) { runCmd->maximumExecutionTime = m_parser.getOptionValue<double>("max-time"); } - if (m_parser.hasOption("dg")) { runCmd->tokenList = m_parser.getOptionValue<std::vector<SSetupScenarioCmd::Token>>("dg"); } - - m_cmdList.push_back(runCmd); + // permissive code here + // any other entry than ff leads to standard mode... + runCmd->playMode = ((playMode == "ff") ? EPlayerPlayMode::Fastfoward : EPlayerPlayMode::Standard); } - return EPlayerReturnCodes::Success; + if (m_parser.hasOption("max-time")) { runCmd->maximumExecutionTime = m_parser.getOptionValue<double>("max-time"); } + if (m_parser.hasOption("dg")) { runCmd->tokenList = m_parser.getOptionValue<std::vector<SSetupScenarioCmd::Token>>("dg"); } + + m_cmdList.push_back(runCmd); } + + return EPlayerReturnCodes::Success; +} } // namespace OpenViBE diff --git a/applications/developer-tools/scenario-player/src/ovspCCommandLineOptionParser.h b/applications/developer-tools/scenario-player/src/ovspCCommandLineOptionParser.h index 01984ec39f4273405ca48663690fd368e9ecf693..62695c2fd45640a3ec5465749bb53c32948c367e 100644 --- a/applications/developer-tools/scenario-player/src/ovspCCommandLineOptionParser.h +++ b/applications/developer-tools/scenario-player/src/ovspCCommandLineOptionParser.h @@ -24,41 +24,40 @@ #include "ovsp_defines.h" #include "ovspICommandParser.h" -namespace OpenViBE +namespace OpenViBE { +/** +* \class CommandLineOptionParser +* \author cgarraud (INRIA) +* \date 2016-01-27 +* \brief Parser implementation that parses command from command-line arguments +* \ingroup ScenarioPlayer +* +* The current implementation retrieves the options from a ProgramOptions parser and +* simply builds the commands from the parsed options. +* +*/ +class CommandLineOptionParser final : public ICommandParser { +public: + /** - * \class CommandLineOptionParser - * \author cgarraud (INRIA) - * \date 2016-01-27 - * \brief Parser implementation that parses command from command-line arguments - * \ingroup ScenarioPlayer * - * The current implementation retrieves the options from a ProgramOptions parser and - * simply builds the commands from the parsed options. + * \brief Constructor + * \param[in] parser Specific instantiation of ProgramOptions parser * */ - class CommandLineOptionParser final : public ICommandParser - { - public: - - /** - * - * \brief Constructor - * \param[in] parser Specific instantiation of ProgramOptions parser - * - */ - explicit CommandLineOptionParser(ProgramOptionParser& parser); + explicit CommandLineOptionParser(ProgramOptionParser& parser); - void initialize() override; - void uninitialize() override; + void initialize() override; + void uninitialize() override; - std::vector<std::shared_ptr<SCommand>> getCommandList() const override; + std::vector<std::shared_ptr<SCommand>> getCommandList() const override; - EPlayerReturnCodes parse() override; + EPlayerReturnCodes parse() override; - private: +private: - ProgramOptionParser& m_parser; - std::vector<std::shared_ptr<SCommand>> m_cmdList; - }; + ProgramOptionParser& m_parser; + std::vector<std::shared_ptr<SCommand>> m_cmdList; +}; } // namespace OpenViBE diff --git a/applications/developer-tools/scenario-player/src/ovspCKernelFacade.cpp b/applications/developer-tools/scenario-player/src/ovspCKernelFacade.cpp index ff94ce0005f610df6754554ea15e2022e3612e9b..8087e4c8e4015526043b946d83a8225e0c6a7a2a 100755 --- a/applications/developer-tools/scenario-player/src/ovspCKernelFacade.cpp +++ b/applications/developer-tools/scenario-player/src/ovspCKernelFacade.cpp @@ -37,13 +37,12 @@ using namespace /*OpenViBE::*/Plugins; using TokenList = std::vector<std::pair<std::string, std::string>>; -namespace +namespace { +void setConfigTokens(IConfigurationManager& configsManager, const TokenList& tokens) { - void setConfigTokens(IConfigurationManager& configsManager, const TokenList& tokens) - { - for (auto& token : tokens) { configsManager.addOrReplaceConfigurationToken(token.first.c_str(), token.second.c_str()); } - } -} // namespace + for (auto& token : tokens) { configsManager.addOrReplaceConfigurationToken(token.first.c_str(), token.second.c_str()); } +} +} // namespace struct CKernelFacade::SKernelFacadeImpl { diff --git a/applications/developer-tools/scenario-player/src/ovspCKernelFacade.h b/applications/developer-tools/scenario-player/src/ovspCKernelFacade.h index b4fe485fa417b2dddbb341cf380e26af8260e470..e48d79b053af1d6144b66d35a028e7d36a777d84 100755 --- a/applications/developer-tools/scenario-player/src/ovspCKernelFacade.h +++ b/applications/developer-tools/scenario-player/src/ovspCKernelFacade.h @@ -24,87 +24,86 @@ #include "ovsp_defines.h" #include <memory> -namespace OpenViBE +namespace OpenViBE { +struct SInitCmd; +struct SResetCmd; +struct SLoadKernelCmd; +struct SLoadScenarioCmd; +struct SUpdateScenarioCmd; +struct SSetupScenarioCmd; +struct SRunScenarioCmd; + +/** +* \class CKernelFacade +* \author cgarraud (INRIA) +* \date 2016-01-26 +* \brief Wrapper class used to access Kernel features +* \ingroup ScenarioPlayer +* +* This class is one-to-many interface used as a central point +* to access a subset of Kernel features. +* +*/ +class CKernelFacade final { - struct SInitCmd; - struct SResetCmd; - struct SLoadKernelCmd; - struct SLoadScenarioCmd; - struct SUpdateScenarioCmd; - struct SSetupScenarioCmd; - struct SRunScenarioCmd; +public: + + CKernelFacade(); + ~CKernelFacade(); + + /** + * \brief Initialize session parameters + */ + static EPlayerReturnCodes initialize() { return EPlayerReturnCodes::Success; } /** - * \class CKernelFacade - * \author cgarraud (INRIA) - * \date 2016-01-26 - * \brief Wrapper class used to access Kernel features - * \ingroup ScenarioPlayer - * - * This class is one-to-many interface used as a central point - * to access a subset of Kernel features. - * + * \brief Reset session parameters */ - class CKernelFacade final - { - public: - - CKernelFacade(); - ~CKernelFacade(); - - /** - * \brief Initialize session parameters - */ - static EPlayerReturnCodes initialize() { return EPlayerReturnCodes::Success; } - - /** - * \brief Reset session parameters - */ - static EPlayerReturnCodes uninitialize() { return EPlayerReturnCodes::Success; } - - /** - * \brief Load kernel - * \param[in] command command containing all mandatory properties - */ - EPlayerReturnCodes loadKernel(const SLoadKernelCmd& command) const; - - /** - * \brief Unload kernel - */ - EPlayerReturnCodes unloadKernel() const; - - /** - * \brief Load scenario - * \param[in] command command containing all mandatory properties - */ - EPlayerReturnCodes loadScenario(const SLoadScenarioCmd& command) const; - - /** - * \brief Update scenario - * \param[in] command command containing all mandatory properties - */ - EPlayerReturnCodes updateScenario(const SUpdateScenarioCmd& command) const; - - /** - * \brief Configure scenario - * \param[in] command command containing all mandatory properties - */ - EPlayerReturnCodes setupScenario(const SSetupScenarioCmd& command) const; - - /** - * \brief Run one or multiple scenarios - * \param[in] command command containing all mandatory properties - */ - EPlayerReturnCodes runScenarioList(const SRunScenarioCmd& command) const; - - private: - - // disable copy and assignment because it is not meant to used - // as a value class event if it is not inheritable - CKernelFacade(const CKernelFacade&) = delete; - CKernelFacade& operator=(const CKernelFacade&) = delete; - - struct SKernelFacadeImpl; - std::unique_ptr<SKernelFacadeImpl> m_impl; - }; + static EPlayerReturnCodes uninitialize() { return EPlayerReturnCodes::Success; } + + /** + * \brief Load kernel + * \param[in] command command containing all mandatory properties + */ + EPlayerReturnCodes loadKernel(const SLoadKernelCmd& command) const; + + /** + * \brief Unload kernel + */ + EPlayerReturnCodes unloadKernel() const; + + /** + * \brief Load scenario + * \param[in] command command containing all mandatory properties + */ + EPlayerReturnCodes loadScenario(const SLoadScenarioCmd& command) const; + + /** + * \brief Update scenario + * \param[in] command command containing all mandatory properties + */ + EPlayerReturnCodes updateScenario(const SUpdateScenarioCmd& command) const; + + /** + * \brief Configure scenario + * \param[in] command command containing all mandatory properties + */ + EPlayerReturnCodes setupScenario(const SSetupScenarioCmd& command) const; + + /** + * \brief Run one or multiple scenarios + * \param[in] command command containing all mandatory properties + */ + EPlayerReturnCodes runScenarioList(const SRunScenarioCmd& command) const; + +private: + + // disable copy and assignment because it is not meant to used + // as a value class event if it is not inheritable + CKernelFacade(const CKernelFacade&) = delete; + CKernelFacade& operator=(const CKernelFacade&) = delete; + + struct SKernelFacadeImpl; + std::unique_ptr<SKernelFacadeImpl> m_impl; +}; } // namespace OpenViBE diff --git a/applications/developer-tools/scenario-player/src/ovspICommand.h b/applications/developer-tools/scenario-player/src/ovspICommand.h index 5f24c7e0d1caab45ccd000f72648d7fa86f57cd3..84136cad6a62942a1863132e853ca1ff5a335792 100644 --- a/applications/developer-tools/scenario-player/src/ovspICommand.h +++ b/applications/developer-tools/scenario-player/src/ovspICommand.h @@ -23,51 +23,50 @@ #include "ovsp_defines.h" -namespace OpenViBE +namespace OpenViBE { +class CKernelFacade; + +/** +* \struct SCommand +* \author cgarraud (INRIA) +* \date 2016-01-26 +* \brief Base abstract struct for commands +* \ingroup ScenarioPlayer +* +* A command is an object that encapsulates all necessary information to perform an action later one. +* Typically, a command implementation should contain an implementation of CommandInterface interface, +* and a list of properties. +* +*/ +struct SCommand { - class CKernelFacade; + SCommand() = default; + virtual ~SCommand() = default; + + friend std::ostream& operator<<(std::ostream& os, const SCommand& cmd); /** - * \struct SCommand - * \author cgarraud (INRIA) - * \date 2016-01-26 - * \brief Base abstract struct for commands - * \ingroup ScenarioPlayer - * - * A command is an object that encapsulates all necessary information to perform an action later one. - * Typically, a command implementation should contain an implementation of CommandInterface interface, - * and a list of properties. - * + * \brief Execute the command + * \param[in] kernelFacade the kernel facade that gives access to kernel features */ - struct SCommand - { - SCommand() = default; - virtual ~SCommand() = default; - - friend std::ostream& operator<<(std::ostream& os, const SCommand& cmd); + virtual EPlayerReturnCodes execute(CKernelFacade& kernelFacade) const = 0; - /** - * \brief Execute the command - * \param[in] kernelFacade the kernel facade that gives access to kernel features - */ - virtual EPlayerReturnCodes execute(CKernelFacade& kernelFacade) const = 0; +protected: - protected: + // use of the non-virtual interface pattern to implement printing in the class hierarchy + virtual void doPrint(std::ostream& os) const = 0; - // use of the non-virtual interface pattern to implement printing in the class hierarchy - virtual void doPrint(std::ostream& os) const = 0; +private: - private: + // disable copy and assignment because it is not meant to used + // as a value class + SCommand(const SCommand&) = delete; + SCommand& operator=(const SCommand&) = delete; +}; - // disable copy and assignment because it is not meant to used - // as a value class - SCommand(const SCommand&) = delete; - SCommand& operator=(const SCommand&) = delete; - }; - - inline std::ostream& operator<<(std::ostream& os, const SCommand& cmd) - { - cmd.doPrint(os); - return os; - } +inline std::ostream& operator<<(std::ostream& os, const SCommand& cmd) +{ + cmd.doPrint(os); + return os; +} } // namespace OpenViBE diff --git a/applications/developer-tools/scenario-player/src/ovspICommandParser.h b/applications/developer-tools/scenario-player/src/ovspICommandParser.h index e54e2c86889bc4982d611550d8af828d8c56db14..62e3c473798f487b3340da213156aa37591f38a3 100644 --- a/applications/developer-tools/scenario-player/src/ovspICommandParser.h +++ b/applications/developer-tools/scenario-player/src/ovspICommandParser.h @@ -25,59 +25,58 @@ #include <vector> #include <memory> -namespace OpenViBE +namespace OpenViBE { +struct SCommand; + +/** +* \class ICommandParser +* \author cgarraud (INRIA) +* \date 2016-01-27 +* \brief Base abstract class for command parser +* \ingroup ScenarioPlayer +* +* Command parsers aim at parsing a list of commands from a specific input. +* +*/ +class ICommandParser { - struct SCommand; +public: + + virtual ~ICommandParser() = default; + ICommandParser() = default; /** - * \class ICommandParser - * \author cgarraud (INRIA) - * \date 2016-01-27 - * \brief Base abstract class for command parser - * \ingroup ScenarioPlayer - * - * Command parsers aim at parsing a list of commands from a specific input. + * \brief Initialize parser * */ - class ICommandParser - { - public: - - virtual ~ICommandParser() = default; - ICommandParser() = default; + virtual void initialize() = 0; - /** - * \brief Initialize parser - * - */ - virtual void initialize() = 0; - - /** - * \brief Unitialize parser - * - */ - virtual void uninitialize() = 0; + /** + * \brief Unitialize parser + * + */ + virtual void uninitialize() = 0; - /** - * \brief Retrieve the list of commands - * \pre This method should be called after the parse() method - * - */ - virtual std::vector<std::shared_ptr<SCommand>> getCommandList() const = 0; + /** + * \brief Retrieve the list of commands + * \pre This method should be called after the parse() method + * + */ + virtual std::vector<std::shared_ptr<SCommand>> getCommandList() const = 0; - /** - * \brief Retrieve the list of commands - * \pre This method should be called after the initialize() method - * - */ - virtual EPlayerReturnCodes parse() = 0; + /** + * \brief Retrieve the list of commands + * \pre This method should be called after the initialize() method + * + */ + virtual EPlayerReturnCodes parse() = 0; - private: +private: - // disable copy and assignment because it is not meant to used - // as a value class - ICommandParser(const ICommandParser&) = delete; - ICommandParser& operator=(const ICommandParser&) = delete; - }; + // disable copy and assignment because it is not meant to used + // as a value class + ICommandParser(const ICommandParser&) = delete; + ICommandParser& operator=(const ICommandParser&) = delete; +}; } // namespace OpenViBE diff --git a/applications/developer-tools/scenario-player/src/ovspTProgramOptions.hpp b/applications/developer-tools/scenario-player/src/ovspTProgramOptions.hpp index b09a9a719c3a1fc066750328f991bbb1cacc9667..1ecfcaf0b99485ed4c8be1e49a2990fa8c693daf 100644 --- a/applications/developer-tools/scenario-player/src/ovspTProgramOptions.hpp +++ b/applications/developer-tools/scenario-player/src/ovspTProgramOptions.hpp @@ -34,430 +34,428 @@ #include <Windows.h> #endif -namespace OpenViBE +namespace OpenViBE { +/** +* \struct SProgramOptionsTraits +* \author cgarraud (INRIA) +* \date 2016-01-26 +* \brief Helper class for ProgramOptions type checking +* \ingroup ScenarioPlayer +* +* This class provides aliases to types currently handled by ProgramOptions class +* as well as type checking meta-programming features. +* +*/ +struct SProgramOptionsTraits +{ + // add a new type here (type must be default constructible) + // and add the corresponding callback in ProgramOptions + + // types handled by ProgramOptions + using TokenPair = std::pair<std::string, std::string>; + using String = std::string; + using Integer = int; + using Float = double; + + using StringList = std::vector<std::string>; + using IntegerList = std::vector<int>; + using FloatList = std::vector<double>; + using TokenPairList = std::vector<TokenPair>; +}; + +namespace ProgramOptionsUtils { +// template meta-programming features + +/* Base type that represents a true value at compile-time */ +struct STrueType +{ + static const bool value = true; +}; + +/* Base type that represents a false value at compile-time */ +struct SFalseType +{ + static const bool value = false; +}; + +/* SIsCompliant is used to statically check if a type is compliant with the handled types */ +template <typename T> +struct SIsCompliant : SFalseType { }; + +/* Specialization of the template for compliant types */ +template <> +struct SIsCompliant<SProgramOptionsTraits::TokenPair> : STrueType {}; + +/* Specialization of the template for compliant types */ +template <> +struct SIsCompliant<SProgramOptionsTraits::TokenPairList> : STrueType {}; + +/* Specialization of the template for compliant types */ +template <> +struct SIsCompliant<SProgramOptionsTraits::String> : STrueType {}; + +/* Specialization of the template for compliant types */ +template <> +struct SIsCompliant<SProgramOptionsTraits::StringList> : STrueType {}; + +/* Specialization of the template for compliant types */ +template <> +struct SIsCompliant<SProgramOptionsTraits::Integer> : STrueType {}; + +/* Specialization of the template for compliant types */ +template <> +struct SIsCompliant<SProgramOptionsTraits::IntegerList> : STrueType {}; + +/* Specialization of the template for compliant types */ +template <> +struct SIsCompliant<SProgramOptionsTraits::Float> : STrueType {}; + +/* Specialization of the template for compliant types */ +template <> +struct SIsCompliant<SProgramOptionsTraits::FloatList> : STrueType {}; + +/* SIsSignatureCompliant is used to statically checked a list of type is compliant with handled type */ +template <typename... TList> +struct SIsSignatureCompliant; + +/* Specialization for empty list */ +template <> +struct SIsSignatureCompliant<> : STrueType {}; + +/* Specialization for non-empty list */ +template <typename THead, typename... TTail> +struct SIsSignatureCompliant<THead, TTail...> : + std::conditional<SIsCompliant<THead>::value, SIsSignatureCompliant<TTail...>, SFalseType>::type { }; + +/* SIsIn is used to statically check if a type T is in a list of types TList*/ +template <typename T, typename... TList> +struct SIsIn; // interface + +/* Specialization for empty list */ +template <typename T> +struct SIsIn<T> : SFalseType {}; + +/* Specialization for list where 1st element is a match */ +template <typename T, typename... TTail> +struct SIsIn<T, T, TTail...> : STrueType {}; + +/* Specialization for list of many elements */ +template <typename T, typename THead, typename... TTail> +struct SIsIn<T, THead, TTail...> : SIsIn<T, TTail...> {}; + +/* SHasDuplicate is used to statically check if a list of types has duplicates*/ +template <typename... TList> +struct SHasDuplicate; + +/* Specialization for empty list */ +template <> +struct SHasDuplicate<> : SFalseType {}; + +/* Specialization for 1-element list */ +template <typename T> +struct SHasDuplicate<T> : SFalseType {}; + +/* Specialization for list of many elements */ +template <typename THead, typename... TTail> +struct SHasDuplicate<THead, TTail...> : std::conditional<SIsIn<THead, TTail...>::value, STrueType, SHasDuplicate<TTail...>>::type { }; +} // namespace ProgramOptionsUtils + +/** +* \class ProgramOptions +* \author cgarraud (INRIA) +* \date 2016-01-25 +* \brief Command-line options parser +* \ingroup ScenarioPlayer +* +* This class is a basic class used to parse program options. +* Input format requirements: +* - Option prefix must be '-' or '--' e.g. cmd -help or --help +* - Option value assignment must be set with '=': e.g. cmd -config=myfile.txt +* - Option value that consists of pair are set with (): e.g. cmd -newToken=(key,value) +* . +* +* Template parameters are the list of option types that can be handled by the class. +* This list of options must comply to types defined in ProgramOptionsTrait.\n +* +* Parsing options occurs in 2 steps: +* - Populating the list of possible options with simple options (e.g. --help) and value options (e.g. --option=value) +* - Parsing options from command line +* . +* +* \todo The parser has only be tested for the player use. It needs more in-depth testing +* to be used in another context. Moreover, it should be extended to accept any type. +* +* \note The implementation is trivial. Prefer the use of robust and fully featured +* boost program_options compiled library if possible. +* +*/ +template <typename TFirst, typename... TTypes> +class ProgramOptions final { +public: + + // static assert are used to raise understandable errors at compile time + static_assert(!ProgramOptionsUtils::SHasDuplicate<TFirst, TTypes...>::value, "Duplicates in the type list"); + static_assert(ProgramOptionsUtils::SIsSignatureCompliant<TFirst, TTypes...>::value, "TTypes not handled by ProgramOptions"); + /** - * \struct SProgramOptionsTraits - * \author cgarraud (INRIA) - * \date 2016-01-26 - * \brief Helper class for ProgramOptions type checking - * \ingroup ScenarioPlayer - * - * This class provides aliases to types currently handled by ProgramOptions class - * as well as type checking meta-programming features. - * + * Struct used to store used-defined option parameters. */ - struct SProgramOptionsTraits + struct SOptionDesc // using a struct allows more extensibility than method parameters { - // add a new type here (type must be default constructible) - // and add the corresponding callback in ProgramOptions - - // types handled by ProgramOptions - using TokenPair = std::pair<std::string, std::string>; - using String = std::string; - using Integer = int; - using Float = double; - - using StringList = std::vector<std::string>; - using IntegerList = std::vector<int>; - using FloatList = std::vector<double>; - using TokenPairList = std::vector<TokenPair>; + /** Option shortname (e.g. h for help) */ + std::string shortName; + /** Option description used for printing option list */ + std::string desc; }; - namespace ProgramOptionsUtils - { - // template meta-programming features - - /* Base type that represents a true value at compile-time */ - struct STrueType - { - static const bool value = true; - }; - - /* Base type that represents a false value at compile-time */ - struct SFalseType - { - static const bool value = false; - }; - - /* SIsCompliant is used to statically check if a type is compliant with the handled types */ - template <typename T> - struct SIsCompliant : SFalseType { }; - - /* Specialization of the template for compliant types */ - template <> - struct SIsCompliant<SProgramOptionsTraits::TokenPair> : STrueType {}; - - /* Specialization of the template for compliant types */ - template <> - struct SIsCompliant<SProgramOptionsTraits::TokenPairList> : STrueType {}; - - /* Specialization of the template for compliant types */ - template <> - struct SIsCompliant<SProgramOptionsTraits::String> : STrueType {}; - - /* Specialization of the template for compliant types */ - template <> - struct SIsCompliant<SProgramOptionsTraits::StringList> : STrueType {}; - - /* Specialization of the template for compliant types */ - template <> - struct SIsCompliant<SProgramOptionsTraits::Integer> : STrueType {}; - - /* Specialization of the template for compliant types */ - template <> - struct SIsCompliant<SProgramOptionsTraits::IntegerList> : STrueType {}; - - /* Specialization of the template for compliant types */ - template <> - struct SIsCompliant<SProgramOptionsTraits::Float> : STrueType {}; - - /* Specialization of the template for compliant types */ - template <> - struct SIsCompliant<SProgramOptionsTraits::FloatList> : STrueType {}; - - /* SIsSignatureCompliant is used to statically checked a list of type is compliant with handled type */ - template <typename... TList> - struct SIsSignatureCompliant; - - /* Specialization for empty list */ - template <> - struct SIsSignatureCompliant<> : STrueType {}; - - /* Specialization for non-empty list */ - template <typename THead, typename... TTail> - struct SIsSignatureCompliant<THead, TTail...> : - std::conditional<SIsCompliant<THead>::value, SIsSignatureCompliant<TTail...>, SFalseType>::type { }; - - /* SIsIn is used to statically check if a type T is in a list of types TList*/ - template <typename T, typename... TList> - struct SIsIn; // interface - - /* Specialization for empty list */ - template <typename T> - struct SIsIn<T> : SFalseType {}; - - /* Specialization for list where 1st element is a match */ - template <typename T, typename... TTail> - struct SIsIn<T, T, TTail...> : STrueType {}; + /** + * \brief Add global description to the list of options + * \param[in] desc the global description in printable format + * + * The global description is used as additional printable documentation + * when printOptionsDesc() is called. + * + */ + void setGlobalDesc(const std::string& desc); - /* Specialization for list of many elements */ - template <typename T, typename THead, typename... TTail> - struct SIsIn<T, THead, TTail...> : SIsIn<T, TTail...> {}; + /** + * \brief Add a simple option to the internal dictionary + * \param[in] name the option name + * \param[in] optionDesc the option description + * + * Simple options are option withou value (e.g. --help or --version) + * + */ + void addSimpleOption(const std::string& name, const SOptionDesc& optionDesc); - /* SHasDuplicate is used to statically check if a list of types has duplicates*/ - template <typename... TList> - struct SHasDuplicate; - /* Specialization for empty list */ - template <> - struct SHasDuplicate<> : SFalseType {}; + /** + * \brief Add a value option to the internal dictionary + * \param[in] name the option name + * \param[in] optionDesc the option description + * + * Template paramter T: The type of the option to be added + */ + template <typename T> + void addValueOption(const std::string& name, const SOptionDesc& optionDesc); - /* Specialization for 1-element list */ - template <typename T> - struct SHasDuplicate<T> : SFalseType {}; + /** + * \brief Parse command line options + * \pre addSimpleOption and addValueOption must be called to populate options dictionary + * \param[in] argc number of arguments + * \param[in] argv pointer to the list of arguments + * \return: false if an error occurred during parsing, true otherwise + */ + bool parse(int argc, char** argv); - /* Specialization for list of many elements */ - template <typename THead, typename... TTail> - struct SHasDuplicate<THead, TTail...> : std::conditional<SIsIn<THead, TTail...>::value, STrueType, SHasDuplicate<TTail...>>::type { }; - } // namespace ProgramOptionsUtils + /** + * \brief Check if an option was parsed or not + * \pre Must be called after parse() + * \param[in] name the option name + * \return: true if the option was parsed, false otherwise + */ + bool hasOption(const std::string& name) const; /** - * \class ProgramOptions - * \author cgarraud (INRIA) - * \date 2016-01-25 - * \brief Command-line options parser - * \ingroup ScenarioPlayer - * - * This class is a basic class used to parse program options. - * Input format requirements: - * - Option prefix must be '-' or '--' e.g. cmd -help or --help - * - Option value assignment must be set with '=': e.g. cmd -config=myfile.txt - * - Option value that consists of pair are set with (): e.g. cmd -newToken=(key,value) - * . - * - * Template parameters are the list of option types that can be handled by the class. - * This list of options must comply to types defined in ProgramOptionsTrait.\n - * - * Parsing options occurs in 2 steps: - * - Populating the list of possible options with simple options (e.g. --help) and value options (e.g. --option=value) - * - Parsing options from command line - * . - * - * \todo The parser has only be tested for the player use. It needs more in-depth testing - * to be used in another context. Moreover, it should be extended to accept any type. - * - * \note The implementation is trivial. Prefer the use of robust and fully featured - * boost program_options compiled library if possible. + * \brief Get option value + * \pre hasOption() should be called to ensure the option is available + * \param[in] name the option name + * \return the option value (will be the default value if the option was not parsed) * + * Template paramter T: the type of the option to retrieve (must match the type used to set + * the option with addValueOption()) */ - template <typename TFirst, typename... TTypes> - class ProgramOptions final - { - public: + template <typename T> + T getOptionValue(const std::string& name) const; - // static assert are used to raise understandable errors at compile time - static_assert(!ProgramOptionsUtils::SHasDuplicate<TFirst, TTypes...>::value, "Duplicates in the type list"); - static_assert(ProgramOptionsUtils::SIsSignatureCompliant<TFirst, TTypes...>::value, "TTypes not handled by ProgramOptions"); - /** - * Struct used to store used-defined option parameters. - */ - struct SOptionDesc // using a struct allows more extensibility than method parameters - { - /** Option shortname (e.g. h for help) */ - std::string shortName; - /** Option description used for printing option list */ - std::string desc; - }; - - /** - * \brief Add global description to the list of options - * \param[in] desc the global description in printable format - * - * The global description is used as additional printable documentation - * when printOptionsDesc() is called. - * - */ - void setGlobalDesc(const std::string& desc); - - /** - * \brief Add a simple option to the internal dictionary - * \param[in] name the option name - * \param[in] optionDesc the option description - * - * Simple options are option withou value (e.g. --help or --version) - * - */ - void addSimpleOption(const std::string& name, const SOptionDesc& optionDesc); - - - /** - * \brief Add a value option to the internal dictionary - * \param[in] name the option name - * \param[in] optionDesc the option description - * - * Template paramter T: The type of the option to be added - */ - template <typename T> - void addValueOption(const std::string& name, const SOptionDesc& optionDesc); - - /** - * \brief Parse command line options - * \pre addSimpleOption and addValueOption must be called to populate options dictionary - * \param[in] argc number of arguments - * \param[in] argv pointer to the list of arguments - * \return: false if an error occurred during parsing, true otherwise - */ - bool parse(int argc, char** argv); - - /** - * \brief Check if an option was parsed or not - * \pre Must be called after parse() - * \param[in] name the option name - * \return: true if the option was parsed, false otherwise - */ - bool hasOption(const std::string& name) const; - - /** - * \brief Get option value - * \pre hasOption() should be called to ensure the option is available - * \param[in] name the option name - * \return the option value (will be the default value if the option was not parsed) - * - * Template paramter T: the type of the option to retrieve (must match the type used to set - * the option with addValueOption()) - */ - template <typename T> - T getOptionValue(const std::string& name) const; - - - /** - * \brief print all option descriptions - */ - void printOptionsDesc() const; + /** + * \brief print all option descriptions + */ + void printOptionsDesc() const; - private: +private: - // The visitor allows us to apply the correct parsing - // for any type (see boost::variant documentation for more details). - // Presently, it is pretty ugly. This should be refactored for - // as there is a lot of behavorial redundancy. - class OptionVisitor : public boost::static_visitor<> - { - public: + // The visitor allows us to apply the correct parsing + // for any type (see boost::variant documentation for more details). + // Presently, it is pretty ugly. This should be refactored for + // as there is a lot of behavorial redundancy. + class OptionVisitor : public boost::static_visitor<> + { + public: - OptionVisitor(std::string& value) : m_value(value) { } + OptionVisitor(std::string& value) : m_value(value) { } - void operator()(SProgramOptionsTraits::Integer& operand) const { operand = std::stoi(m_value); } - void operator()(SProgramOptionsTraits::Float& operand) const { operand = std::stod(m_value); } - void operator()(SProgramOptionsTraits::String& operand) const { operand = m_value; } - void operator()(SProgramOptionsTraits::TokenPair& operand) const { operand = this->parsePair(m_value); } - void operator()(SProgramOptionsTraits::IntegerList& operand) const { operand.push_back(std::stoi(m_value)); } - void operator()(SProgramOptionsTraits::FloatList& operand) const { operand.push_back(std::stod(m_value)); } - void operator()(SProgramOptionsTraits::StringList& operand) const { operand.push_back(m_value); } - void operator()(SProgramOptionsTraits::TokenPairList& operand) const { operand.push_back(this->parsePair(m_value)); } + void operator()(SProgramOptionsTraits::Integer& operand) const { operand = std::stoi(m_value); } + void operator()(SProgramOptionsTraits::Float& operand) const { operand = std::stod(m_value); } + void operator()(SProgramOptionsTraits::String& operand) const { operand = m_value; } + void operator()(SProgramOptionsTraits::TokenPair& operand) const { operand = this->parsePair(m_value); } + void operator()(SProgramOptionsTraits::IntegerList& operand) const { operand.push_back(std::stoi(m_value)); } + void operator()(SProgramOptionsTraits::FloatList& operand) const { operand.push_back(std::stod(m_value)); } + void operator()(SProgramOptionsTraits::StringList& operand) const { operand.push_back(m_value); } + void operator()(SProgramOptionsTraits::TokenPairList& operand) const { operand.push_back(this->parsePair(m_value)); } - private: + private: - static SProgramOptionsTraits::TokenPair parsePair(const std::string& str); + static SProgramOptionsTraits::TokenPair parsePair(const std::string& str); - std::string& m_value; - }; + std::string& m_value; + }; - using OptionValue = boost::variant<TFirst, TTypes...>; + using OptionValue = boost::variant<TFirst, TTypes...>; - // the pair contais a boolean to quickly know if an option - // is a simple option or a value option - using FullOptionDesc = std::pair<bool, SOptionDesc>; + // the pair contais a boolean to quickly know if an option + // is a simple option or a value option + using FullOptionDesc = std::pair<bool, SOptionDesc>; - std::string m_globalDesc; - std::map<std::string, FullOptionDesc> m_descs; - std::map<std::string, OptionValue> m_values; - std::vector<std::string> m_options; - }; + std::string m_globalDesc; + std::map<std::string, FullOptionDesc> m_descs; + std::map<std::string, OptionValue> m_values; + std::vector<std::string> m_options; +}; - /////////////////////////////////////////// - /////// Definition ProgramOptions ///////// - /////////////////////////////////////////// +/////////////////////////////////////////// +/////// Definition ProgramOptions ///////// +/////////////////////////////////////////// - template <typename TFirst, typename... TTypes> - void ProgramOptions<TFirst, TTypes...>::setGlobalDesc(const std::string& desc) { m_globalDesc = desc; } +template <typename TFirst, typename... TTypes> +void ProgramOptions<TFirst, TTypes...>::setGlobalDesc(const std::string& desc) { m_globalDesc = desc; } - template <typename TFirst, typename... TTypes> - void ProgramOptions<TFirst, TTypes...>::addSimpleOption(const std::string& name, const SOptionDesc& optionDesc) - { - m_descs[name] = std::make_pair(true, optionDesc); - } +template <typename TFirst, typename... TTypes> +void ProgramOptions<TFirst, TTypes...>::addSimpleOption(const std::string& name, const SOptionDesc& optionDesc) +{ + m_descs[name] = std::make_pair(true, optionDesc); +} - template <typename TFirst, typename... TTypes> - template <typename T> - void ProgramOptions<TFirst, TTypes...>::addValueOption(const std::string& name, const SOptionDesc& optionDesc) - { - m_descs[name] = std::make_pair(false, optionDesc); +template <typename TFirst, typename... TTypes> +template <typename T> +void ProgramOptions<TFirst, TTypes...>::addValueOption(const std::string& name, const SOptionDesc& optionDesc) +{ + m_descs[name] = std::make_pair(false, optionDesc); - T defaultValue{}; // with this implementation, only default constructible type can be added - m_values[name] = defaultValue; - } + T defaultValue{}; // with this implementation, only default constructible type can be added + m_values[name] = defaultValue; +} - template <typename TFirst, typename... TTypes> - bool ProgramOptions<TFirst, TTypes...>::hasOption(const std::string& name) const - { - return std::find(m_options.begin(), m_options.end(), name) != m_options.end(); - } +template <typename TFirst, typename... TTypes> +bool ProgramOptions<TFirst, TTypes...>::hasOption(const std::string& name) const +{ + return std::find(m_options.begin(), m_options.end(), name) != m_options.end(); +} - template <typename TFirst, typename... TTypes> - template <typename T> - T ProgramOptions<TFirst, TTypes...>::getOptionValue(const std::string& name) const - { - T value{}; +template <typename TFirst, typename... TTypes> +template <typename T> +T ProgramOptions<TFirst, TTypes...>::getOptionValue(const std::string& name) const +{ + T value{}; - try { value = boost::get<T>(m_values.at(name)); } - catch (const std::exception& e) { std::cerr << "ERROR: Caught exception during option value retrieval: " << e.what() << std::endl; } + try { value = boost::get<T>(m_values.at(name)); } + catch (const std::exception& e) { std::cerr << "ERROR: Caught exception during option value retrieval: " << e.what() << std::endl; } - return value; - } + return value; +} - template <typename TFirst, typename... TTypes> - bool ProgramOptions<TFirst, TTypes...>::parse(const int argc, char** argv) - { - std::vector<std::string> args; +template <typename TFirst, typename... TTypes> +bool ProgramOptions<TFirst, TTypes...>::parse(const int argc, char** argv) +{ + std::vector<std::string> args; #if defined TARGET_OS_Windows - int nArg; - LPWSTR* argListUtf16 = CommandLineToArgvW(GetCommandLineW(), &nArg); - std::wstring_convert<std::codecvt_utf8<wchar_t>> converter; - for (int i = 0; i < nArg; ++i) { args.push_back(converter.to_bytes(argListUtf16[i])); } + int nArg; + LPWSTR* argListUtf16 = CommandLineToArgvW(GetCommandLineW(), &nArg); + std::wstring_convert<std::codecvt_utf8<wchar_t>> converter; + for (int i = 0; i < nArg; ++i) { args.push_back(converter.to_bytes(argListUtf16[i])); } #else args = std::vector<std::string>(argv, argv + argc); #endif - for (int i = 1; i < argc; ++i) + for (int i = 1; i < argc; ++i) + { + std::string arg = args[i]; + const auto argSplit = arg.find_first_of('='); // = is the separator for value option + std::string key; + + if (argSplit == std::string::npos) { key = arg; } // simple option + else { key = arg.substr(0, argSplit); } // value option + + // first check if the key exists + auto keyMatch = std::find_if(m_descs.begin(), m_descs.end(), [&](const std::pair<std::string, FullOptionDesc>& p) + { + const auto& desc = p.second.second; + return (("-" + p.first) == key) || (("--" + p.first) == key) || (("-" + desc.shortName) == key) || ( + ("--" + desc.shortName) == key); + } + ); + + if (keyMatch == m_descs.end()) + { + std::cout << "WARNING: Found unknown option: " << key << std::endl; + std::cout << "Skipping..." << std::endl; + continue; + } + + if (!keyMatch->second.first) // value option { - std::string arg = args[i]; - const auto argSplit = arg.find_first_of('='); // = is the separator for value option - std::string key; - - if (argSplit == std::string::npos) { key = arg; } // simple option - else { key = arg.substr(0, argSplit); } // value option - - // first check if the key exists - auto keyMatch = std::find_if(m_descs.begin(), m_descs.end(), [&](const std::pair<std::string, FullOptionDesc>& p) - { - const auto& desc = p.second.second; - return (("-" + p.first) == key) || (("--" + p.first) == key) || (("-" + desc.shortName) == key) || ( - ("--" + desc.shortName) == key); - } - ); - - if (keyMatch == m_descs.end()) + if (key == arg) { - std::cout << "WARNING: Found unknown option: " << key << std::endl; - std::cout << "Skipping..." << std::endl; - continue; + std::cerr << "ERROR: No value set for argument: " << key << std::endl; + return false; } - if (!keyMatch->second.first) // value option + std::string val = arg.substr(argSplit + 1, arg.size() - argSplit - 1); // take value part of the arg + + try { boost::apply_visitor(OptionVisitor(val), m_values[keyMatch->first]); } + catch (const std::exception& e) { - if (key == arg) - { - std::cerr << "ERROR: No value set for argument: " << key << std::endl; - return false; - } - - std::string val = arg.substr(argSplit + 1, arg.size() - argSplit - 1); // take value part of the arg - - try { boost::apply_visitor(OptionVisitor(val), m_values[keyMatch->first]); } - catch (const std::exception& e) - { - std::cerr << "ERROR: Caught exception during option parsing: " << e.what() << std::endl; - std::cerr << "Could not parse option with key = " << key << " and value = " << val << std::endl; - return false; - } + std::cerr << "ERROR: Caught exception during option parsing: " << e.what() << std::endl; + std::cerr << "Could not parse option with key = " << key << " and value = " << val << std::endl; + return false; } - - m_options.push_back(keyMatch->first); } - - return true; + m_options.push_back(keyMatch->first); } - template <typename TFirst, typename... TTypes> - void ProgramOptions<TFirst, TTypes...>::printOptionsDesc() const - { - if (!m_globalDesc.empty()) { std::cout << m_globalDesc << std::endl; } - std::cout << "TList of available options:\n" << std::endl; + return true; +} - for (auto& option : m_descs) - { - std::cout << "Option: --" << option.first << std::endl; - const auto& desc = option.second.second; - if (!desc.shortName.empty()) { std::cout << "Shortname: --" << desc.shortName << std::endl; } - std::cout << "Description: " << std::endl; - std::cout << desc.desc << std::endl << std::endl; - } - } +template <typename TFirst, typename... TTypes> +void ProgramOptions<TFirst, TTypes...>::printOptionsDesc() const +{ + if (!m_globalDesc.empty()) { std::cout << m_globalDesc << std::endl; } - /////////////////////////////////////////// - /////// Definition Internal Visitor /////// - /////////////////////////////////////////// + std::cout << "TList of available options:\n" << std::endl; - template <typename TFirst, typename... TTypes> - SProgramOptionsTraits::TokenPair ProgramOptions<TFirst, TTypes...>::OptionVisitor::parsePair(const std::string& str) + for (auto& option : m_descs) { - const auto split = str.find_first_of(':'); - const auto size = str.size(); + std::cout << "Option: --" << option.first << std::endl; + const auto& desc = option.second.second; + if (!desc.shortName.empty()) { std::cout << "Shortname: --" << desc.shortName << std::endl; } + std::cout << "Description: " << std::endl; + std::cout << desc.desc << std::endl << std::endl; + } +} - // (a:b) pattern expected - // minimal regex std::regex("\\(.+:.+\\)") - if (!(size >= 5 && str[0] == '(' && str[size - 1] == ')') || split == std::string::npos) - { - throw std::runtime_error("Failed to parse token pair from value: " + str); - } +/////////////////////////////////////////// +/////// Definition Internal Visitor /////// +/////////////////////////////////////////// + +template <typename TFirst, typename... TTypes> +SProgramOptionsTraits::TokenPair ProgramOptions<TFirst, TTypes...>::OptionVisitor::parsePair(const std::string& str) +{ + const auto split = str.find_first_of(':'); + const auto size = str.size(); - // magic 2 numbers is because substr takes a length as second parameter - // 2 = remove the last ) + account for the first one - return std::make_pair(str.substr(1, split - 1), str.substr(split + 1, size - split - 2)); + // (a:b) pattern expected + // minimal regex std::regex("\\(.+:.+\\)") + if (!(size >= 5 && str[0] == '(' && str[size - 1] == ')') || split == std::string::npos) + { + throw std::runtime_error("Failed to parse token pair from value: " + str); } -} // namespace OpenViBE + + // magic 2 numbers is because substr takes a length as second parameter + // 2 = remove the last ) + account for the first one + return std::make_pair(str.substr(1, split - 1), str.substr(split + 1, size - split - 2)); +} +} // namespace OpenViBE diff --git a/applications/developer-tools/scenario-player/src/ovsp_defines.h b/applications/developer-tools/scenario-player/src/ovsp_defines.h index 533a907c2745c055fcfe7113f6661a17e22e831f..6e8ae505f7c80424832645750b0a58cab916d36d 100644 --- a/applications/developer-tools/scenario-player/src/ovsp_defines.h +++ b/applications/developer-tools/scenario-player/src/ovsp_defines.h @@ -23,64 +23,63 @@ #include "ovspTProgramOptions.hpp" -namespace OpenViBE -{ - /** - * \defgroup ScenarioPlayer Scenario Player - */ +namespace OpenViBE { +/** +* \defgroup ScenarioPlayer Scenario Player +*/ - /** - * \class EPlayerReturnCodes - * \author cgarraud - * \date 2016-01-25 - * \brief Scenario player list of potential return code - * \ingroup ScenarioPlayer - */ - enum class EPlayerReturnCodes - { - Success = 0, ///< No error during execution */ - InvalidArg, ///< Invalid command-line options */ - MissingMandatoryArgument, ///< A mandatory argument is missing */ - BadArg, ///< An argument is given with a wrong value */ - OpeningFileFailure, ///< A file could not be opened */ - ParsingCommandFailure, ///< General parsing command error*/ - UnkownFailure, ///< Error of unknown type*/ - KernelLoadingFailure, ///< Kernel loading failed*/ - KernelInvalidDesc, ///< Invalid kernel descriptor*/ - KernelInvalidContext, ///< Invalid kernel context*/ - KernelInternalFailure, ///< Generic error type for kernel internal error*/ - ScenarioNotLoaded ///< Error triggered when an action is requested on an unknown scenario */ - }; +/** +* \class EPlayerReturnCodes +* \author cgarraud +* \date 2016-01-25 +* \brief Scenario player list of potential return code +* \ingroup ScenarioPlayer +*/ +enum class EPlayerReturnCodes +{ + Success = 0, ///< No error during execution */ + InvalidArg, ///< Invalid command-line options */ + MissingMandatoryArgument, ///< A mandatory argument is missing */ + BadArg, ///< An argument is given with a wrong value */ + OpeningFileFailure, ///< A file could not be opened */ + ParsingCommandFailure, ///< General parsing command error*/ + UnkownFailure, ///< Error of unknown type*/ + KernelLoadingFailure, ///< Kernel loading failed*/ + KernelInvalidDesc, ///< Invalid kernel descriptor*/ + KernelInvalidContext, ///< Invalid kernel context*/ + KernelInternalFailure, ///< Generic error type for kernel internal error*/ + ScenarioNotLoaded ///< Error triggered when an action is requested on an unknown scenario */ +}; - /** - * \class EPlayerPlayMode - * \author cgarraud - * \date 2016-01-25 - * \brief Way of playing a scenario - * \ingroup ScenarioPlayer - */ - enum class EPlayerPlayMode { Standard = 0, Fastfoward }; +/** +* \class EPlayerPlayMode +* \author cgarraud +* \date 2016-01-25 +* \brief Way of playing a scenario +* \ingroup ScenarioPlayer +*/ +enum class EPlayerPlayMode { Standard = 0, Fastfoward }; - /* Define the common parser to be used in the application */ - using ProgramOptionParser = ProgramOptions<SProgramOptionsTraits::String, SProgramOptionsTraits::Float, SProgramOptionsTraits::TokenPairList>; +/* Define the common parser to be used in the application */ +using ProgramOptionParser = ProgramOptions<SProgramOptionsTraits::String, SProgramOptionsTraits::Float, SProgramOptionsTraits::TokenPairList>; - inline std::string toString(const EPlayerReturnCodes code) +inline std::string toString(const EPlayerReturnCodes code) +{ + switch (code) { - switch (code) - { - case EPlayerReturnCodes::Success: return "Success"; - case EPlayerReturnCodes::InvalidArg: return "Invalid Arg"; - case EPlayerReturnCodes::MissingMandatoryArgument: return "Missing Mandatory Argument"; - case EPlayerReturnCodes::BadArg: return "Bad Arg"; - case EPlayerReturnCodes::OpeningFileFailure: return "Opening File Failure"; - case EPlayerReturnCodes::ParsingCommandFailure: return "Parsing Command Failure"; - case EPlayerReturnCodes::UnkownFailure: return "Unkown Failure"; - case EPlayerReturnCodes::KernelLoadingFailure: return "Kernel Loading Failure"; - case EPlayerReturnCodes::KernelInvalidDesc: return "Kernel Invalid Desc"; - case EPlayerReturnCodes::KernelInvalidContext: return "Kernel Invalid Context"; - case EPlayerReturnCodes::KernelInternalFailure: return "Kernel Internal Failure"; - case EPlayerReturnCodes::ScenarioNotLoaded: return "Scenario Not Loaded"; - default: return "Invalid Code"; - } + case EPlayerReturnCodes::Success: return "Success"; + case EPlayerReturnCodes::InvalidArg: return "Invalid Arg"; + case EPlayerReturnCodes::MissingMandatoryArgument: return "Missing Mandatory Argument"; + case EPlayerReturnCodes::BadArg: return "Bad Arg"; + case EPlayerReturnCodes::OpeningFileFailure: return "Opening File Failure"; + case EPlayerReturnCodes::ParsingCommandFailure: return "Parsing Command Failure"; + case EPlayerReturnCodes::UnkownFailure: return "Unkown Failure"; + case EPlayerReturnCodes::KernelLoadingFailure: return "Kernel Loading Failure"; + case EPlayerReturnCodes::KernelInvalidDesc: return "Kernel Invalid Desc"; + case EPlayerReturnCodes::KernelInvalidContext: return "Kernel Invalid Context"; + case EPlayerReturnCodes::KernelInternalFailure: return "Kernel Internal Failure"; + case EPlayerReturnCodes::ScenarioNotLoaded: return "Scenario Not Loaded"; + default: return "Invalid Code"; } +} } // namespace OpenViBE diff --git a/applications/examples/external-processing/CMakeLists.txt b/applications/examples/external-processing/CMakeLists.txt index 394317d98f8589a3cd47bf584f2693fb1239f588..dd29736266aafafd93cfd2ba7fd221f07a9b67b0 100644 --- a/applications/examples/external-processing/CMakeLists.txt +++ b/applications/examples/external-processing/CMakeLists.txt @@ -1,9 +1,9 @@ PROJECT(sdk-examples-communication-client-generator) SET(SRC_FILES src/main-generator.cpp) - ADD_EXECUTABLE(${PROJECT_NAME} ${SRC_FILES}) ADD_DEPENDENCIES(${PROJECT_NAME} openvibe-toolkit) +SET_PROPERTY(TARGET ${PROJECT_NAME} PROPERTY FOLDER ${APP_FOLDER}) INCLUDE("FindOpenViBE") INCLUDE("FindOpenViBECommon") @@ -21,8 +21,8 @@ INSTALL(TARGETS ${PROJECT_NAME} PROJECT(sdk-examples-communication-client-filter) SET(SRC_FILES src/main-filter.cpp) - ADD_EXECUTABLE(${PROJECT_NAME} ${SRC_FILES}) +SET_PROPERTY(TARGET ${PROJECT_NAME} PROPERTY FOLDER ${APP_FOLDER}) INCLUDE("FindOpenViBE") INCLUDE("FindOpenViBECommon") diff --git a/applications/examples/external-processing/src/main-filter.cpp b/applications/examples/external-processing/src/main-filter.cpp index 27f1b92750aa1b7b396a7431c9788c2e8f19876f..ed456aaed75124724f4d0468dbac2cdd7351aecb 100644 --- a/applications/examples/external-processing/src/main-filter.cpp +++ b/applications/examples/external-processing/src/main-filter.cpp @@ -130,7 +130,6 @@ int main(const int argc, char** argv) { while (client.popEBML(packetId, index, startTime, endtime, ebml)) { - // We just push out the received EBML as is if (!client.pushEBML(index, startTime, endtime, ebml)) { diff --git a/build-tool/stimulation-generator/CMakeLists.txt b/build-tool/stimulation-generator/CMakeLists.txt index 9a52d67a07e34f9ae757da091ac44d0f68507d59..e92f9089b68078334c98ffa5b3a4de2592cded25 100644 --- a/build-tool/stimulation-generator/CMakeLists.txt +++ b/build-tool/stimulation-generator/CMakeLists.txt @@ -18,8 +18,6 @@ ADD_EXECUTABLE(openvibe-stimulation-generator ${SRC_FILES}) # --------------------------------- # Target macros -# Defines target operating system -# Defines target architecture -# Defines target compiler +# Defines target operating system, architecture and compiler # --------------------------------- SET_BUILD_PLATFORM() diff --git a/build-tool/stimulation-generator/src/ovbt_sg_cpp_code_generator.cpp b/build-tool/stimulation-generator/src/ovbt_sg_cpp_code_generator.cpp index ad9a941388d80dd925669ae5574f3b5f4725558c..20ac01cbe2e74d84be514c92bd7cd7c2b9431a12 100644 --- a/build-tool/stimulation-generator/src/ovbt_sg_cpp_code_generator.cpp +++ b/build-tool/stimulation-generator/src/ovbt_sg_cpp_code_generator.cpp @@ -20,14 +20,12 @@ bool CCppCodeGenerator::openFile(const char* filename) return true; } - bool CCppCodeGenerator::appendStimulation(SStimulation& stim) { m_file << "\ttypeManager.registerEnumerationEntry(OV_TypeId_Stimulation, \"" << stim.name << "\", " << stim.id << ");" << endl; return true; } - bool CCppCodeGenerator::closeFile() { m_file << endl << "\treturn true;" << endl << "}" << endl; diff --git a/build-tool/stimulation-generator/src/ovbt_sg_cpp_define_generator.cpp b/build-tool/stimulation-generator/src/ovbt_sg_cpp_define_generator.cpp index 91844ff4501fa8dd6c0f918d6e2e413213375ba6..3e0b29c338a0fa4c7e664cf6208f7456882a92fb 100644 --- a/build-tool/stimulation-generator/src/ovbt_sg_cpp_define_generator.cpp +++ b/build-tool/stimulation-generator/src/ovbt_sg_cpp_define_generator.cpp @@ -13,14 +13,12 @@ bool CCppDefineGenerator::openFile(const char* filename) return true; } - bool CCppDefineGenerator::appendStimulation(SStimulation& stim) { m_file << "#define " << stim.id << " " << stim.hexa << endl; return true; } - bool CCppDefineGenerator::closeFile() { m_file << endl; diff --git a/build-tool/stimulation-generator/src/ovbt_sg_main.cpp b/build-tool/stimulation-generator/src/ovbt_sg_main.cpp index 24ab8301e16f45050eff2b1b9949ee4efa48fdd5..457ff1575191892db6e70b69e94d086dbe557285 100644 --- a/build-tool/stimulation-generator/src/ovbt_sg_main.cpp +++ b/build-tool/stimulation-generator/src/ovbt_sg_main.cpp @@ -9,7 +9,6 @@ using namespace std; enum class EGenerationTypes { CPP, MATLAB, PYTHON, LUA, UNKNOWN }; - EGenerationTypes parse_argument(string option) { if (option == "--cpp") { return EGenerationTypes::CPP; } @@ -86,7 +85,6 @@ int main(int argc, char** argv) //Now we generate all files that needs to be done for (auto& s : stimulations) { for (auto& g : generators) { g->appendStimulation(s); } } - for (auto& g : generators) { g->closeFile(); } return 0; diff --git a/build-tool/stimulation-generator/src/ovbt_sg_matlab_generator.cpp b/build-tool/stimulation-generator/src/ovbt_sg_matlab_generator.cpp index ec6ccbe423334bc3704037d23ddeba4b6f268d4c..b33960ab069e7bd5e285d883aa2cfece76f5abdf 100644 --- a/build-tool/stimulation-generator/src/ovbt_sg_matlab_generator.cpp +++ b/build-tool/stimulation-generator/src/ovbt_sg_matlab_generator.cpp @@ -4,7 +4,6 @@ using namespace std; - string getBrutHexaCode(string formatedHexaCode) { string res = formatedHexaCode; @@ -33,7 +32,6 @@ bool CMatlabGenerator::appendStimulation(SStimulation& stim) return true; } - bool CMatlabGenerator::closeFile() { m_file << "end" << endl; diff --git a/common/CMakeLists.txt b/common/CMakeLists.txt index 3a3355a2ddd8e5137be707dd19201aa74522a122..dd6d5ecafa25cd4ee86c52a6b1f631b353c9c95f 100755 --- a/common/CMakeLists.txt +++ b/common/CMakeLists.txt @@ -12,11 +12,14 @@ INCLUDE_DIRECTORIES(include) ADD_EXECUTABLE(${PROJECT_NAME} ${SRC_FILES}) INCLUDE("FindThirdPartyBoost") +SET_TARGET_PROPERTIES(${PROJECT_NAME} PROPERTIES + VERSION ${PROJECT_VERSION} + SOVERSION ${PROJECT_VERSION_MAJOR} + FOLDER ${KERNEL_FOLDER}) + # --------------------------------- # Target macros -# Defines target operating system -# Defines target architecture -# Defines target compiler +# Defines target operating system, architecture and compiler # --------------------------------- SET_BUILD_PLATFORM() diff --git a/common/include/m_ConverterUtf8.h b/common/include/m_ConverterUtf8.h index d1d06f31e669728f3c09e7b0e5470d71b78b8bc8..e4628ef9b0f83b5893aa7979565dcd2b4610ca3b 100644 --- a/common/include/m_ConverterUtf8.h +++ b/common/include/m_ConverterUtf8.h @@ -66,5 +66,5 @@ static std::wstring Utf8ToUtf16(const std::string& utf8) } #endif // TARGET_OS_Windows -} // namespace Converter -} // namespace Common +} // namespace Converter +} // namespace Common diff --git a/common/include/ovCResampler.h b/common/include/ovCResampler.h index a1f5acb424af1560c9a9b55859c0e7d106a8a6c5..9e41f50ad7ea94bc2eea9f3cf4731c9c93f68ed0 100644 --- a/common/include/ovCResampler.h +++ b/common/include/ovCResampler.h @@ -418,5 +418,5 @@ typedef TResampler<float, EResamplerStoreModes::ChannelWise> CDownsamplerCf; typedef TResampler<double, EResamplerStoreModes::SampleWise> CDownsamplerSd; typedef TResampler<double, EResamplerStoreModes::ChannelWise> CDownsamplerCd; -} // namespace Resampler -} // namespace Common +} // namespace Resampler +} // namespace Common diff --git a/common/include/ov_common_defines.h b/common/include/ov_common_defines.h index 684e7948fc8660b7ee30ab4b3e799ab23c33fbab..a38da6cbd4fe2cb5ddbdaa163d3b0152e29d54ed 100644 --- a/common/include/ov_common_defines.h +++ b/common/include/ov_common_defines.h @@ -118,14 +118,14 @@ #define OVP_API_Import #endif #else -#define OVP_API_Export -#define OVP_API_Import +# define OVP_API_Export +# define OVP_API_Import #endif #if defined OVP_Exports -#define OVP_API OVP_API_Export +# define OVP_API OVP_API_Export #else -#define OVP_API OVP_API_Import +# define OVP_API OVP_API_Import #endif //___________________________________________________________________// // // diff --git a/kernel/CMakeLists.txt b/kernel/CMakeLists.txt index fd147288b97fee1b06300dab03f222b345ec3714..687e5ba2d065d8b453205ed87b429fc78563cf6a 100755 --- a/kernel/CMakeLists.txt +++ b/kernel/CMakeLists.txt @@ -13,6 +13,7 @@ ADD_LIBRARY(${PROJECT_NAME} SHARED ${SRC_FILES}) SET_TARGET_PROPERTIES(${PROJECT_NAME} PROPERTIES VERSION ${PROJECT_VERSION} SOVERSION ${PROJECT_VERSION_MAJOR} + FOLDER ${KERNEL_FOLDER} COMPILE_FLAGS "-DOVK_Exports -DOVK_Shared") INCLUDE("FindOpenViBE") @@ -55,9 +56,7 @@ ENDIF(UNIX) # --------------------------------- # Target macros -# Defines target operating system -# Defines target architecture -# Defines target compiler +# Defines target operating system, architecture and compiler # --------------------------------- SET_BUILD_PLATFORM() diff --git a/kernel/src/kernel/algorithm/ovkCAlgorithmContext.h b/kernel/src/kernel/algorithm/ovkCAlgorithmContext.h index 5ae509b720e760c14b65d35fc5a41b11bee19ded..0c9df7f9e41d89219acea81ad4de8b1b73d8f720 100644 --- a/kernel/src/kernel/algorithm/ovkCAlgorithmContext.h +++ b/kernel/src/kernel/algorithm/ovkCAlgorithmContext.h @@ -3,50 +3,45 @@ #include "../ovkTKernelObject.h" #include "ovkCAlgorithmProxy.h" -namespace OpenViBE +namespace OpenViBE { +namespace Kernel { +class CAlgorithmContext final : public TKernelObject<IAlgorithmContext> { - namespace Kernel - { - class CAlgorithmContext final : public TKernelObject<IAlgorithmContext> - { - public: +public: - CAlgorithmContext(const IKernelContext& ctx, CAlgorithmProxy& algorithmProxy, const Plugins::IPluginObjectDesc& /*pluginObjectDesc*/) - : TKernelObject<IAlgorithmContext>(ctx), m_logManager(ctx.getLogManager()), m_algorithmProxy(algorithmProxy) {} + CAlgorithmContext(const IKernelContext& ctx, CAlgorithmProxy& algorithmProxy, const Plugins::IPluginObjectDesc& /*pluginObjectDesc*/) + : TKernelObject<IAlgorithmContext>(ctx), m_logManager(ctx.getLogManager()), m_algorithmProxy(algorithmProxy) {} - ~CAlgorithmContext() override { } - IConfigurationManager& getConfigurationManager() const override { return getKernelContext().getConfigurationManager(); } - IAlgorithmManager& getAlgorithmManager() const override { return getKernelContext().getAlgorithmManager(); } - ILogManager& getLogManager() const override { return m_logManager; } - IErrorManager& getErrorManager() const override { return getKernelContext().getErrorManager(); } - ITypeManager& getTypeManager() const override { return getKernelContext().getTypeManager(); } + ~CAlgorithmContext() override { } + IConfigurationManager& getConfigurationManager() const override { return getKernelContext().getConfigurationManager(); } + IAlgorithmManager& getAlgorithmManager() const override { return getKernelContext().getAlgorithmManager(); } + ILogManager& getLogManager() const override { return m_logManager; } + IErrorManager& getErrorManager() const override { return getKernelContext().getErrorManager(); } + ITypeManager& getTypeManager() const override { return getKernelContext().getTypeManager(); } - CIdentifier getNextInputParameterIdentifier(const CIdentifier& previous) const override - { - return m_algorithmProxy.getNextInputParameterIdentifier(previous); - } + CIdentifier getNextInputParameterIdentifier(const CIdentifier& previous) const override + { + return m_algorithmProxy.getNextInputParameterIdentifier(previous); + } - IParameter* getInputParameter(const CIdentifier& identifier) override { return m_algorithmProxy.getInputParameter(identifier); } + IParameter* getInputParameter(const CIdentifier& identifier) override { return m_algorithmProxy.getInputParameter(identifier); } - CIdentifier getNextOutputParameterIdentifier(const CIdentifier& previous) const override - { - return m_algorithmProxy.getNextOutputParameterIdentifier(previous); - } + CIdentifier getNextOutputParameterIdentifier(const CIdentifier& previous) const override + { + return m_algorithmProxy.getNextOutputParameterIdentifier(previous); + } - IParameter* getOutputParameter(const CIdentifier& identifier) override { return m_algorithmProxy.getOutputParameter(identifier); } - bool isInputTriggerActive(const CIdentifier& identifier) const override { return m_algorithmProxy.isInputTriggerActive(identifier); } + IParameter* getOutputParameter(const CIdentifier& identifier) override { return m_algorithmProxy.getOutputParameter(identifier); } + bool isInputTriggerActive(const CIdentifier& identifier) const override { return m_algorithmProxy.isInputTriggerActive(identifier); } - bool activateOutputTrigger(const CIdentifier& identifier, const bool state) override - { - return m_algorithmProxy.activateOutputTrigger(identifier, state); - } + bool activateOutputTrigger(const CIdentifier& identifier, const bool state) override { return m_algorithmProxy.activateOutputTrigger(identifier, state); } - _IsDerivedFromClass_Final_(TKernelObject<IAlgorithmContext>, OVK_ClassId_Kernel_Algorithm_AlgorithmContext) + _IsDerivedFromClass_Final_(TKernelObject<IAlgorithmContext>, OVK_ClassId_Kernel_Algorithm_AlgorithmContext) - protected: +protected: - ILogManager& m_logManager; - CAlgorithmProxy& m_algorithmProxy; - }; - } // namespace Kernel -} // namespace OpenViBE + ILogManager& m_logManager; + CAlgorithmProxy& m_algorithmProxy; +}; +} // namespace Kernel +} // namespace OpenViBE diff --git a/kernel/src/kernel/algorithm/ovkCAlgorithmManager.h b/kernel/src/kernel/algorithm/ovkCAlgorithmManager.h index 0a4f36a0c6618188900b9d6619a05bea0ddc4afe..27248f18d1c136a86bfbb701f65b089ae7326593 100755 --- a/kernel/src/kernel/algorithm/ovkCAlgorithmManager.h +++ b/kernel/src/kernel/algorithm/ovkCAlgorithmManager.h @@ -5,32 +5,30 @@ #include <map> #include <mutex> -namespace OpenViBE +namespace OpenViBE { +namespace Kernel { +class CAlgorithmProxy; + +class CAlgorithmManager final : public TKernelObject<IAlgorithmManager> { - namespace Kernel - { - class CAlgorithmProxy; - - class CAlgorithmManager final : public TKernelObject<IAlgorithmManager> - { - public: - - explicit CAlgorithmManager(const IKernelContext& ctx); - ~CAlgorithmManager() override; - CIdentifier createAlgorithm(const CIdentifier& algorithmClassID) override; - CIdentifier createAlgorithm(const Plugins::IAlgorithmDesc& algorithmDesc) override; - bool releaseAlgorithm(const CIdentifier& rAlgorithmIdentifier) override; - bool releaseAlgorithm(IAlgorithmProxy& rAlgorithm) override; - IAlgorithmProxy& getAlgorithm(const CIdentifier& rAlgorithmIdentifier) override; - CIdentifier getNextAlgorithmIdentifier(const CIdentifier& previousID) const override; - - _IsDerivedFromClass_Final_(TKernelObject<IAlgorithmManager>, OVK_ClassId_Kernel_Algorithm_AlgorithmManager) - - protected: - - CIdentifier getUnusedIdentifier() const; - std::map<CIdentifier, CAlgorithmProxy*> m_algorithms; - mutable std::mutex m_oMutex; - }; - } // namespace Kernel -} // namespace OpenViBE +public: + + explicit CAlgorithmManager(const IKernelContext& ctx); + ~CAlgorithmManager() override; + CIdentifier createAlgorithm(const CIdentifier& algorithmClassID) override; + CIdentifier createAlgorithm(const Plugins::IAlgorithmDesc& algorithmDesc) override; + bool releaseAlgorithm(const CIdentifier& rAlgorithmIdentifier) override; + bool releaseAlgorithm(IAlgorithmProxy& rAlgorithm) override; + IAlgorithmProxy& getAlgorithm(const CIdentifier& rAlgorithmIdentifier) override; + CIdentifier getNextAlgorithmIdentifier(const CIdentifier& previousID) const override; + + _IsDerivedFromClass_Final_(TKernelObject<IAlgorithmManager>, OVK_ClassId_Kernel_Algorithm_AlgorithmManager) + +protected: + + CIdentifier getUnusedIdentifier() const; + std::map<CIdentifier, CAlgorithmProxy*> m_algorithms; + mutable std::mutex m_oMutex; +}; +} // namespace Kernel +} // namespace OpenViBE diff --git a/kernel/src/kernel/algorithm/ovkCAlgorithmProto.cpp b/kernel/src/kernel/algorithm/ovkCAlgorithmProto.cpp index 2c6c40881de985778a6add2cec23e7bbb223a7fd..5f7ea3f6459016861a348de6817297254f54f0ad 100644 --- a/kernel/src/kernel/algorithm/ovkCAlgorithmProto.cpp +++ b/kernel/src/kernel/algorithm/ovkCAlgorithmProto.cpp @@ -7,7 +7,7 @@ using namespace /*OpenViBE::*/Kernel; CAlgorithmProto::CAlgorithmProto(const IKernelContext& ctx, CAlgorithmProxy& rAlgorithmProxy) : TKernelObject<IAlgorithmProto>(ctx), m_algorithmProxy(rAlgorithmProxy) {} -bool CAlgorithmProto::addInputParameter(const CIdentifier& inputParameterID, const CString& sInputName, +bool CAlgorithmProto::addInputParameter(const CIdentifier& inputParameterID, const CString& sInputName, const EParameterType eParameterType, const CIdentifier& subTypeID) { return m_algorithmProxy.addInputParameter(inputParameterID, sInputName, eParameterType, subTypeID); diff --git a/kernel/src/kernel/algorithm/ovkCAlgorithmProto.h b/kernel/src/kernel/algorithm/ovkCAlgorithmProto.h index c12f6aab8ba769032fc49e9907ca3179b8a55492..6720d470e343add256fd516dbeb4b18224b7b0f0 100644 --- a/kernel/src/kernel/algorithm/ovkCAlgorithmProto.h +++ b/kernel/src/kernel/algorithm/ovkCAlgorithmProto.h @@ -2,29 +2,27 @@ #include "../ovkTKernelObject.h" -namespace OpenViBE -{ - namespace Kernel - { - class CAlgorithmProxy; +namespace OpenViBE { +namespace Kernel { +class CAlgorithmProxy; - class CAlgorithmProto final : public TKernelObject<IAlgorithmProto> - { - public: +class CAlgorithmProto final : public TKernelObject<IAlgorithmProto> +{ +public: - CAlgorithmProto(const IKernelContext& ctx, CAlgorithmProxy& rAlgorithmProxy); - bool addInputParameter(const CIdentifier& inputParameterID, const CString& sInputName, EParameterType eParameterType, - const CIdentifier& subTypeID) override; - bool addOutputParameter(const CIdentifier& outputParameterID, const CString& sOutputName, EParameterType eParameterType, - const CIdentifier& subTypeID) override; - bool addInputTrigger(const CIdentifier& inputTriggerID, const CString& rInputTriggerName) override; - bool addOutputTrigger(const CIdentifier& outputTriggerID, const CString& rOutputTriggerName) override; + CAlgorithmProto(const IKernelContext& ctx, CAlgorithmProxy& rAlgorithmProxy); + bool addInputParameter(const CIdentifier& inputParameterID, const CString& sInputName, EParameterType eParameterType, + const CIdentifier& subTypeID) override; + bool addOutputParameter(const CIdentifier& outputParameterID, const CString& sOutputName, EParameterType eParameterType, + const CIdentifier& subTypeID) override; + bool addInputTrigger(const CIdentifier& inputTriggerID, const CString& rInputTriggerName) override; + bool addOutputTrigger(const CIdentifier& outputTriggerID, const CString& rOutputTriggerName) override; - _IsDerivedFromClass_Final_(TKernelObject<IAlgorithmProto>, OVK_ClassId_Kernel_Algorithm_AlgorithmProto) + _IsDerivedFromClass_Final_(TKernelObject<IAlgorithmProto>, OVK_ClassId_Kernel_Algorithm_AlgorithmProto) - protected: +protected: - CAlgorithmProxy& m_algorithmProxy; - }; - } // namespace Kernel -} // namespace OpenViBE + CAlgorithmProxy& m_algorithmProxy; +}; +} // namespace Kernel +} // namespace OpenViBE diff --git a/kernel/src/kernel/algorithm/ovkCAlgorithmProxy.h b/kernel/src/kernel/algorithm/ovkCAlgorithmProxy.h index 8645f4586ea9f7f7041bd55ad216ba548de30ca0..3a5dd1026cee7ce95acc0460802f0184d16858cf 100644 --- a/kernel/src/kernel/algorithm/ovkCAlgorithmProxy.h +++ b/kernel/src/kernel/algorithm/ovkCAlgorithmProxy.h @@ -4,75 +4,73 @@ #include <map> -namespace OpenViBE +namespace OpenViBE { +namespace Kernel { +class CAlgorithmProxy final : public TKernelObject<IAlgorithmProxy> { - namespace Kernel - { - class CAlgorithmProxy final : public TKernelObject<IAlgorithmProxy> - { - public: - - CAlgorithmProxy(const IKernelContext& ctx, Plugins::IAlgorithm& rAlgorithm, const Plugins::IAlgorithmDesc& algorithmDesc); - ~CAlgorithmProxy() override; - - Plugins::IAlgorithm& getAlgorithm(); - const Plugins::IAlgorithm& getAlgorithm() const; - const Plugins::IAlgorithmDesc& getAlgorithmDesc() const; - - bool addInputParameter(const CIdentifier& parameterID, const CString& name, EParameterType parameterType, const CIdentifier& subTypeID); - CIdentifier getNextInputParameterIdentifier(const CIdentifier& parameterID) const override; - IParameter* getInputParameter(const CIdentifier& parameterID) override; - EParameterType getInputParameterType(const CIdentifier& parameterID) const; - CString getInputParameterName(const CIdentifier& parameterID) const override; - bool removeInputParameter(const CIdentifier& parameterID); - - bool addOutputParameter(const CIdentifier& parameterID, const CString& name, EParameterType parameterType, const CIdentifier& subTypeID); - CIdentifier getNextOutputParameterIdentifier(const CIdentifier& parameterID) const override; - IParameter* getOutputParameter(const CIdentifier& parameterID) override; - EParameterType getOutputParameterType(const CIdentifier& parameterID) const; - CString getOutputParameterName(const CIdentifier& parameterID) const override; - bool removeOutputParameter(const CIdentifier& parameterID); - - bool addInputTrigger(const CIdentifier& triggerID, const CString& name); - CIdentifier getNextInputTriggerIdentifier(const CIdentifier& triggerID) const override; - CString getInputTriggerName(const CIdentifier& triggerID) const override; - bool isInputTriggerActive(const CIdentifier& triggerID) const; - bool activateInputTrigger(const CIdentifier& triggerID, bool triggerState) override; - bool removeInputTrigger(const CIdentifier& triggerID); - - bool addOutputTrigger(const CIdentifier& triggerID, const CString& name); - CIdentifier getNextOutputTriggerIdentifier(const CIdentifier& triggerID) const override; - CString getOutputTriggerName(const CIdentifier& triggerID) const override; - bool isOutputTriggerActive(const CIdentifier& triggerID) const override; - bool activateOutputTrigger(const CIdentifier& triggerID, const bool triggerState); - bool removeOutputTrigger(const CIdentifier& triggerID); - bool initialize() override; - bool uninitialize() override; - bool process() override; - bool process(const CIdentifier& triggerID) override; - bool isAlgorithmDerivedFrom(const CIdentifier& classID) override; - - _IsDerivedFromClass_Final_(TKernelObject<IAlgorithmProxy>, OVK_ClassId_Kernel_Algorithm_AlgorithmProxy) - - protected: - - IConfigurable* m_iConfigurable = nullptr; - IConfigurable* m_oConfigurable = nullptr; - std::map<CIdentifier, CString> m_iParameterNames; - std::map<CIdentifier, CString> m_oParameterNames; - std::map<CIdentifier, std::pair<CString, bool>> m_iTriggers; - std::map<CIdentifier, std::pair<CString, bool>> m_oTriggers; - - void setAllInputTriggers(bool status); - void setAllOutputTriggers(bool status); - - private: - - void handleException(const char* errorHint, const std::exception& exception); - - const Plugins::IAlgorithmDesc& m_algorithmDesc; - Plugins::IAlgorithm& m_algorithm; - bool m_isInitialized = false; - }; - } // namespace Kernel -} // namespace OpenViBE +public: + + CAlgorithmProxy(const IKernelContext& ctx, Plugins::IAlgorithm& rAlgorithm, const Plugins::IAlgorithmDesc& algorithmDesc); + ~CAlgorithmProxy() override; + + Plugins::IAlgorithm& getAlgorithm(); + const Plugins::IAlgorithm& getAlgorithm() const; + const Plugins::IAlgorithmDesc& getAlgorithmDesc() const; + + bool addInputParameter(const CIdentifier& parameterID, const CString& name, EParameterType parameterType, const CIdentifier& subTypeID); + CIdentifier getNextInputParameterIdentifier(const CIdentifier& parameterID) const override; + IParameter* getInputParameter(const CIdentifier& parameterID) override; + EParameterType getInputParameterType(const CIdentifier& parameterID) const; + CString getInputParameterName(const CIdentifier& parameterID) const override; + bool removeInputParameter(const CIdentifier& parameterID); + + bool addOutputParameter(const CIdentifier& parameterID, const CString& name, EParameterType parameterType, const CIdentifier& subTypeID); + CIdentifier getNextOutputParameterIdentifier(const CIdentifier& parameterID) const override; + IParameter* getOutputParameter(const CIdentifier& parameterID) override; + EParameterType getOutputParameterType(const CIdentifier& parameterID) const; + CString getOutputParameterName(const CIdentifier& parameterID) const override; + bool removeOutputParameter(const CIdentifier& parameterID); + + bool addInputTrigger(const CIdentifier& triggerID, const CString& name); + CIdentifier getNextInputTriggerIdentifier(const CIdentifier& triggerID) const override; + CString getInputTriggerName(const CIdentifier& triggerID) const override; + bool isInputTriggerActive(const CIdentifier& triggerID) const; + bool activateInputTrigger(const CIdentifier& triggerID, bool triggerState) override; + bool removeInputTrigger(const CIdentifier& triggerID); + + bool addOutputTrigger(const CIdentifier& triggerID, const CString& name); + CIdentifier getNextOutputTriggerIdentifier(const CIdentifier& triggerID) const override; + CString getOutputTriggerName(const CIdentifier& triggerID) const override; + bool isOutputTriggerActive(const CIdentifier& triggerID) const override; + bool activateOutputTrigger(const CIdentifier& triggerID, const bool triggerState); + bool removeOutputTrigger(const CIdentifier& triggerID); + bool initialize() override; + bool uninitialize() override; + bool process() override; + bool process(const CIdentifier& triggerID) override; + bool isAlgorithmDerivedFrom(const CIdentifier& classID) override; + + _IsDerivedFromClass_Final_(TKernelObject<IAlgorithmProxy>, OVK_ClassId_Kernel_Algorithm_AlgorithmProxy) + +protected: + + IConfigurable* m_iConfigurable = nullptr; + IConfigurable* m_oConfigurable = nullptr; + std::map<CIdentifier, CString> m_iParameterNames; + std::map<CIdentifier, CString> m_oParameterNames; + std::map<CIdentifier, std::pair<CString, bool>> m_iTriggers; + std::map<CIdentifier, std::pair<CString, bool>> m_oTriggers; + + void setAllInputTriggers(bool status); + void setAllOutputTriggers(bool status); + +private: + + void handleException(const char* errorHint, const std::exception& exception); + + const Plugins::IAlgorithmDesc& m_algorithmDesc; + Plugins::IAlgorithm& m_algorithm; + bool m_isInitialized = false; +}; +} // namespace Kernel +} // namespace OpenViBE diff --git a/kernel/src/kernel/configuration/ovkCConfigurationManager.cpp b/kernel/src/kernel/configuration/ovkCConfigurationManager.cpp index bd5b14195b10b9eb55a3d5a428d1f7fe85f03add..476e7114d264dfec938c64dac79d1b7217430be6 100755 --- a/kernel/src/kernel/configuration/ovkCConfigurationManager.cpp +++ b/kernel/src/kernel/configuration/ovkCConfigurationManager.cpp @@ -30,116 +30,113 @@ using namespace OpenViBE; using namespace /*OpenViBE::*/Kernel; using namespace /*OpenViBE::*/Plugins; -namespace -{ - // because std::tolower has multiple signatures, - // it can not be easily used in std::transform - // this workaround is taken from http://www.gcek.net/ref/books/sw/cpp/ticppv2/ - template <class TCharT> - TCharT ToLower(TCharT c) { return std::tolower(c); } -} // namespace - -namespace OpenViBE +namespace { +// because std::tolower has multiple signatures, +// it can not be easily used in std::transform +// this workaround is taken from http://www.gcek.net/ref/books/sw/cpp/ticppv2/ +template <class TCharT> +TCharT ToLower(TCharT c) { return std::tolower(c); } +} // namespace + +namespace OpenViBE { +namespace Kernel { +class CConfigurationManagerEntryEnumeratorCallBack final : public FS::IEntryEnumeratorCallBack { - namespace Kernel +public: + + CConfigurationManagerEntryEnumeratorCallBack(ILogManager& logManager, IErrorManager& errorManager, IConfigurationManager& configManger) + : m_logManager(logManager), m_errorManager(errorManager), m_configManager(configManger) { } + + static std::string reduce(const std::string& value) { - class CConfigurationManagerEntryEnumeratorCallBack final : public FS::IEntryEnumeratorCallBack - { - public: + if (value.length() == 0) { return ""; } - CConfigurationManagerEntryEnumeratorCallBack(ILogManager& logManager, IErrorManager& errorManager, IConfigurationManager& configManger) - : m_logManager(logManager), m_errorManager(errorManager), m_configManager(configManger) { } + size_t i = 0; + size_t j = value.length() - 1; - static std::string reduce(const std::string& value) - { - if (value.length() == 0) { return ""; } + while (i < value.length() && (value[i] == '\t' || value[i] == ' ')) { i++; } + while (j >= i && (value[j] == '\t' || value[j] == ' ')) { j--; } - size_t i = 0; - size_t j = value.length() - 1; + return value.substr(i, j - i + 1); + } - while (i < value.length() && (value[i] == '\t' || value[i] == ' ')) { i++; } - while (j >= i && (value[j] == '\t' || value[j] == ' ')) { j--; } + bool callback(FS::IEntryEnumerator::IEntry& rEntry, FS::IEntryEnumerator::IAttributes& /*attributes*/) override + { + std::ifstream file; + FS::Files::openIFStream(file, rEntry.getName()); - return value.substr(i, j - i + 1); - } + OV_ERROR_UNLESS(file.good(), "Could not open file " << rEntry.getName(), ErrorType::ResourceNotFound, false, m_errorManager, m_logManager); + m_logManager << LogLevel_Trace << "Processing configuration file " << rEntry.getName() << "\n"; - bool callback(FS::IEntryEnumerator::IEntry& rEntry, FS::IEntryEnumerator::IAttributes& /*attributes*/) override + do + { + std::string line; + std::string linePart; + size_t eq; + + while (!file.eof() && (line.length() == 0 || line[line.length() - 1] == '\\')) { - std::ifstream file; - FS::Files::openIFStream(file, rEntry.getName()); + while (line.length() != 0 && line[line.length() - 1] == '\\') + { + line.resize(line.length() - 1); // removes ending backslashes + } - OV_ERROR_UNLESS(file.good(), "Could not open file " << rEntry.getName(), ErrorType::ResourceNotFound, false, m_errorManager, m_logManager); - m_logManager << LogLevel_Trace << "Processing configuration file " << rEntry.getName() << "\n"; + std::getline(file, linePart, '\n'); + line += reduce(linePart); + } - do - { - std::string line; - std::string linePart; - size_t eq; + // process everything except empty line or comment + if (!line.empty() && line[0] != '\0' && line[0] != '#') + { + OV_ERROR_UNLESS((eq=line.find('=')) != std::string::npos, + "Invalid syntax in configuration file " << CString(rEntry.getName()) << " : " << line, + ErrorType::BadFileParsing, false, m_errorManager, m_logManager); - while (!file.eof() && (line.length() == 0 || line[line.length() - 1] == '\\')) + std::string name(reduce(line.substr(0, eq))); + std::string value(reduce(line.substr(eq + 1, line.length() - eq))); + if (name == "Include") + { + CString wildCard = m_configManager.expand(value.c_str()); + m_logManager << LogLevel_Trace << "Including configuration file " << wildCard << "...\n"; + m_configManager.addConfigurationFromFile(wildCard); + m_logManager << LogLevel_Trace << "Including configuration file " << wildCard << " done...\n"; + } + else + { + CIdentifier tokenID = m_configManager.lookUpConfigurationTokenIdentifier(name.c_str()); + if (tokenID == OV_UndefinedIdentifier) { - while (line.length() != 0 && line[line.length() - 1] == '\\') - { - line.resize(line.length() - 1); // removes ending backslashes - } - - std::getline(file, linePart, '\n'); - line += reduce(linePart); + m_logManager << LogLevel_Trace << "Adding configuration token " << name << " : " << value << "\n"; + m_configManager.createConfigurationToken(name.c_str(), value.c_str()); } - - // process everything except empty line or comment - if (!line.empty() && line[0] != '\0' && line[0] != '#') + else { - OV_ERROR_UNLESS((eq=line.find('=')) != std::string::npos, - "Invalid syntax in configuration file " << CString(rEntry.getName()) << " : " << line, - ErrorType::BadFileParsing, false, m_errorManager, m_logManager); + m_logManager << LogLevel_Trace << "Changing configuration token " << name << " to " << value << "\n"; - std::string name(reduce(line.substr(0, eq))); - std::string value(reduce(line.substr(eq + 1, line.length() - eq))); - if (name == "Include") - { - CString wildCard = m_configManager.expand(value.c_str()); - m_logManager << LogLevel_Trace << "Including configuration file " << wildCard << "...\n"; - m_configManager.addConfigurationFromFile(wildCard); - m_logManager << LogLevel_Trace << "Including configuration file " << wildCard << " done...\n"; - } - else - { - CIdentifier tokenID = m_configManager.lookUpConfigurationTokenIdentifier(name.c_str()); - if (tokenID == OV_UndefinedIdentifier) - { - m_logManager << LogLevel_Trace << "Adding configuration token " << name << " : " << value << "\n"; - m_configManager.createConfigurationToken(name.c_str(), value.c_str()); - } - else - { - m_logManager << LogLevel_Trace << "Changing configuration token " << name << " to " << value << "\n"; - - // warning if base token are overwritten here - OV_WARNING_UNLESS(name != "Path_UserData" && name != "Path_Log" && name != "Path_Tmp" - && name != "Path_Lib" && name != "Path_Bin" && name != "OperatingSystem", - "Overwriting critical token " + name, m_logManager); - - m_configManager.setConfigurationTokenValue(tokenID, value.c_str()); - } - } + // warning if base token are overwritten here + OV_WARNING_UNLESS(name != "Path_UserData" && name != "Path_Log" && name != "Path_Tmp" + && name != "Path_Lib" && name != "Path_Bin" && name != "OperatingSystem", + "Overwriting critical token " + name, m_logManager); + + m_configManager.setConfigurationTokenValue(tokenID, value.c_str()); } - } while (!file.eof()); + } + } + } while (!file.eof()); - m_logManager << LogLevel_Trace << "Processing configuration file " << CString(rEntry.getName()) << " finished\n"; + m_logManager << LogLevel_Trace << "Processing configuration file " << CString(rEntry.getName()) << " finished\n"; - return true; - } + return true; + } - protected: +protected: - ILogManager& m_logManager; - IErrorManager& m_errorManager; - IConfigurationManager& m_configManager; - }; - } // namespace Kernel -} // namespace OpenViBE + ILogManager& m_logManager; + IErrorManager& m_errorManager; + IConfigurationManager& m_configManager; +}; +} // namespace Kernel +} // namespace OpenViBE CConfigurationManager::CConfigurationManager(const IKernelContext& ctx, IConfigurationManager* parentConfigManager) : TKernelObject<IConfigurationManager>(ctx), m_parentConfigManager(parentConfigManager) diff --git a/kernel/src/kernel/configuration/ovkCConfigurationManager.h b/kernel/src/kernel/configuration/ovkCConfigurationManager.h index 5717425805fa7d7421518b5e1ceb338efdb74651..a3b058e21ce2f35556e683222e74143ba1c2c298 100755 --- a/kernel/src/kernel/configuration/ovkCConfigurationManager.h +++ b/kernel/src/kernel/configuration/ovkCConfigurationManager.h @@ -6,71 +6,69 @@ #include <string> #include <mutex> -namespace OpenViBE -{ - namespace Kernel - { - class IConfigurationKeywordExpandCallback; +namespace OpenViBE { +namespace Kernel { +class IConfigurationKeywordExpandCallback; - typedef struct - { - CString name; - CString value; - } config_token_t; +typedef struct +{ + CString name; + CString value; +} config_token_t; - class CConfigurationManager final : public TKernelObject<IConfigurationManager> - { - public: +class CConfigurationManager final : public TKernelObject<IConfigurationManager> +{ +public: - CConfigurationManager(const IKernelContext& ctx, IConfigurationManager* parentConfigManager = nullptr); - void clear() override; - bool addConfigurationFromFile(const CString& rFileNameWildCard) override; - CIdentifier createConfigurationToken(const CString& name, const CString& value) override; - bool releaseConfigurationToken(const CIdentifier& identifier) override; - CIdentifier getNextConfigurationTokenIdentifier(const CIdentifier& prevConfigTokenID) const override; - CString getConfigurationTokenName(const CIdentifier& identifier) const override; - CString getConfigurationTokenValue(const CIdentifier& identifier) const override; - bool setConfigurationTokenName(const CIdentifier& identifier, const CString& name) override; - bool setConfigurationTokenValue(const CIdentifier& identifier, const CString& value) override; - bool addOrReplaceConfigurationToken(const CString& name, const CString& value) override; - CIdentifier lookUpConfigurationTokenIdentifier(const CString& name, bool recursive) const override; - CString lookUpConfigurationTokenValue(const CString& name) const override; - bool registerKeywordParser(const CString& keyword, const IConfigurationKeywordExpandCallback& callback) override; - bool unregisterKeywordParser(const CString& keyword) override; - bool unregisterKeywordParser(const IConfigurationKeywordExpandCallback& callback) override; - CString expand(const CString& expression) const override; + CConfigurationManager(const IKernelContext& ctx, IConfigurationManager* parentConfigManager = nullptr); + void clear() override; + bool addConfigurationFromFile(const CString& rFileNameWildCard) override; + CIdentifier createConfigurationToken(const CString& name, const CString& value) override; + bool releaseConfigurationToken(const CIdentifier& identifier) override; + CIdentifier getNextConfigurationTokenIdentifier(const CIdentifier& prevConfigTokenID) const override; + CString getConfigurationTokenName(const CIdentifier& identifier) const override; + CString getConfigurationTokenValue(const CIdentifier& identifier) const override; + bool setConfigurationTokenName(const CIdentifier& identifier, const CString& name) override; + bool setConfigurationTokenValue(const CIdentifier& identifier, const CString& value) override; + bool addOrReplaceConfigurationToken(const CString& name, const CString& value) override; + CIdentifier lookUpConfigurationTokenIdentifier(const CString& name, bool recursive) const override; + CString lookUpConfigurationTokenValue(const CString& name) const override; + bool registerKeywordParser(const CString& keyword, const IConfigurationKeywordExpandCallback& callback) override; + bool unregisterKeywordParser(const CString& keyword) override; + bool unregisterKeywordParser(const IConfigurationKeywordExpandCallback& callback) override; + CString expand(const CString& expression) const override; - _IsDerivedFromClass_Final_(TKernelObject<IConfigurationManager>, OVK_ClassId_Kernel_Config_ConfigManager) - CString expandOnlyKeyword(const CString& rKeyword, const CString& expression, bool preserveBackslashes) const override; - double expandAsFloat(const CString& expression, double fallbackValue) const override; - int64_t expandAsInteger(const CString& expression, int64_t fallbackValue) const override; - uint64_t expandAsUInteger(const CString& expression, uint64_t fallbackValue) const override; - bool expandAsBoolean(const CString& expression, bool fallbackValue) const override; - uint64_t expandAsEnumerationEntryValue(const CString& expression, const CIdentifier& enumTypeID, uint64_t fallbackValue) const override; + _IsDerivedFromClass_Final_(TKernelObject<IConfigurationManager>, OVK_ClassId_Kernel_Config_ConfigManager) + CString expandOnlyKeyword(const CString& rKeyword, const CString& expression, bool preserveBackslashes) const override; + double expandAsFloat(const CString& expression, double fallbackValue) const override; + int64_t expandAsInteger(const CString& expression, int64_t fallbackValue) const override; + uint64_t expandAsUInteger(const CString& expression, uint64_t fallbackValue) const override; + bool expandAsBoolean(const CString& expression, bool fallbackValue) const override; + uint64_t expandAsEnumerationEntryValue(const CString& expression, const CIdentifier& enumTypeID, uint64_t fallbackValue) const override; - protected: +protected: - CIdentifier getUnusedIdentifier() const; + CIdentifier getUnusedIdentifier() const; - bool internalExpand(const std::string& sValue, std::string& result) const; - bool internalExpandOnlyKeyword(const std::string& sKeyword, const std::string& sValue, std::string& sResult, bool preserveBackslashes) const; - bool internalGetConfigurationTokenValueFromName(const std::string& name, std::string& value) const; + bool internalExpand(const std::string& sValue, std::string& result) const; + bool internalExpandOnlyKeyword(const std::string& sKeyword, const std::string& sValue, std::string& sResult, bool preserveBackslashes) const; + bool internalGetConfigurationTokenValueFromName(const std::string& name, std::string& value) const; - IConfigurationManager* m_parentConfigManager = nullptr; - mutable size_t m_idx; - mutable size_t m_startTime; + IConfigurationManager* m_parentConfigManager = nullptr; + mutable size_t m_idx; + mutable size_t m_startTime; - static size_t getRandom(); - size_t getIndex() const; - static CString getTime(); - static CString getDate(); - size_t getRealTime() const; - static size_t getProcessId(); + static size_t getRandom(); + size_t getIndex() const; + static CString getTime(); + static CString getDate(); + size_t getRealTime() const; + static size_t getProcessId(); - std::map<CIdentifier, config_token_t> m_ConfigTokens; - std::map<CString, const IConfigurationKeywordExpandCallback*> m_keywordOverrides; + std::map<CIdentifier, config_token_t> m_ConfigTokens; + std::map<CString, const IConfigurationKeywordExpandCallback*> m_keywordOverrides; - mutable std::recursive_mutex m_mutex; - }; - } // namespace Kernel -} // namespace OpenViBE + mutable std::recursive_mutex m_mutex; +}; +} // namespace Kernel +} // namespace OpenViBE diff --git a/kernel/src/kernel/error/ovkCErrorManager.cpp b/kernel/src/kernel/error/ovkCErrorManager.cpp index 9a9ae67d4eb88a69d520335448fd87f2edc51ed2..d3741a4f58ee8d67058806e200752c52f99d1cde 100644 --- a/kernel/src/kernel/error/ovkCErrorManager.cpp +++ b/kernel/src/kernel/error/ovkCErrorManager.cpp @@ -27,85 +27,78 @@ using namespace OpenViBE; using namespace /*OpenViBE::*/Kernel; // Error manager IError internal implementation -namespace OpenViBE +namespace OpenViBE { +namespace Kernel { +class CError final : public IError { - namespace Kernel - { - class CError final : public IError - { - public: +public: - CError(ErrorType type, const char* description, IError* nestedError, const char* filename, const size_t line) - : m_errorType(type), m_nestedError(nestedError), m_description(description), m_location(std::string(filename) + ":" + std::to_string(line)) { } + CError(ErrorType type, const char* description, IError* nestedError, const char* filename, const size_t line) + : m_errorType(type), m_nestedError(nestedError), m_description(description), m_location(std::string(filename) + ":" + std::to_string(line)) { } - ~CError() override { } + ~CError() override { } - const char* getErrorString() const override { return m_description.c_str(); } + const char* getErrorString() const override { return m_description.c_str(); } + const char* getErrorLocation() const override { return m_location.c_str(); } + ErrorType getErrorType() const override { return m_errorType; } + const IError* getNestedError() const override { return m_nestedError.get(); } - const char* getErrorLocation() const override { return m_location.c_str(); } + _IsDerivedFromClass_Final_(IError, OVK_ClassId_Kernel_Error_Error) - ErrorType getErrorType() const override { return m_errorType; } +private: - const IError* getNestedError() const override { return m_nestedError.get(); } + ErrorType m_errorType; + std::unique_ptr<IError> m_nestedError; + std::string m_description; + std::string m_location; +}; +} // namespace Kernel +} // namespace OpenViBE - _IsDerivedFromClass_Final_(IError, OVK_ClassId_Kernel_Error_Error) +// Error manager implementation +namespace OpenViBE { +namespace Kernel { +CErrorManager::CErrorManager(const IKernelContext& context) : TKernelObject<IErrorManager>(context), m_topError(nullptr) { } - private: +CErrorManager::~CErrorManager() { this->releaseErrors(); } - ErrorType m_errorType; - std::unique_ptr<IError> m_nestedError; - std::string m_description; - std::string m_location; - }; - } // namespace Kernel -} // namespace OpenViBE +void CErrorManager::pushError(const ErrorType type, const char* description) { this->pushErrorAtLocation(type, description, "NoLocationInfo", 0); } -// Error manager implementation -namespace OpenViBE +void CErrorManager::pushErrorAtLocation(const ErrorType type, const char* description, const char* filename, const size_t line) +{ + std::lock_guard<std::mutex> lock(m_managerGuard); + const auto lastTopError = m_topError.release(); + m_topError.reset(new CError(type, description, lastTopError, filename, line)); +} + +void CErrorManager::releaseErrors() +{ + std::lock_guard<std::mutex> lock(m_managerGuard); + m_topError.reset(nullptr); +} + +bool CErrorManager::hasError() const +{ + std::lock_guard<std::mutex> lock(m_managerGuard); + return (m_topError != nullptr); +} + +const IError* CErrorManager::getLastError() const +{ + std::lock_guard<std::mutex> lock(m_managerGuard); + return m_topError.get(); +} + +const char* CErrorManager::getLastErrorString() const +{ + std::lock_guard<std::mutex> lock(m_managerGuard); + return (m_topError ? m_topError->getErrorString() : ""); +} + +ErrorType CErrorManager::getLastErrorType() const { - namespace Kernel - { - CErrorManager::CErrorManager(const IKernelContext& context) : TKernelObject<IErrorManager>(context), m_topError(nullptr) { } - - CErrorManager::~CErrorManager() { this->releaseErrors(); } - - void CErrorManager::pushError(const ErrorType type, const char* description) { this->pushErrorAtLocation(type, description, "NoLocationInfo", 0); } - - void CErrorManager::pushErrorAtLocation(const ErrorType type, const char* description, const char* filename, const size_t line) - { - std::lock_guard<std::mutex> lock(m_managerGuard); - const auto lastTopError = m_topError.release(); - m_topError.reset(new CError(type, description, lastTopError, filename, line)); - } - - void CErrorManager::releaseErrors() - { - std::lock_guard<std::mutex> lock(m_managerGuard); - m_topError.reset(nullptr); - } - - bool CErrorManager::hasError() const - { - std::lock_guard<std::mutex> lock(m_managerGuard); - return (m_topError != nullptr); - } - - const IError* CErrorManager::getLastError() const - { - std::lock_guard<std::mutex> lock(m_managerGuard); - return m_topError.get(); - } - - const char* CErrorManager::getLastErrorString() const - { - std::lock_guard<std::mutex> lock(m_managerGuard); - return (m_topError ? m_topError->getErrorString() : ""); - } - - ErrorType CErrorManager::getLastErrorType() const - { - std::lock_guard<std::mutex> lock(m_managerGuard); - return (m_topError ? m_topError->getErrorType() : ErrorType::NoErrorFound); - } - } // namespace Kernel -} // namespace OpenViBE + std::lock_guard<std::mutex> lock(m_managerGuard); + return (m_topError ? m_topError->getErrorType() : ErrorType::NoErrorFound); +} +} // namespace Kernel +} // namespace OpenViBE diff --git a/kernel/src/kernel/error/ovkCErrorManager.h b/kernel/src/kernel/error/ovkCErrorManager.h index 0e37fcfc0a37bc7f852a92739cdd4f4f299c263f..9c9f15d84bdf28e5475128b988cb77952bc78e26 100644 --- a/kernel/src/kernel/error/ovkCErrorManager.h +++ b/kernel/src/kernel/error/ovkCErrorManager.h @@ -26,43 +26,35 @@ #include "../ovkTKernelObject.h" -namespace OpenViBE +namespace OpenViBE { +namespace Kernel { +/** + * \class CErrorManager + * \author Charles Garraud (Inria) + * \date 2016-07-13 + * \brief Error manager kernel default implementation + */ +class CErrorManager final : public TKernelObject<IErrorManager> { - namespace Kernel - { - /** - * \class CErrorManager - * \author Charles Garraud (Inria) - * \date 2016-07-13 - * \brief Error manager kernel default implementation - */ - class CErrorManager final : public TKernelObject<IErrorManager> - { - public: +public: - explicit CErrorManager(const IKernelContext& context); - ~CErrorManager() override; + explicit CErrorManager(const IKernelContext& context); + ~CErrorManager() override; - void pushError(ErrorType type, const char* description) override; + void pushError(ErrorType type, const char* description) override; + void pushErrorAtLocation(ErrorType type, const char* description, const char* filename, size_t line) override; + void releaseErrors() override; + bool hasError() const override; + const IError* getLastError() const override; + const char* getLastErrorString() const override; + ErrorType getLastErrorType() const override; - void pushErrorAtLocation(ErrorType type, const char* description, const char* filename, size_t line) override; + _IsDerivedFromClass_Final_(TKernelObject<IErrorManager>, OVK_ClassId_Kernel_Error_ErrorManager) - void releaseErrors() override; +private: - bool hasError() const override; - - const IError* getLastError() const override; - - const char* getLastErrorString() const override; - - ErrorType getLastErrorType() const override; - - _IsDerivedFromClass_Final_(TKernelObject<IErrorManager>, OVK_ClassId_Kernel_Error_ErrorManager) - - private: - - mutable std::mutex m_managerGuard; - std::unique_ptr<IError> m_topError; - }; - } // namespace Kernel -} // namespace OpenViBE + mutable std::mutex m_managerGuard; + std::unique_ptr<IError> m_topError; +}; +} // namespace Kernel +} // namespace OpenViBE diff --git a/kernel/src/kernel/log/ovkCLogListenerConsole.cpp b/kernel/src/kernel/log/ovkCLogListenerConsole.cpp index 08f204a5dcbe1541149ee825b0233266e4ad8307..81707f92ec1d51c501f93e71dbbacd94beed5c5e 100755 --- a/kernel/src/kernel/log/ovkCLogListenerConsole.cpp +++ b/kernel/src/kernel/log/ovkCLogListenerConsole.cpp @@ -405,5 +405,5 @@ void CLogListenerConsole::applyColor() void CLogListenerConsole::applyColor() { } #endif -} // namespace Kernel -} // namespace OpenViBE +} // namespace Kernel +} // namespace OpenViBE diff --git a/kernel/src/kernel/log/ovkCLogListenerConsole.h b/kernel/src/kernel/log/ovkCLogListenerConsole.h index 320d25c0f9121d8aee203ac8c669e7abcab55f39..8a06bbf05c57c71609ba9068284c50131c80c437 100644 --- a/kernel/src/kernel/log/ovkCLogListenerConsole.h +++ b/kernel/src/kernel/log/ovkCLogListenerConsole.h @@ -50,5 +50,5 @@ protected: bool m_useColor = false; }; -} // namespace Kernel -} // namespace OpenViBE +} // namespace Kernel +} // namespace OpenViBE diff --git a/kernel/src/kernel/log/ovkCLogListenerFile.cpp b/kernel/src/kernel/log/ovkCLogListenerFile.cpp index 8d987b17987c701c715ddfe70a411c727c121905..4fe65f400f3d764e4b173bacdb8f728230f25e68 100644 --- a/kernel/src/kernel/log/ovkCLogListenerFile.cpp +++ b/kernel/src/kernel/log/ovkCLogListenerFile.cpp @@ -53,5 +53,5 @@ bool CLogListenerFile::activate(const ELogLevel startLevel, const ELogLevel endL bool CLogListenerFile::activate(const bool active) { return activate(LogLevel_First, LogLevel_Last, active); } -} // namespace Kernel -} // namespace OpenViBE +} // namespace Kernel +} // namespace OpenViBE diff --git a/kernel/src/kernel/log/ovkCLogListenerFile.h b/kernel/src/kernel/log/ovkCLogListenerFile.h index 9b20c132826c34384fddf18fb52a38e0dcec9e30..246c5e78454bc92d0167f057666739170ce4c53d 100644 --- a/kernel/src/kernel/log/ovkCLogListenerFile.h +++ b/kernel/src/kernel/log/ovkCLogListenerFile.h @@ -64,5 +64,5 @@ private: } }; -} // namespace Kernel -} // namespace OpenViBE +} // namespace Kernel +} // namespace OpenViBE diff --git a/kernel/src/kernel/log/ovkCLogManager.cpp b/kernel/src/kernel/log/ovkCLogManager.cpp index 6a71727e81488e5595ae35d93508e506200b7d25..719d6af5674c017342ddfd11de7a5efa35c33370 100755 --- a/kernel/src/kernel/log/ovkCLogManager.cpp +++ b/kernel/src/kernel/log/ovkCLogManager.cpp @@ -82,5 +82,5 @@ bool CLogManager::removeListener(ILogListener* listener) return false; } -} // namespace Kernel -} // namespace OpenViBE +} // namespace Kernel +} // namespace OpenViBE diff --git a/kernel/src/kernel/log/ovkCLogManager.h b/kernel/src/kernel/log/ovkCLogManager.h index 3fc02808e0fcdb84e34cefa0bfe66b7038e7d244..8a3103f1f03720fce6bbfaaaf53601072893f0d3 100755 --- a/kernel/src/kernel/log/ovkCLogManager.h +++ b/kernel/src/kernel/log/ovkCLogManager.h @@ -71,5 +71,5 @@ protected: std::thread::id m_owner; }; -} // namespace Kernel -} // namespace OpenViBE +} // namespace Kernel +} // namespace OpenViBE diff --git a/kernel/src/kernel/metabox/ovkCMetaboxManager.cpp b/kernel/src/kernel/metabox/ovkCMetaboxManager.cpp index 212782b263ab0b8b88b7835d79dc03b956e5dfe4..5a61c90176e8059841fa540452a9ab1618c34e0a 100755 --- a/kernel/src/kernel/metabox/ovkCMetaboxManager.cpp +++ b/kernel/src/kernel/metabox/ovkCMetaboxManager.cpp @@ -13,68 +13,66 @@ using namespace /*OpenViBE::*/Kernel; using namespace Metabox; using namespace std; -namespace OpenViBE +namespace OpenViBE { +namespace Kernel { +class CMetaboxManagerEntryEnumeratorCallBack final : public TKernelObject<IObject>, public FS::IEntryEnumeratorCallBack { - namespace Kernel +public: + + CMetaboxManagerEntryEnumeratorCallBack(const IKernelContext& ctx, CMetaboxManager& metaboxManager) + : TKernelObject<IObject>(ctx), m_manager(metaboxManager) { m_n = 0; } + + bool callback(FS::IEntryEnumerator::IEntry& rEntry, FS::IEntryEnumerator::IAttributes& rAttributes) override { - class CMetaboxManagerEntryEnumeratorCallBack final : public TKernelObject<IObject>, public FS::IEntryEnumeratorCallBack + if (rAttributes.isFile()) { - public: - - CMetaboxManagerEntryEnumeratorCallBack(const IKernelContext& ctx, CMetaboxManager& metaboxManager) - : TKernelObject<IObject>(ctx), m_manager(metaboxManager) { m_n = 0; } + const char* fullFileName = rEntry.getName(); - bool callback(FS::IEntryEnumerator::IEntry& rEntry, FS::IEntryEnumerator::IAttributes& rAttributes) override + CIdentifier scenarioID, metaboxId, metaboxHash; + this->getKernelContext().getScenarioManager(). + importScenarioFromFile(scenarioID, OV_ScenarioImportContext_OnLoadMetaboxImport, fullFileName); + if (scenarioID != OV_UndefinedIdentifier) { - if (rAttributes.isFile()) + IScenario& metaboxScenario = this->getKernelContext().getScenarioManager().getScenario(scenarioID); + const bool isValid = metaboxId.fromString(metaboxScenario.getAttributeValue(OVP_AttributeId_Metabox_ID)); + if (isValid && metaboxScenario.getAttributeValue(OV_AttributeId_Scenario_Name) != CString()) { - const char* fullFileName = rEntry.getName(); - - CIdentifier scenarioID, metaboxId, metaboxHash; - this->getKernelContext().getScenarioManager(). - importScenarioFromFile(scenarioID, OV_ScenarioImportContext_OnLoadMetaboxImport, fullFileName); - if (scenarioID != OV_UndefinedIdentifier) + const bool hasHash = metaboxHash.fromString(metaboxScenario.getAttributeValue(OV_AttributeId_Scenario_MetaboxHash)); + if (!hasHash) { - IScenario& metaboxScenario = this->getKernelContext().getScenarioManager().getScenario(scenarioID); - const bool isValid = metaboxId.fromString(metaboxScenario.getAttributeValue(OVP_AttributeId_Metabox_ID)); - if (isValid && metaboxScenario.getAttributeValue(OV_AttributeId_Scenario_Name) != CString()) - { - const bool hasHash = metaboxHash.fromString(metaboxScenario.getAttributeValue(OV_AttributeId_Scenario_MetaboxHash)); - if (!hasHash) - { - this->getKernelContext().getLogManager() << LogLevel_Warning << "The metabox " << metaboxId.str() << - " has no Hash in the scenario " << fullFileName << "\n"; - } - m_manager.setMetaboxFilePath(metaboxId, CString(fullFileName)); - m_manager.setMetaboxHash(metaboxId, metaboxHash); - m_manager.setMetaboxObjectDesc(metaboxId, new CMetaboxObjectDesc(metaboxId.str().c_str(), metaboxScenario)); - m_n++; - } - else - { - this->getKernelContext().getLogManager() << LogLevel_Warning << "The metabox file " << fullFileName << - " is missing elements. Please check it.\n"; - } + this->getKernelContext().getLogManager() << LogLevel_Warning << "The metabox " << metaboxId.str() << + " has no Hash in the scenario " << fullFileName << "\n"; } - this->getKernelContext().getScenarioManager().releaseScenario(scenarioID); + m_manager.setMetaboxFilePath(metaboxId, CString(fullFileName)); + m_manager.setMetaboxHash(metaboxId, metaboxHash); + m_manager.setMetaboxObjectDesc(metaboxId, new CMetaboxObjectDesc(metaboxId.str().c_str(), metaboxScenario)); + m_n++; + } + else + { + this->getKernelContext().getLogManager() << LogLevel_Warning << "The metabox file " << fullFileName << + " is missing elements. Please check it.\n"; } - return true; } + this->getKernelContext().getScenarioManager().releaseScenario(scenarioID); + } + return true; + } - size_t resetMetaboxCount() - { - const size_t res = m_n; - m_n = 0; - return res; - } + size_t resetMetaboxCount() + { + const size_t res = m_n; + m_n = 0; + return res; + } - _IsDerivedFromClass_Final_(TKernelObject<IObject>, OV_UndefinedIdentifier) - protected: - CMetaboxManager& m_manager; - size_t m_n; - }; - } // namespace Kernel -} // namespace OpenViBE + _IsDerivedFromClass_Final_(TKernelObject<IObject>, OV_UndefinedIdentifier) +protected: + CMetaboxManager& m_manager; + size_t m_n; +}; +} // namespace Kernel +} // namespace OpenViBE CMetaboxManager::CMetaboxManager(const IKernelContext& ctx) : TKernelObject<IMetaboxManager>(ctx) { diff --git a/kernel/src/kernel/metabox/ovkCMetaboxManager.h b/kernel/src/kernel/metabox/ovkCMetaboxManager.h index 09875d4399b6e6598a85132095044f8bdba1c57a..1e9f82203fdb950279831bf1fba2d474c5c7333f 100755 --- a/kernel/src/kernel/metabox/ovkCMetaboxManager.h +++ b/kernel/src/kernel/metabox/ovkCMetaboxManager.h @@ -5,30 +5,28 @@ #include <map> -namespace OpenViBE +namespace OpenViBE { +namespace Kernel { +class CMetaboxManager final : public TKernelObject<IMetaboxManager> { - namespace Kernel - { - class CMetaboxManager final : public TKernelObject<IMetaboxManager> - { - public: - explicit CMetaboxManager(const IKernelContext& ctx); - ~CMetaboxManager() override; - bool addMetaboxesFromFiles(const CString& fileNameWildCard) override; - CIdentifier getNextMetaboxObjectDescIdentifier(const CIdentifier& previousID) const override; - const Plugins::IPluginObjectDesc* getMetaboxObjectDesc(const CIdentifier& metaboxID) const override; - void setMetaboxObjectDesc(const CIdentifier& metaboxID, Plugins::IPluginObjectDesc* metaboxDesc) override; - CString getMetaboxFilePath(const CIdentifier& metaboxID) const override; - void setMetaboxFilePath(const CIdentifier& metaboxID, const CString& filePath) override; - CIdentifier getMetaboxHash(const CIdentifier& metaboxID) const override; - void setMetaboxHash(const CIdentifier& metaboxID, const CIdentifier& hash) override; +public: + explicit CMetaboxManager(const IKernelContext& ctx); + ~CMetaboxManager() override; + bool addMetaboxesFromFiles(const CString& fileNameWildCard) override; + CIdentifier getNextMetaboxObjectDescIdentifier(const CIdentifier& previousID) const override; + const Plugins::IPluginObjectDesc* getMetaboxObjectDesc(const CIdentifier& metaboxID) const override; + void setMetaboxObjectDesc(const CIdentifier& metaboxID, Plugins::IPluginObjectDesc* metaboxDesc) override; + CString getMetaboxFilePath(const CIdentifier& metaboxID) const override; + void setMetaboxFilePath(const CIdentifier& metaboxID, const CString& filePath) override; + CIdentifier getMetaboxHash(const CIdentifier& metaboxID) const override; + void setMetaboxHash(const CIdentifier& metaboxID, const CIdentifier& hash) override; - _IsDerivedFromClass_Final_(TKernelObject<IMetaboxManager>, OVK_ClassId_Kernel_Metaboxes_MetaboxManager) + _IsDerivedFromClass_Final_(TKernelObject<IMetaboxManager>, OVK_ClassId_Kernel_Metaboxes_MetaboxManager) - protected: - std::map<CIdentifier, const Plugins::IPluginObjectDesc*> m_objectDesc; - std::map<CIdentifier, CString> m_filepath; - std::map<CIdentifier, CIdentifier> m_hash; - }; - } // namespace Kernel -} // namespace OpenViBE +protected: + std::map<CIdentifier, const Plugins::IPluginObjectDesc*> m_objectDesc; + std::map<CIdentifier, CString> m_filepath; + std::map<CIdentifier, CIdentifier> m_hash; +}; +} // namespace Kernel +} // namespace OpenViBE diff --git a/kernel/src/kernel/metabox/ovkCMetaboxObjectDesc.h b/kernel/src/kernel/metabox/ovkCMetaboxObjectDesc.h index 4fa8b016ae3bea666c75220558ec69cb9dd30f9d..47d8a52b3bb79069f259b202fc8b4f0c27b88d41 100755 --- a/kernel/src/kernel/metabox/ovkCMetaboxObjectDesc.h +++ b/kernel/src/kernel/metabox/ovkCMetaboxObjectDesc.h @@ -4,93 +4,91 @@ #include <vector> -namespace OpenViBE +namespace OpenViBE { +namespace Metabox { + +/** + * \brief The CMetaboxObjectDesc virtual BoxAlgorithmDesc for metaboxes + * + * This class provides a virtual algorithm descriptor for metaboxes. Each metabox-scenario + * will result in one of these descriptors. The prototype is created from scenario inputs, + * outputs and settings. + * + * Variables such as name, author etc are pulled from scenario information. + */ +class CMetaboxObjectDesc final : virtual public IMetaboxObjectDesc { - namespace Metabox +public: + CMetaboxObjectDesc() { } + + CMetaboxObjectDesc(const CString& rMetaboxDescriptor, Kernel::IScenario& metaboxScenario); + void release() override { } + CString getMetaboxDescriptor() const override { return m_metaboxDesc; } + CString getName() const override { return m_name; } + CString getAuthorName() const override { return m_authorName; } + CString getAuthorCompanyName() const override { return m_authorCompanyName; } + CString getShortDescription() const override { return m_shortDesc; } + CString getDetailedDescription() const override { return m_detailedDesc; } + CString getCategory() const override { return m_category; } + CString getVersion() const override { return m_version; } + CString getStockItemName() const override { return m_stockItemName; } + CString getAddedSoftwareVersion() const override { return m_addedSoftwareVersion; } + CString getUpdatedSoftwareVersion() const override { return m_updatedSoftwareVersion; } + CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_Metabox; } + Plugins::IPluginObject* create() override { return nullptr; } + + // Handling of the virtual prototype + + // Since we have to construct a prototype on the fly, the special Metabox descriptor + // will also hold the information about the settings, inputs and outputs of the box + typedef struct SStream { + SStream() : m_name(""), m_typeID(OV_UndefinedIdentifier), m_id(OV_UndefinedIdentifier) {} - /** - * \brief The CMetaboxObjectDesc virtual BoxAlgorithmDesc for metaboxes - * - * This class provides a virtual algorithm descriptor for metaboxes. Each metabox-scenario - * will result in one of these descriptors. The prototype is created from scenario inputs, - * outputs and settings. - * - * Variables such as name, author etc are pulled from scenario information. - */ - class CMetaboxObjectDesc final : virtual public IMetaboxObjectDesc - { - public: - CMetaboxObjectDesc() { } - - CMetaboxObjectDesc(const CString& rMetaboxDescriptor, Kernel::IScenario& metaboxScenario); - void release() override { } - CString getMetaboxDescriptor() const override { return m_metaboxDesc; } - CString getName() const override { return m_name; } - CString getAuthorName() const override { return m_authorName; } - CString getAuthorCompanyName() const override { return m_authorCompanyName; } - CString getShortDescription() const override { return m_shortDesc; } - CString getDetailedDescription() const override { return m_detailedDesc; } - CString getCategory() const override { return m_category; } - CString getVersion() const override { return m_version; } - CString getStockItemName() const override { return m_stockItemName; } - CString getAddedSoftwareVersion() const override { return m_addedSoftwareVersion; } - CString getUpdatedSoftwareVersion() const override { return m_updatedSoftwareVersion; } - CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_Metabox; } - Plugins::IPluginObject* create() override { return nullptr; } - - // Handling of the virtual prototype - - // Since we have to construct a prototype on the fly, the special Metabox descriptor - // will also hold the information about the settings, inputs and outputs of the box - typedef struct SStream - { - SStream() : m_name(""), m_typeID(OV_UndefinedIdentifier), m_id(OV_UndefinedIdentifier) {} - - SStream(const CString& name, const CIdentifier& typeID, const CIdentifier& identifier) - : m_name(name), m_typeID(typeID), m_id(identifier) {} - - CString m_name; - CIdentifier m_typeID = OV_UndefinedIdentifier; - CIdentifier m_id = OV_UndefinedIdentifier; - } io_stream_t; - - typedef struct SSetting - { - SSetting() - : m_name(""), m_typeID(OV_UndefinedIdentifier), m_defaultValue(""), m_id(OV_UndefinedIdentifier) {} - - SSetting(const CString& name, const CIdentifier& typeID, const CString& value, const CIdentifier& id) - : m_name(name), m_typeID(typeID), m_defaultValue(value), m_id(id) { } - - CString m_name; - CIdentifier m_typeID = OV_UndefinedIdentifier; - CString m_defaultValue; - CIdentifier m_id = OV_UndefinedIdentifier; - } setting_t; - - bool getBoxPrototype(Kernel::IBoxProto& prototype) const override; - - _IsDerivedFromClass_Final_(IMetaboxObjectDesc, OVP_ClassId_BoxAlgorithm_MetaboxDesc) - - private: - CString m_metaboxDesc; - - CString m_name; - CString m_authorName; - CString m_authorCompanyName; - CString m_shortDesc; - CString m_detailedDesc; - CString m_category; - CString m_version; - CString m_stockItemName; - CString m_addedSoftwareVersion; - CString m_updatedSoftwareVersion; - CString m_metaboxID; - - std::vector<io_stream_t> m_inputs; - std::vector<io_stream_t> m_outputs; - std::vector<setting_t> m_settings; - }; - } // namespace Metabox -} // namespace OpenViBE + SStream(const CString& name, const CIdentifier& typeID, const CIdentifier& identifier) + : m_name(name), m_typeID(typeID), m_id(identifier) {} + + CString m_name; + CIdentifier m_typeID = OV_UndefinedIdentifier; + CIdentifier m_id = OV_UndefinedIdentifier; + } io_stream_t; + + typedef struct SSetting + { + SSetting() + : m_name(""), m_typeID(OV_UndefinedIdentifier), m_defaultValue(""), m_id(OV_UndefinedIdentifier) {} + + SSetting(const CString& name, const CIdentifier& typeID, const CString& value, const CIdentifier& id) + : m_name(name), m_typeID(typeID), m_defaultValue(value), m_id(id) { } + + CString m_name; + CIdentifier m_typeID = OV_UndefinedIdentifier; + CString m_defaultValue; + CIdentifier m_id = OV_UndefinedIdentifier; + } setting_t; + + bool getBoxPrototype(Kernel::IBoxProto& prototype) const override; + + _IsDerivedFromClass_Final_(IMetaboxObjectDesc, OVP_ClassId_BoxAlgorithm_MetaboxDesc) + +private: + CString m_metaboxDesc; + + CString m_name; + CString m_authorName; + CString m_authorCompanyName; + CString m_shortDesc; + CString m_detailedDesc; + CString m_category; + CString m_version; + CString m_stockItemName; + CString m_addedSoftwareVersion; + CString m_updatedSoftwareVersion; + CString m_metaboxID; + + std::vector<io_stream_t> m_inputs; + std::vector<io_stream_t> m_outputs; + std::vector<setting_t> m_settings; +}; +} // namespace Metabox +} // namespace OpenViBE diff --git a/kernel/src/kernel/ovkCConfigurable.h b/kernel/src/kernel/ovkCConfigurable.h index 0320c539f3ced956ebda037ad174f751597650e4..f9d336ae5327e39fc6bfe00a1373879d0861e9fe 100644 --- a/kernel/src/kernel/ovkCConfigurable.h +++ b/kernel/src/kernel/ovkCConfigurable.h @@ -3,19 +3,17 @@ #include "ovkTKernelObject.h" #include "ovkTConfigurable.h" -namespace OpenViBE -{ - namespace Kernel - { - typedef TBaseConfigurable<TKernelObject<IConfigurable>> configurable; +namespace OpenViBE { +namespace Kernel { +typedef TBaseConfigurable<TKernelObject<IConfigurable>> configurable; - class CConfigurable final : public configurable - { - public: +class CConfigurable final : public configurable +{ +public: - explicit CConfigurable(const IKernelContext& ctx) : TBaseConfigurable<TKernelObject<IConfigurable>>(ctx) { } + explicit CConfigurable(const IKernelContext& ctx) : TBaseConfigurable<TKernelObject<IConfigurable>>(ctx) { } - _IsDerivedFromClass_Final_(configurable, OVK_ClassId_Kernel_Configurable) - }; - } // namespace Kernel -} // namespace OpenViBE + _IsDerivedFromClass_Final_(configurable, OVK_ClassId_Kernel_Configurable) +}; +} // namespace Kernel +} // namespace OpenViBE diff --git a/kernel/src/kernel/ovkCKernelContext.h b/kernel/src/kernel/ovkCKernelContext.h index 6d05f9b6ed1e367794112293510f03a1595db071..eeaebe48a747a5210885db03ef748a852046a3b1 100755 --- a/kernel/src/kernel/ovkCKernelContext.h +++ b/kernel/src/kernel/ovkCKernelContext.h @@ -4,118 +4,113 @@ #include "ovkTKernelObject.h" -namespace OpenViBE +namespace OpenViBE { +namespace Kernel { +class CLogListenerConsole; +class CLogListenerFile; + +class CKernelContext final : public IKernelContext +{ +public: + + CKernelContext(const IKernelContext* masterKernelCtx, const CString& applicationName, const CString& configFile); + ~CKernelContext() override; + bool initialize(const char* const * tokenList, size_t nToken) override; + bool uninitialize() override; + IAlgorithmManager& getAlgorithmManager() const override; + IConfigurationManager& getConfigurationManager() const override; + IKernelObjectFactory& getKernelObjectFactory() const override; + IPlayerManager& getPlayerManager() const override; + IPluginManager& getPluginManager() const override; + IMetaboxManager& getMetaboxManager() const override; + IScenarioManager& getScenarioManager() const override; + ITypeManager& getTypeManager() const override; + ILogManager& getLogManager() const override; + IErrorManager& getErrorManager() const override; + + _IsDerivedFromClass_Final_(IKernelContext, OVK_ClassId_Kernel_KernelContext) + +protected: + + ELogLevel earlyGetLogLevel(const CString& rLogLevelName); + +private: + + const IKernelContext& m_masterKernelCtx; + + std::unique_ptr<IAlgorithmManager> m_algorithmManager; + std::unique_ptr<IConfigurationManager> m_configManager; + std::unique_ptr<IKernelObjectFactory> m_kernelObjectFactory; + std::unique_ptr<IPlayerManager> m_playerManager; + std::unique_ptr<IPluginManager> m_pluginManager; + std::unique_ptr<IMetaboxManager> m_metaboxManager; + std::unique_ptr<IScenarioManager> m_scenarioManager; + std::unique_ptr<ITypeManager> m_typeManager; + std::unique_ptr<ILogManager> m_logManager; + std::unique_ptr<IErrorManager> m_errorManager; + + CString m_applicationName; + CString m_configFile; + + std::unique_ptr<CLogListenerConsole> m_logListenerConsole; + std::unique_ptr<CLogListenerFile> m_logListenerFile; + + CKernelContext() = delete; +}; + +class CKernelContextBridge final : public IKernelContext { - namespace Kernel +public: + + explicit CKernelContextBridge(const IKernelContext& ctx) : m_kernelCtx(ctx) { } + + bool initialize() { return true; } + bool uninitialize() override { return true; } + + void setAlgorithmManager(IAlgorithmManager* manager) { m_algorithmManager = manager; } + void setConfigurationManager(IConfigurationManager* manager) { m_configManager = manager; } + void setKernelObjectFactory(IKernelObjectFactory* kernelObjectFactory) { m_kernelObjectFactory = kernelObjectFactory; } + void setPlayerManager(IPlayerManager* manager) { m_playerManager = manager; } + void setPluginManager(IPluginManager* manager) { m_pluginManager = manager; } + void setMetaboxManager(IMetaboxManager* manager) { m_metaboxManager = manager; } + void setScenarioManager(IScenarioManager* manager) { m_scenarioManager = manager; } + void setTypeManager(ITypeManager* manager) { m_typeManager = manager; } + void setLogManager(ILogManager* manager) { m_logManager = manager; } + void setErrorManager(IErrorManager* manager) { m_errorManager = manager; } + + IAlgorithmManager& getAlgorithmManager() const override { return m_algorithmManager ? *m_algorithmManager : m_kernelCtx.getAlgorithmManager(); } + + IConfigurationManager& getConfigurationManager() const override { return m_configManager ? *m_configManager : m_kernelCtx.getConfigurationManager(); } + + IKernelObjectFactory& getKernelObjectFactory() const override { - class CLogListenerConsole; - class CLogListenerFile; - - class CKernelContext final : public IKernelContext - { - public: - - CKernelContext(const IKernelContext* masterKernelCtx, const CString& applicationName, const CString& configFile); - ~CKernelContext() override; - bool initialize(const char* const * tokenList, size_t nToken) override; - bool uninitialize() override; - IAlgorithmManager& getAlgorithmManager() const override; - IConfigurationManager& getConfigurationManager() const override; - IKernelObjectFactory& getKernelObjectFactory() const override; - IPlayerManager& getPlayerManager() const override; - IPluginManager& getPluginManager() const override; - IMetaboxManager& getMetaboxManager() const override; - IScenarioManager& getScenarioManager() const override; - ITypeManager& getTypeManager() const override; - ILogManager& getLogManager() const override; - IErrorManager& getErrorManager() const override; - - _IsDerivedFromClass_Final_(IKernelContext, OVK_ClassId_Kernel_KernelContext) - - protected: - - ELogLevel earlyGetLogLevel(const CString& rLogLevelName); - - private: - - const IKernelContext& m_masterKernelCtx; - - std::unique_ptr<IAlgorithmManager> m_algorithmManager; - std::unique_ptr<IConfigurationManager> m_configManager; - std::unique_ptr<IKernelObjectFactory> m_kernelObjectFactory; - std::unique_ptr<IPlayerManager> m_playerManager; - std::unique_ptr<IPluginManager> m_pluginManager; - std::unique_ptr<IMetaboxManager> m_metaboxManager; - std::unique_ptr<IScenarioManager> m_scenarioManager; - std::unique_ptr<ITypeManager> m_typeManager; - std::unique_ptr<ILogManager> m_logManager; - std::unique_ptr<IErrorManager> m_errorManager; - - CString m_applicationName; - CString m_configFile; - - std::unique_ptr<CLogListenerConsole> m_logListenerConsole; - std::unique_ptr<CLogListenerFile> m_logListenerFile; - - CKernelContext() = delete; - }; - - class CKernelContextBridge final : public IKernelContext - { - public: - - explicit CKernelContextBridge(const IKernelContext& ctx) : m_kernelCtx(ctx) { } - - bool initialize() { return true; } - bool uninitialize() override { return true; } - - void setAlgorithmManager(IAlgorithmManager* manager) { m_algorithmManager = manager; } - void setConfigurationManager(IConfigurationManager* manager) { m_configManager = manager; } - void setKernelObjectFactory(IKernelObjectFactory* kernelObjectFactory) { m_kernelObjectFactory = kernelObjectFactory; } - void setPlayerManager(IPlayerManager* manager) { m_playerManager = manager; } - void setPluginManager(IPluginManager* manager) { m_pluginManager = manager; } - void setMetaboxManager(IMetaboxManager* manager) { m_metaboxManager = manager; } - void setScenarioManager(IScenarioManager* manager) { m_scenarioManager = manager; } - void setTypeManager(ITypeManager* manager) { m_typeManager = manager; } - void setLogManager(ILogManager* manager) { m_logManager = manager; } - void setErrorManager(IErrorManager* manager) { m_errorManager = manager; } - - IAlgorithmManager& getAlgorithmManager() const override { return m_algorithmManager ? *m_algorithmManager : m_kernelCtx.getAlgorithmManager(); } - - IConfigurationManager& getConfigurationManager() const override - { - return m_configManager ? *m_configManager : m_kernelCtx.getConfigurationManager(); - } - - IKernelObjectFactory& getKernelObjectFactory() const override - { - return m_kernelObjectFactory ? *m_kernelObjectFactory : m_kernelCtx.getKernelObjectFactory(); - } - - IPlayerManager& getPlayerManager() const override { return m_playerManager ? *m_playerManager : m_kernelCtx.getPlayerManager(); } - IPluginManager& getPluginManager() const override { return m_pluginManager ? *m_pluginManager : m_kernelCtx.getPluginManager(); } - IMetaboxManager& getMetaboxManager() const override { return m_metaboxManager ? *m_metaboxManager : m_kernelCtx.getMetaboxManager(); } - IScenarioManager& getScenarioManager() const override { return m_scenarioManager ? *m_scenarioManager : m_kernelCtx.getScenarioManager(); } - ITypeManager& getTypeManager() const override { return m_typeManager ? *m_typeManager : m_kernelCtx.getTypeManager(); } - ILogManager& getLogManager() const override { return m_logManager ? *m_logManager : m_kernelCtx.getLogManager(); } - IErrorManager& getErrorManager() const override { return m_errorManager ? *m_errorManager : m_kernelCtx.getErrorManager(); } - - _IsDerivedFromClass_Final_(IKernelContext, OVK_ClassId_Kernel_KernelContext) - - protected: - - const IKernelContext& m_kernelCtx; - - mutable IAlgorithmManager* m_algorithmManager = nullptr; - mutable IConfigurationManager* m_configManager = nullptr; - mutable IKernelObjectFactory* m_kernelObjectFactory = nullptr; - mutable IPlayerManager* m_playerManager = nullptr; - mutable IPluginManager* m_pluginManager = nullptr; - mutable IMetaboxManager* m_metaboxManager = nullptr; - mutable IScenarioManager* m_scenarioManager = nullptr; - mutable ITypeManager* m_typeManager = nullptr; - mutable ILogManager* m_logManager = nullptr; - mutable IErrorManager* m_errorManager = nullptr; - }; - } // namespace Kernel -} // namespace OpenViBE + return m_kernelObjectFactory ? *m_kernelObjectFactory : m_kernelCtx.getKernelObjectFactory(); + } + + IPlayerManager& getPlayerManager() const override { return m_playerManager ? *m_playerManager : m_kernelCtx.getPlayerManager(); } + IPluginManager& getPluginManager() const override { return m_pluginManager ? *m_pluginManager : m_kernelCtx.getPluginManager(); } + IMetaboxManager& getMetaboxManager() const override { return m_metaboxManager ? *m_metaboxManager : m_kernelCtx.getMetaboxManager(); } + IScenarioManager& getScenarioManager() const override { return m_scenarioManager ? *m_scenarioManager : m_kernelCtx.getScenarioManager(); } + ITypeManager& getTypeManager() const override { return m_typeManager ? *m_typeManager : m_kernelCtx.getTypeManager(); } + ILogManager& getLogManager() const override { return m_logManager ? *m_logManager : m_kernelCtx.getLogManager(); } + IErrorManager& getErrorManager() const override { return m_errorManager ? *m_errorManager : m_kernelCtx.getErrorManager(); } + + _IsDerivedFromClass_Final_(IKernelContext, OVK_ClassId_Kernel_KernelContext) + +protected: + + const IKernelContext& m_kernelCtx; + + mutable IAlgorithmManager* m_algorithmManager = nullptr; + mutable IConfigurationManager* m_configManager = nullptr; + mutable IKernelObjectFactory* m_kernelObjectFactory = nullptr; + mutable IPlayerManager* m_playerManager = nullptr; + mutable IPluginManager* m_pluginManager = nullptr; + mutable IMetaboxManager* m_metaboxManager = nullptr; + mutable IScenarioManager* m_scenarioManager = nullptr; + mutable ITypeManager* m_typeManager = nullptr; + mutable ILogManager* m_logManager = nullptr; + mutable IErrorManager* m_errorManager = nullptr; +}; +} // namespace Kernel +} // namespace OpenViBE diff --git a/kernel/src/kernel/ovkCKernelObjectFactory.h b/kernel/src/kernel/ovkCKernelObjectFactory.h index 1cbba3aab1dec74397d39853e3c3c97dfa1153f2..a2d61263025ed5381c76b38e496b981b680108f2 100755 --- a/kernel/src/kernel/ovkCKernelObjectFactory.h +++ b/kernel/src/kernel/ovkCKernelObjectFactory.h @@ -5,25 +5,23 @@ #include <vector> #include <mutex> -namespace OpenViBE +namespace OpenViBE { +namespace Kernel { +class CKernelObjectFactory final : public TKernelObject<IKernelObjectFactory> { - namespace Kernel - { - class CKernelObjectFactory final : public TKernelObject<IKernelObjectFactory> - { - public: +public: - explicit CKernelObjectFactory(const IKernelContext& ctx) : TKernelObject<IKernelObjectFactory>(ctx) {} - IObject* createObject(const CIdentifier& classID) override; - bool releaseObject(IObject* pObject) override; + explicit CKernelObjectFactory(const IKernelContext& ctx) : TKernelObject<IKernelObjectFactory>(ctx) {} + IObject* createObject(const CIdentifier& classID) override; + bool releaseObject(IObject* pObject) override; - _IsDerivedFromClass_Final_(TKernelObject<IKernelObjectFactory>, OVK_ClassId_Kernel_KernelObjectFactory) + _IsDerivedFromClass_Final_(TKernelObject<IKernelObjectFactory>, OVK_ClassId_Kernel_KernelObjectFactory) - protected: +protected: - std::vector<IObject*> m_oCreatedObjects; + std::vector<IObject*> m_oCreatedObjects; - std::mutex m_oMutex; - }; - } // namespace Kernel -} // namespace OpenViBE + std::mutex m_oMutex; +}; +} // namespace Kernel +} // namespace OpenViBE diff --git a/kernel/src/kernel/ovkCObjectVisitorContext.cpp b/kernel/src/kernel/ovkCObjectVisitorContext.cpp index ba017afb211cdf3f494fff6b59c00ff5f126a672..67c3f72cca6bd18eccfd91a1037ef0071c1c6730 100644 --- a/kernel/src/kernel/ovkCObjectVisitorContext.cpp +++ b/kernel/src/kernel/ovkCObjectVisitorContext.cpp @@ -10,11 +10,7 @@ CObjectVisitorContext::CObjectVisitorContext(const IKernelContext& ctx) CObjectVisitorContext::~CObjectVisitorContext() {} IAlgorithmManager& CObjectVisitorContext::getAlgorithmManager() const { return TKernelObject<IObjectVisitorContext>::getAlgorithmManager(); } - IConfigurationManager& CObjectVisitorContext::getConfigurationManager() const { return TKernelObject<IObjectVisitorContext>::getConfigurationManager(); } - ITypeManager& CObjectVisitorContext::getTypeManager() const { return TKernelObject<IObjectVisitorContext>::getTypeManager(); } - ILogManager& CObjectVisitorContext::getLogManager() const { return TKernelObject<IObjectVisitorContext>::getLogManager(); } - IErrorManager& CObjectVisitorContext::getErrorManager() const { return TKernelObject<IObjectVisitorContext>::getErrorManager(); } diff --git a/kernel/src/kernel/ovkCObjectVisitorContext.h b/kernel/src/kernel/ovkCObjectVisitorContext.h index 747bd54cf20d2e5a2203c6a34383432bd66f4c6a..188ffe0abe0b275ccd75f64efb10416bef0ecdac 100644 --- a/kernel/src/kernel/ovkCObjectVisitorContext.h +++ b/kernel/src/kernel/ovkCObjectVisitorContext.h @@ -2,23 +2,21 @@ #include "ovkTKernelObject.h" -namespace OpenViBE +namespace OpenViBE { +namespace Kernel { +class CObjectVisitorContext final : public TKernelObject<IObjectVisitorContext> { - namespace Kernel - { - class CObjectVisitorContext final : public TKernelObject<IObjectVisitorContext> - { - public: +public: - explicit CObjectVisitorContext(const IKernelContext& ctx); - ~CObjectVisitorContext() override; - IAlgorithmManager& getAlgorithmManager() const override; - IConfigurationManager& getConfigurationManager() const override; - ITypeManager& getTypeManager() const override; - ILogManager& getLogManager() const override; - IErrorManager& getErrorManager() const override; + explicit CObjectVisitorContext(const IKernelContext& ctx); + ~CObjectVisitorContext() override; + IAlgorithmManager& getAlgorithmManager() const override; + IConfigurationManager& getConfigurationManager() const override; + ITypeManager& getTypeManager() const override; + ILogManager& getLogManager() const override; + IErrorManager& getErrorManager() const override; - _IsDerivedFromClass_Final_(TKernelObject<IObjectVisitorContext>, OVK_ClassId_Kernel_ObjectVisitorContext) - }; - } // namespace Kernel -} // namespace OpenViBE + _IsDerivedFromClass_Final_(TKernelObject<IObjectVisitorContext>, OVK_ClassId_Kernel_ObjectVisitorContext) +}; +} // namespace Kernel +} // namespace OpenViBE diff --git a/kernel/src/kernel/ovkCParameter.h b/kernel/src/kernel/ovkCParameter.h index bf6f88b9f1e6cd092f63936d75dd69afd5cfdf12..9861ffc22546427b9979425c3122345996568f87 100644 --- a/kernel/src/kernel/ovkCParameter.h +++ b/kernel/src/kernel/ovkCParameter.h @@ -5,10 +5,8 @@ #include <cstring> -namespace OpenViBE -{ - namespace Kernel - { +namespace OpenViBE { +namespace Kernel { #define _parameter_template_instance_simple_type_(_CName_, CType, IType, oClassId) \ typedef TBaseParameter<TKernelObject<IParameter>, IType> _Base_##_CName_; \ class _CName_ : public _Base_##_CName_ \ @@ -58,32 +56,30 @@ namespace OpenViBE CType m_defaultValue; \ }; - _parameter_template_instance_simple_type_(CIntegerParameter, int64_t, int64_t, OVK_ClassId_Kernel_IntegerParameter) +_parameter_template_instance_simple_type_(CIntegerParameter, int64_t, int64_t, OVK_ClassId_Kernel_IntegerParameter) - _parameter_template_instance_simple_type_(CUIntegerParameter, uint64_t, uint64_t, OVK_ClassId_Kernel_UIntegerParameter) +_parameter_template_instance_simple_type_(CUIntegerParameter, uint64_t, uint64_t, OVK_ClassId_Kernel_UIntegerParameter) - _parameter_template_instance_simple_type_(CEnumerationParameter, uint64_t, uint64_t, OVK_ClassId_Kernel_EnumerationParameter) +_parameter_template_instance_simple_type_(CEnumerationParameter, uint64_t, uint64_t, OVK_ClassId_Kernel_EnumerationParameter) - _parameter_template_instance_simple_type_(CBooleanParameter, bool, bool, OVK_ClassId_Kernel_BooleanParameter) +_parameter_template_instance_simple_type_(CBooleanParameter, bool, bool, OVK_ClassId_Kernel_BooleanParameter) - _parameter_template_instance_simple_type_(CFloatParameter, double, double, OVK_ClassId_Kernel_FloatParameter) +_parameter_template_instance_simple_type_(CFloatParameter, double, double, OVK_ClassId_Kernel_FloatParameter) - _parameter_template_instance_object_(CStringParameter, CString, CString*, OVK_ClassId_Kernel_StringParameter) +_parameter_template_instance_object_(CStringParameter, CString, CString*, OVK_ClassId_Kernel_StringParameter) - _parameter_template_instance_object_(CIdentifierParameter, CIdentifier, CIdentifier*, OVK_ClassId_Kernel_IdentifierParameter) +_parameter_template_instance_object_(CIdentifierParameter, CIdentifier, CIdentifier*, OVK_ClassId_Kernel_IdentifierParameter) - _parameter_template_instance_object_(CMatrixParameter, CMatrix, IMatrix*, OVK_ClassId_Kernel_MatrixParameter) +_parameter_template_instance_object_(CMatrixParameter, CMatrix, IMatrix*, OVK_ClassId_Kernel_MatrixParameter) - _parameter_template_instance_object_(CStimulationSetParameter, CStimulationSet, IStimulationSet*, - OVK_ClassId_Kernel_StimulationSetParameter) +_parameter_template_instance_object_(CStimulationSetParameter, CStimulationSet, IStimulationSet*, OVK_ClassId_Kernel_StimulationSetParameter) - _parameter_template_instance_object_(CMemoryBufferParameter, CMemoryBuffer, IMemoryBuffer*, - OVK_ClassId_Kernel_MemoryBufferParameter) +_parameter_template_instance_object_(CMemoryBufferParameter, CMemoryBuffer, IMemoryBuffer*, OVK_ClassId_Kernel_MemoryBufferParameter) - _parameter_template_instance_object_(CObjectParameter, CNullObject, IObject*, OVK_ClassId_Kernel_ObjectParameter) +_parameter_template_instance_object_(CObjectParameter, CNullObject, IObject*, OVK_ClassId_Kernel_ObjectParameter) - _parameter_template_instance_pointer_(CPointerParameter, void*, void*, OVK_ClassId_Kernel_PointerParameter) +_parameter_template_instance_pointer_(CPointerParameter, void*, void*, OVK_ClassId_Kernel_PointerParameter) #undef _instance_ - } // namespace Kernel -} // namespace OpenViBE +} // namespace Kernel +} // namespace OpenViBE diff --git a/kernel/src/kernel/ovkCTypeManager.cpp b/kernel/src/kernel/ovkCTypeManager.cpp index 43439e301e117669863b03f40fdfb3159da05ded..e9e5b32a37a9ff23724b7e167f41800ceb46fe6e 100755 --- a/kernel/src/kernel/ovkCTypeManager.cpp +++ b/kernel/src/kernel/ovkCTypeManager.cpp @@ -15,19 +15,18 @@ using namespace OpenViBE; using namespace /*OpenViBE::*/Kernel; -namespace +namespace { +// because std::tolower has multiple signatures, +// it can not be easily used in std::transform +// this workaround is taken from http://www.gcek.net/ref/books/sw/cpp/ticppv2/ +template <class TCharT> +TCharT ToLower(TCharT c) { return std::tolower(c); } + +struct SAInfB { - // because std::tolower has multiple signatures, - // it can not be easily used in std::transform - // this workaround is taken from http://www.gcek.net/ref/books/sw/cpp/ticppv2/ - template <class TCharT> - TCharT ToLower(TCharT c) { return std::tolower(c); } - - struct SAInfB - { - bool operator()(const std::pair<CIdentifier, CString> a, const std::pair<CIdentifier, CString>& b) const { return a.second < b.second; } - }; -} // namespace + bool operator()(const std::pair<CIdentifier, CString> a, const std::pair<CIdentifier, CString>& b) const { return a.second < b.second; } +}; +} // namespace CTypeManager::CTypeManager(const IKernelContext& ctx) : TKernelObject<ITypeManager>(ctx) diff --git a/kernel/src/kernel/ovkCTypeManager.h b/kernel/src/kernel/ovkCTypeManager.h index 806e4add56638b3fd6cf0f8e8ff9fa2530bef00b..2a203e417ae548ba6a0c7c6f148e944cebbb57c7 100755 --- a/kernel/src/kernel/ovkCTypeManager.h +++ b/kernel/src/kernel/ovkCTypeManager.h @@ -7,53 +7,51 @@ #include <vector> #include <mutex> -namespace OpenViBE +namespace OpenViBE { +namespace Kernel { +class CTypeManager final : public TKernelObject<ITypeManager> { - namespace Kernel - { - class CTypeManager final : public TKernelObject<ITypeManager> - { - public: - - explicit CTypeManager(const IKernelContext& ctx); - CIdentifier getNextTypeIdentifier(const CIdentifier& previousID) const override; - std::vector<std::pair<CIdentifier, CString>> getSortedTypes() const override; - bool registerType(const CIdentifier& typeID, const CString& name) override; - bool registerStreamType(const CIdentifier& typeID, const CString& name, const CIdentifier& parentTypeID) override; - bool registerEnumerationType(const CIdentifier& typeID, const CString& name) override; - bool registerEnumerationEntry(const CIdentifier& typeID, const CString& name, uint64_t value) override; - bool registerBitMaskType(const CIdentifier& typeID, const CString& name) override; - bool registerBitMaskEntry(const CIdentifier& typeID, const CString& name, uint64_t value) override; - bool isRegistered(const CIdentifier& typeID) const override; - bool isStream(const CIdentifier& typeID) const override; - bool isDerivedFromStream(const CIdentifier& typeID, const CIdentifier& parentTypeID) const override; - bool isEnumeration(const CIdentifier& typeID) const override; - bool isBitMask(const CIdentifier& typeID) const override; - CString getTypeName(const CIdentifier& typeID) const override; - CIdentifier getStreamParentType(const CIdentifier& typeID) const override; - size_t getEnumerationEntryCount(const CIdentifier& typeID) const override; - bool getEnumerationEntry(const CIdentifier& typeID, uint64_t index, CString& name, uint64_t& value) const override; - CString getEnumerationEntryNameFromValue(const CIdentifier& typeID, uint64_t value) const override; - uint64_t getEnumerationEntryValueFromName(const CIdentifier& typeID, const CString& name) const override; - size_t getBitMaskEntryCount(const CIdentifier& typeID) const override; - bool getBitMaskEntry(const CIdentifier& typeID, uint64_t index, CString& name, uint64_t& value) const override; - CString getBitMaskEntryNameFromValue(const CIdentifier& typeID, uint64_t value) const override; - uint64_t getBitMaskEntryValueFromName(const CIdentifier& typeID, const CString& name) const override; - CString getBitMaskEntryCompositionNameFromValue(const CIdentifier& typeID, uint64_t value) const override; - uint64_t getBitMaskEntryCompositionValueFromName(const CIdentifier& typeID, const CString& name) const override; - bool evaluateSettingValue(CString value, double& result) const override; - - _IsDerivedFromClass_Final_(TKernelObject<ITypeManager>, OVK_ClassId_Kernel_TypeManager) - - protected: - - std::map<CIdentifier, CString> m_names; - std::set<CString> m_takenNames; - std::map<CIdentifier, std::map<uint64_t, CString>> m_enumerations; - std::map<CIdentifier, std::map<uint64_t, CString>> m_bitMasks; - std::map<CIdentifier, CIdentifier> m_streams; - - mutable std::recursive_mutex m_mutex; - }; - } // namespace Kernel -} // namespace OpenViBE +public: + + explicit CTypeManager(const IKernelContext& ctx); + CIdentifier getNextTypeIdentifier(const CIdentifier& previousID) const override; + std::vector<std::pair<CIdentifier, CString>> getSortedTypes() const override; + bool registerType(const CIdentifier& typeID, const CString& name) override; + bool registerStreamType(const CIdentifier& typeID, const CString& name, const CIdentifier& parentTypeID) override; + bool registerEnumerationType(const CIdentifier& typeID, const CString& name) override; + bool registerEnumerationEntry(const CIdentifier& typeID, const CString& name, uint64_t value) override; + bool registerBitMaskType(const CIdentifier& typeID, const CString& name) override; + bool registerBitMaskEntry(const CIdentifier& typeID, const CString& name, uint64_t value) override; + bool isRegistered(const CIdentifier& typeID) const override; + bool isStream(const CIdentifier& typeID) const override; + bool isDerivedFromStream(const CIdentifier& typeID, const CIdentifier& parentTypeID) const override; + bool isEnumeration(const CIdentifier& typeID) const override; + bool isBitMask(const CIdentifier& typeID) const override; + CString getTypeName(const CIdentifier& typeID) const override; + CIdentifier getStreamParentType(const CIdentifier& typeID) const override; + size_t getEnumerationEntryCount(const CIdentifier& typeID) const override; + bool getEnumerationEntry(const CIdentifier& typeID, uint64_t index, CString& name, uint64_t& value) const override; + CString getEnumerationEntryNameFromValue(const CIdentifier& typeID, uint64_t value) const override; + uint64_t getEnumerationEntryValueFromName(const CIdentifier& typeID, const CString& name) const override; + size_t getBitMaskEntryCount(const CIdentifier& typeID) const override; + bool getBitMaskEntry(const CIdentifier& typeID, uint64_t index, CString& name, uint64_t& value) const override; + CString getBitMaskEntryNameFromValue(const CIdentifier& typeID, uint64_t value) const override; + uint64_t getBitMaskEntryValueFromName(const CIdentifier& typeID, const CString& name) const override; + CString getBitMaskEntryCompositionNameFromValue(const CIdentifier& typeID, uint64_t value) const override; + uint64_t getBitMaskEntryCompositionValueFromName(const CIdentifier& typeID, const CString& name) const override; + bool evaluateSettingValue(CString value, double& result) const override; + + _IsDerivedFromClass_Final_(TKernelObject<ITypeManager>, OVK_ClassId_Kernel_TypeManager) + +protected: + + std::map<CIdentifier, CString> m_names; + std::set<CString> m_takenNames; + std::map<CIdentifier, std::map<uint64_t, CString>> m_enumerations; + std::map<CIdentifier, std::map<uint64_t, CString>> m_bitMasks; + std::map<CIdentifier, CIdentifier> m_streams; + + mutable std::recursive_mutex m_mutex; +}; +} // namespace Kernel +} // namespace OpenViBE diff --git a/kernel/src/kernel/ovkTConfigurable.h b/kernel/src/kernel/ovkTConfigurable.h index dcb39f31f6b8d8ff780ab53aea29a4dc2450f7ba..d97d000de048b54c80f98b44d5dcec1d32652dee 100644 --- a/kernel/src/kernel/ovkTConfigurable.h +++ b/kernel/src/kernel/ovkTConfigurable.h @@ -6,111 +6,109 @@ #include <map> -namespace OpenViBE -{ - namespace Kernel - { - class IParameter; +namespace OpenViBE { +namespace Kernel { +class IParameter; - template <class TBase> - class TBaseConfigurable : public TBase - { - public: +template <class TBase> +class TBaseConfigurable : public TBase +{ +public: - explicit TBaseConfigurable(const IKernelContext& ctx) : TBase(ctx) { } + explicit TBaseConfigurable(const IKernelContext& ctx) : TBase(ctx) { } - ~TBaseConfigurable() override + ~TBaseConfigurable() override + { + auto itParameter = m_parameters.begin(); + while (itParameter != m_parameters.end()) + { + // @FIXME is this really as intended, test the first, delete the second? + if (itParameter->second.first) { - auto itParameter = m_parameters.begin(); - while (itParameter != m_parameters.end()) - { - // @FIXME is this really as intended, test the first, delete the second? - if (itParameter->second.first) - { - delete itParameter->second.second; - itParameter->second.second = nullptr; - } - ++itParameter; - } + delete itParameter->second.second; + itParameter->second.second = nullptr; } + ++itParameter; + } + } - CIdentifier getNextParameterIdentifier(const CIdentifier& previousID) const override - { - return getNextIdentifier<std::pair<bool, IParameter*>>(m_parameters, previousID); - } + CIdentifier getNextParameterIdentifier(const CIdentifier& previousID) const override + { + return getNextIdentifier<std::pair<bool, IParameter*>>(m_parameters, previousID); + } - IParameter* getParameter(const CIdentifier& parameterID) override - { - const auto it = m_parameters.find(parameterID); - if (it == m_parameters.end()) { return nullptr; } - return it->second.second; - } + IParameter* getParameter(const CIdentifier& parameterID) override + { + const auto it = m_parameters.find(parameterID); + if (it == m_parameters.end()) { return nullptr; } + return it->second.second; + } - bool setParameter(const CIdentifier& parameterID, IParameter& parameter) override - { - this->removeParameter(parameterID); + bool setParameter(const CIdentifier& parameterID, IParameter& parameter) override + { + this->removeParameter(parameterID); - m_parameters[parameterID] = std::pair<bool, IParameter*>(false, ¶meter); + m_parameters[parameterID] = std::pair<bool, IParameter*>(false, ¶meter); - return true; - } + return true; + } - IParameter* createParameter(const CIdentifier& parameterID, const EParameterType parameterType, const CIdentifier& subTypeID) override - { - const auto it = m_parameters.find(parameterID); - if (it != m_parameters.end()) { return nullptr; } - - IParameter* parameter = nullptr; - switch (parameterType) - { - case ParameterType_UInteger: parameter = new CUIntegerParameter(this->getKernelContext(), parameterType); - break; - case ParameterType_Integer: parameter = new CIntegerParameter(this->getKernelContext(), parameterType); - break; - case ParameterType_Enumeration: parameter = new CEnumerationParameter(this->getKernelContext(), parameterType, subTypeID); - break; - case ParameterType_Boolean: parameter = new CBooleanParameter(this->getKernelContext(), parameterType); - break; - case ParameterType_Float: parameter = new CFloatParameter(this->getKernelContext(), parameterType); - break; - case ParameterType_String: parameter = new CStringParameter(this->getKernelContext(), parameterType); - break; - case ParameterType_Identifier: parameter = new CIdentifierParameter(this->getKernelContext(), parameterType); - break; - case ParameterType_Matrix: parameter = new CMatrixParameter(this->getKernelContext(), parameterType); - break; - case ParameterType_StimulationSet: parameter = new CStimulationSetParameter(this->getKernelContext(), parameterType); - break; - case ParameterType_MemoryBuffer: parameter = new CMemoryBufferParameter(this->getKernelContext(), parameterType); - break; - case ParameterType_Object: parameter = new CObjectParameter(this->getKernelContext(), parameterType); - break; - case ParameterType_None: - case ParameterType_Pointer: parameter = new CPointerParameter(this->getKernelContext(), parameterType); - break; - } - - if (parameter != nullptr) { m_parameters[parameterID] = std::pair<bool, IParameter*>(true, parameter); } - - return parameter; - } + IParameter* createParameter(const CIdentifier& parameterID, const EParameterType parameterType, const CIdentifier& subTypeID) override + { + const auto it = m_parameters.find(parameterID); + if (it != m_parameters.end()) { return nullptr; } - bool removeParameter(const CIdentifier& rParameterIdentifier) override - { - auto itParameter = m_parameters.find(rParameterIdentifier); - if (itParameter == m_parameters.end()) { return false; } + IParameter* parameter = nullptr; + switch (parameterType) + { + case ParameterType_UInteger: parameter = new CUIntegerParameter(this->getKernelContext(), parameterType); + break; + case ParameterType_Integer: parameter = new CIntegerParameter(this->getKernelContext(), parameterType); + break; + case ParameterType_Enumeration: parameter = new CEnumerationParameter(this->getKernelContext(), parameterType, subTypeID); + break; + case ParameterType_Boolean: parameter = new CBooleanParameter(this->getKernelContext(), parameterType); + break; + case ParameterType_Float: parameter = new CFloatParameter(this->getKernelContext(), parameterType); + break; + case ParameterType_String: parameter = new CStringParameter(this->getKernelContext(), parameterType); + break; + case ParameterType_Identifier: parameter = new CIdentifierParameter(this->getKernelContext(), parameterType); + break; + case ParameterType_Matrix: parameter = new CMatrixParameter(this->getKernelContext(), parameterType); + break; + case ParameterType_StimulationSet: parameter = new CStimulationSetParameter(this->getKernelContext(), parameterType); + break; + case ParameterType_MemoryBuffer: parameter = new CMemoryBufferParameter(this->getKernelContext(), parameterType); + break; + case ParameterType_Object: parameter = new CObjectParameter(this->getKernelContext(), parameterType); + break; + case ParameterType_None: + case ParameterType_Pointer: parameter = new CPointerParameter(this->getKernelContext(), parameterType); + break; + } + + if (parameter != nullptr) { m_parameters[parameterID] = std::pair<bool, IParameter*>(true, parameter); } + + return parameter; + } + + bool removeParameter(const CIdentifier& rParameterIdentifier) override + { + auto itParameter = m_parameters.find(rParameterIdentifier); + if (itParameter == m_parameters.end()) { return false; } - if (itParameter->second.first) { delete itParameter->second.second; } - m_parameters.erase(itParameter); + if (itParameter->second.first) { delete itParameter->second.second; } + m_parameters.erase(itParameter); - return true; - } + return true; + } - _IsDerivedFromClass_Final_(TBase, OVK_ClassId_Kernel_ConfigurableT) + _IsDerivedFromClass_Final_(TBase, OVK_ClassId_Kernel_ConfigurableT) - private: +private: - std::map<CIdentifier, std::pair<bool, IParameter*>> m_parameters; - }; - } // namespace Kernel -} // namespace OpenViBE + std::map<CIdentifier, std::pair<bool, IParameter*>> m_parameters; +}; +} // namespace Kernel +} // namespace OpenViBE diff --git a/kernel/src/kernel/ovkTKernelObject.h b/kernel/src/kernel/ovkTKernelObject.h index 1cfb9f52980d7b48c6f2f655efc1f6b457ef7051..e1c66a871dfbab47d3b3efa395b78aa21648946b 100755 --- a/kernel/src/kernel/ovkTKernelObject.h +++ b/kernel/src/kernel/ovkTKernelObject.h @@ -4,40 +4,38 @@ #include <openvibe/ov_all.h> -namespace OpenViBE +namespace OpenViBE { +namespace Kernel { +template <class T> +class TKernelObject : public T { - namespace Kernel - { - template <class T> - class TKernelObject : public T - { - public: - virtual ~TKernelObject() = default; - - explicit TKernelObject(const IKernelContext& ctx) : m_kernelCtx(ctx) { } - - TKernelObject(const TKernelObject&) = delete; - TKernelObject& operator=(const TKernelObject&) = delete; - - const IKernelContext& getKernelContext() const { return m_kernelCtx; } - virtual IAlgorithmManager& getAlgorithmManager() const { return m_kernelCtx.getAlgorithmManager(); } - virtual IConfigurationManager& getConfigurationManager() const { return m_kernelCtx.getConfigurationManager(); } - virtual IKernelObjectFactory& getKernelObjectFactory() const { return m_kernelCtx.getKernelObjectFactory(); } - virtual IPlayerManager& getPlayerManager() const { return m_kernelCtx.getPlayerManager(); } - virtual IPluginManager& getPluginManager() const { return m_kernelCtx.getPluginManager(); } - virtual IMetaboxManager& getMetaboxManager() const { return m_kernelCtx.getMetaboxManager(); } - virtual IScenarioManager& getScenarioManager() const { return m_kernelCtx.getScenarioManager(); } - virtual ITypeManager& getTypeManager() const { return m_kernelCtx.getTypeManager(); } - virtual ILogManager& getLogManager() const { return m_kernelCtx.getLogManager(); } - virtual IErrorManager& getErrorManager() const { return m_kernelCtx.getErrorManager(); } - - _IsDerivedFromClass_(T, OVK_ClassId_Kernel_KernelObjectT) - - private: - - const IKernelContext& m_kernelCtx; - - // TKernelObject(); - }; - } // namespace Kernel -} // namespace OpenViBE +public: + virtual ~TKernelObject() = default; + + explicit TKernelObject(const IKernelContext& ctx) : m_kernelCtx(ctx) { } + + TKernelObject(const TKernelObject&) = delete; + TKernelObject& operator=(const TKernelObject&) = delete; + + const IKernelContext& getKernelContext() const { return m_kernelCtx; } + virtual IAlgorithmManager& getAlgorithmManager() const { return m_kernelCtx.getAlgorithmManager(); } + virtual IConfigurationManager& getConfigurationManager() const { return m_kernelCtx.getConfigurationManager(); } + virtual IKernelObjectFactory& getKernelObjectFactory() const { return m_kernelCtx.getKernelObjectFactory(); } + virtual IPlayerManager& getPlayerManager() const { return m_kernelCtx.getPlayerManager(); } + virtual IPluginManager& getPluginManager() const { return m_kernelCtx.getPluginManager(); } + virtual IMetaboxManager& getMetaboxManager() const { return m_kernelCtx.getMetaboxManager(); } + virtual IScenarioManager& getScenarioManager() const { return m_kernelCtx.getScenarioManager(); } + virtual ITypeManager& getTypeManager() const { return m_kernelCtx.getTypeManager(); } + virtual ILogManager& getLogManager() const { return m_kernelCtx.getLogManager(); } + virtual IErrorManager& getErrorManager() const { return m_kernelCtx.getErrorManager(); } + + _IsDerivedFromClass_(T, OVK_ClassId_Kernel_KernelObjectT) + +private: + + const IKernelContext& m_kernelCtx; + + // TKernelObject(); +}; +} // namespace Kernel +} // namespace OpenViBE diff --git a/kernel/src/kernel/ovkTParameter.h b/kernel/src/kernel/ovkTParameter.h index 655b860148536754e0a48db5cec0f3afe6847844..6ce735f1878dd686de4c71b84ab77b31abae237d 100644 --- a/kernel/src/kernel/ovkTParameter.h +++ b/kernel/src/kernel/ovkTParameter.h @@ -4,80 +4,78 @@ #include <cstring> -namespace OpenViBE +namespace OpenViBE { +namespace Kernel { +template <class TBase, class TType> +class TBaseParameter : public TBase { - namespace Kernel - { - template <class TBase, class TType> - class TBaseParameter : public TBase - { - public: +public: - TBaseParameter(const IKernelContext& ctx, const EParameterType type, const CIdentifier& subTypeID = OV_UndefinedIdentifier) - : TBase(ctx), m_valueRef(nullptr), m_value(0), m_parameterType(type), m_subTypeID(subTypeID) { } + TBaseParameter(const IKernelContext& ctx, const EParameterType type, const CIdentifier& subTypeID = OV_UndefinedIdentifier) + : TBase(ctx), m_valueRef(nullptr), m_value(0), m_parameterType(type), m_subTypeID(subTypeID) { } - uint64_t getParameterSize() const override { return sizeof(TType); } - EParameterType getType() const override { return m_parameterType; } - CIdentifier getSubTypeIdentifier() const override { return m_subTypeID; } + uint64_t getParameterSize() const override { return sizeof(TType); } + EParameterType getType() const override { return m_parameterType; } + CIdentifier getSubTypeIdentifier() const override { return m_subTypeID; } - bool clearReferenceTarget() override - { - m_valueRef = NULL; - m_parameterRef = nullptr; - return true; - } + bool clearReferenceTarget() override + { + m_valueRef = NULL; + m_parameterRef = nullptr; + return true; + } - bool getReferenceTarget(IParameter*& pParameterRef) const override - { - pParameterRef = m_parameterRef; - return true; - } + bool getReferenceTarget(IParameter*& pParameterRef) const override + { + pParameterRef = m_parameterRef; + return true; + } - bool setReferenceTarget(IParameter* pParameterRef) override - { - if (m_valueRef) { m_valueRef = NULL; } - m_parameterRef = pParameterRef; - return true; - } + bool setReferenceTarget(IParameter* pParameterRef) override + { + if (m_valueRef) { m_valueRef = NULL; } + m_parameterRef = pParameterRef; + return true; + } - bool getReferenceTarget(void* pValue) const override - { - memcpy(&pValue, &m_valueRef, sizeof(TType*)); - return true; - } + bool getReferenceTarget(void* pValue) const override + { + memcpy(&pValue, &m_valueRef, sizeof(TType*)); + return true; + } - bool setReferenceTarget(const void* pValue) override - { - if (m_parameterRef) { m_parameterRef = nullptr; } - memcpy(&m_valueRef, &pValue, sizeof(TType*)); - return true; - } + bool setReferenceTarget(const void* pValue) override + { + if (m_parameterRef) { m_parameterRef = nullptr; } + memcpy(&m_valueRef, &pValue, sizeof(TType*)); + return true; + } - bool getValue(void* pValue) const override - { - if (m_parameterRef) { return m_parameterRef->getValue(pValue); } - if (m_valueRef) { memcpy(pValue, m_valueRef, sizeof(TType)); } - else { memcpy(pValue, &m_value, sizeof(TType)); } - return true; - } + bool getValue(void* pValue) const override + { + if (m_parameterRef) { return m_parameterRef->getValue(pValue); } + if (m_valueRef) { memcpy(pValue, m_valueRef, sizeof(TType)); } + else { memcpy(pValue, &m_value, sizeof(TType)); } + return true; + } - bool setValue(const void* pValue) override - { - if (m_parameterRef) { return m_parameterRef->setValue(pValue); } - if (m_valueRef) { memcpy(m_valueRef, pValue, sizeof(TType)); } - else { memcpy(&m_value, pValue, sizeof(TType)); } - return true; - } + bool setValue(const void* pValue) override + { + if (m_parameterRef) { return m_parameterRef->setValue(pValue); } + if (m_valueRef) { memcpy(m_valueRef, pValue, sizeof(TType)); } + else { memcpy(&m_value, pValue, sizeof(TType)); } + return true; + } - _IsDerivedFromClass_(TBase, OVK_ClassId_Kernel_ParameterT) + _IsDerivedFromClass_(TBase, OVK_ClassId_Kernel_ParameterT) - protected: +protected: - IParameter* m_parameterRef = nullptr; - TType* m_valueRef = nullptr; - TType m_value; - EParameterType m_parameterType; - CIdentifier m_subTypeID = OV_UndefinedIdentifier; - }; - } // namespace Kernel -} // namespace OpenViBE + IParameter* m_parameterRef = nullptr; + TType* m_valueRef = nullptr; + TType m_value; + EParameterType m_parameterType; + CIdentifier m_subTypeID = OV_UndefinedIdentifier; +}; +} // namespace Kernel +} // namespace OpenViBE diff --git a/kernel/src/kernel/player/ovkCBoxAlgorithmContext.h b/kernel/src/kernel/player/ovkCBoxAlgorithmContext.h index 50997d7fb457d701322048753e980f91d555d3d8..8bee8283460a884854b757432a85ceadfebc1fad 100644 --- a/kernel/src/kernel/player/ovkCBoxAlgorithmContext.h +++ b/kernel/src/kernel/player/ovkCBoxAlgorithmContext.h @@ -3,35 +3,33 @@ #include "../ovkTKernelObject.h" #include "ovkCPlayerContext.h" -namespace OpenViBE +namespace OpenViBE { +namespace Kernel { +class CSimulatedBox; + +class CBoxAlgorithmCtx final : public TKernelObject<IBoxAlgorithmContext> { - namespace Kernel - { - class CSimulatedBox; - - class CBoxAlgorithmCtx final : public TKernelObject<IBoxAlgorithmContext> - { - public: - - CBoxAlgorithmCtx(const IKernelContext& ctx, CSimulatedBox* pSimulatedBox, const IBox* pBox); - ~CBoxAlgorithmCtx() override {} - const IBox* getStaticBoxContext() override { return m_pStaticBoxContext; } - IBoxIO* getDynamicBoxContext() override { return m_pDynamicBoxContext; } - IPlayerContext* getPlayerContext() override { return &m_oPlayerContext; } - bool markAlgorithmAsReadyToProcess() override; - - _IsDerivedFromClass_Final_(TKernelObject<IBoxAlgorithmContext>, OVK_ClassId_Kernel_Player_BoxAlgorithmContext) - - bool isAlgorithmReadyToProcess() const { return m_bReadyToProcess; } - - protected: - - const IBox* m_pStaticBoxContext = nullptr; - IBoxIO* m_pDynamicBoxContext = nullptr; - // here we prefer value type over reference/pointer - // in order to improve performance at runtime (no heap allocation) - CPlayerContext m_oPlayerContext; - bool m_bReadyToProcess = false; - }; - } // namespace Kernel -} // namespace OpenViBE +public: + + CBoxAlgorithmCtx(const IKernelContext& ctx, CSimulatedBox* pSimulatedBox, const IBox* pBox); + ~CBoxAlgorithmCtx() override {} + const IBox* getStaticBoxContext() override { return m_pStaticBoxContext; } + IBoxIO* getDynamicBoxContext() override { return m_pDynamicBoxContext; } + IPlayerContext* getPlayerContext() override { return &m_oPlayerContext; } + bool markAlgorithmAsReadyToProcess() override; + + _IsDerivedFromClass_Final_(TKernelObject<IBoxAlgorithmContext>, OVK_ClassId_Kernel_Player_BoxAlgorithmContext) + + bool isAlgorithmReadyToProcess() const { return m_bReadyToProcess; } + +protected: + + const IBox* m_pStaticBoxContext = nullptr; + IBoxIO* m_pDynamicBoxContext = nullptr; + // here we prefer value type over reference/pointer + // in order to improve performance at runtime (no heap allocation) + CPlayerContext m_oPlayerContext; + bool m_bReadyToProcess = false; +}; +} // namespace Kernel +} // namespace OpenViBE diff --git a/kernel/src/kernel/player/ovkCBoxAlgorithmLogManager.cpp b/kernel/src/kernel/player/ovkCBoxAlgorithmLogManager.cpp index b14639feb7de409fc46a7aa9e4dbc14ac572b01b..f94911ac7e702d8e3542130fadf54f50d1eddddb 100644 --- a/kernel/src/kernel/player/ovkCBoxAlgorithmLogManager.cpp +++ b/kernel/src/kernel/player/ovkCBoxAlgorithmLogManager.cpp @@ -13,5 +13,5 @@ void CBoxAlgorithmLogManager::log(const ELogLevel logLevel) << "Box algorithm" << LogColor_PopStateBit << "::" << boxId << " aka " << m_simulatedBox.getName() << "> "; } -} // namespace Kernel -} // namespace OpenViBE +} // namespace Kernel +} // namespace OpenViBE diff --git a/kernel/src/kernel/player/ovkCBoxAlgorithmLogManager.h b/kernel/src/kernel/player/ovkCBoxAlgorithmLogManager.h index 7d9fb926c77113b3348cc2f19a447b7b519df5f4..a038c1e7e4bdc4d716376e95253121de0a84db87 100644 --- a/kernel/src/kernel/player/ovkCBoxAlgorithmLogManager.h +++ b/kernel/src/kernel/player/ovkCBoxAlgorithmLogManager.h @@ -48,5 +48,5 @@ private: CSimulatedBox& m_simulatedBox; }; -} // namespace Kernel -} // namespace OpenViBE +} // namespace Kernel +} // namespace OpenViBE diff --git a/kernel/src/kernel/player/ovkCBoxSettingModifierVisitor.h b/kernel/src/kernel/player/ovkCBoxSettingModifierVisitor.h index a88b562002fb457a4f30e2fc9fdc075730d7eb84..6fa79d2df6772750f11848d60baae70e6cb9bac8 100644 --- a/kernel/src/kernel/player/ovkCBoxSettingModifierVisitor.h +++ b/kernel/src/kernel/player/ovkCBoxSettingModifierVisitor.h @@ -10,31 +10,29 @@ #define OVD_AttributeId_SettingOverrideFilename OpenViBE::CIdentifier(0x8D21FF41, 0xDF6AFE7E) -namespace OpenViBE +namespace OpenViBE { +namespace Kernel { +class CBoxSettingModifierVisitor final : public IObjectVisitor, public XML::IReaderCallback { - namespace Kernel - { - class CBoxSettingModifierVisitor final : public IObjectVisitor, public XML::IReaderCallback - { - public: - - explicit CBoxSettingModifierVisitor(IConfigurationManager* pConfigurationManager = nullptr) - : IObjectVisitor(), m_ConfigManager(pConfigurationManager) {} - - void openChild(const char* name, const char** sAttributeName, const char** sAttributeValue, const size_t nAttribute) override; - void processChildData(const char* data) override; - void closeChild() override; - bool processBegin(IObjectVisitorContext& visitorCtx, IBox& box) override; - bool processEnd(IObjectVisitorContext& visitorCtx, IBox& box) override; - - IObjectVisitorContext* m_ObjectVisitorCtx = nullptr; - IBox* m_Box = nullptr; - size_t m_SettingIdx = 0; - bool m_IsParsingSettingValue = false; - bool m_IsParsingSettingOverride = false; - IConfigurationManager* m_ConfigManager = nullptr; - - _IsDerivedFromClass_Final_(IObjectVisitor, OV_UndefinedIdentifier) - }; - } //namespace Kernel +public: + + explicit CBoxSettingModifierVisitor(IConfigurationManager* pConfigurationManager = nullptr) + : IObjectVisitor(), m_ConfigManager(pConfigurationManager) {} + + void openChild(const char* name, const char** sAttributeName, const char** sAttributeValue, const size_t nAttribute) override; + void processChildData(const char* data) override; + void closeChild() override; + bool processBegin(IObjectVisitorContext& visitorCtx, IBox& box) override; + bool processEnd(IObjectVisitorContext& visitorCtx, IBox& box) override; + + IObjectVisitorContext* m_ObjectVisitorCtx = nullptr; + IBox* m_Box = nullptr; + size_t m_SettingIdx = 0; + bool m_IsParsingSettingValue = false; + bool m_IsParsingSettingOverride = false; + IConfigurationManager* m_ConfigManager = nullptr; + + _IsDerivedFromClass_Final_(IObjectVisitor, OV_UndefinedIdentifier) +}; +} //namespace Kernel } //namespace OpenViBE diff --git a/kernel/src/kernel/player/ovkCBuffer.h b/kernel/src/kernel/player/ovkCBuffer.h index 40ef34d6f4379b6d4d41bd1fa6de5bf919c5f6aa..c58ceb4237eb685aeb190dd04db297890a99ea29 100644 --- a/kernel/src/kernel/player/ovkCBuffer.h +++ b/kernel/src/kernel/player/ovkCBuffer.h @@ -2,18 +2,16 @@ #include <openvibe/ov_all.h> -namespace OpenViBE +namespace OpenViBE { +namespace Kernel { +class CBuffer final : public CMemoryBuffer { - namespace Kernel - { - class CBuffer final : public CMemoryBuffer - { - public: +public: - CBuffer() { } - explicit CBuffer(const CBuffer& buffer); + CBuffer() { } + explicit CBuffer(const CBuffer& buffer); - CBuffer& operator=(const CBuffer& buffer); - }; - } // namespace Kernel -} // namespace OpenViBE + CBuffer& operator=(const CBuffer& buffer); +}; +} // namespace Kernel +} // namespace OpenViBE diff --git a/kernel/src/kernel/player/ovkCMessageClock.h b/kernel/src/kernel/player/ovkCMessageClock.h deleted file mode 100644 index e812887987c1e76568e40c4d8a67ce766ee4f345..0000000000000000000000000000000000000000 --- a/kernel/src/kernel/player/ovkCMessageClock.h +++ /dev/null @@ -1,22 +0,0 @@ -#pragma once - -#include "../ovkTKernelObject.h" -#include "ovkTMessage.h" - -#include <openvibe/ov_all.h> - -namespace OpenViBE -{ - namespace Kernel - { - class CMessageClock final : public TMessage<TKernelObject<IMessageClock>> - { - public: - - explicit CMessageClock(const IKernelContext& ctx) - : TMessage<TKernelObject<IMessageClock>>(ctx) { } - - _IsDerivedFromClass_Final_(TMessage<TKernelObject<IMessageClock>>, OVK_ClassId_Kernel_Player_MessageClock) - }; - } // namespace Kernel -} // namespace OpenViBE diff --git a/kernel/src/kernel/player/ovkCMessageEvent.h b/kernel/src/kernel/player/ovkCMessageEvent.h deleted file mode 100644 index 133c4cba050556505d9687acb3889a7737ac967d..0000000000000000000000000000000000000000 --- a/kernel/src/kernel/player/ovkCMessageEvent.h +++ /dev/null @@ -1,22 +0,0 @@ -#pragma once - -#include "../ovkTKernelObject.h" -#include "ovkTMessage.h" - -#include <openvibe/ov_all.h> - -namespace OpenViBE -{ - namespace Kernel - { - class CMessageEvent final : public TMessage<TKernelObject<IMessageEvent>> - { - public: - - explicit CMessageEvent(const IKernelContext& ctx) - : TMessage<TKernelObject<IMessageEvent>>(ctx) { } - - _IsDerivedFromClass_Final_(TMessage<TKernelObject<IMessageEvent>>, OVK_ClassId_Kernel_Player_MessageEvent) - }; - } // namespace Kernel -} // namespace OpenViBE diff --git a/kernel/src/kernel/player/ovkCMessageSignal.h b/kernel/src/kernel/player/ovkCMessageSignal.h deleted file mode 100644 index e36a134f5690d93e9d1149a9edfbb6bbf3b383ae..0000000000000000000000000000000000000000 --- a/kernel/src/kernel/player/ovkCMessageSignal.h +++ /dev/null @@ -1,22 +0,0 @@ -#pragma once - -#include "../ovkTKernelObject.h" -#include "ovkTMessage.h" - -#include <openvibe/ov_all.h> - -namespace OpenViBE -{ - namespace Kernel - { - class CMessageSignal final : public TMessage<TKernelObject<IMessageSignal>> - { - public: - - explicit CMessageSignal(const IKernelContext& ctx) - : TMessage<TKernelObject<IMessageSignal>>(ctx) { } - - _IsDerivedFromClass_Final_(TMessage<TKernelObject<IMessageSignal>>, OVK_ClassId_Kernel_Player_MessageSignal) - }; - } // namespace Kernel -} // namespace OpenViBE diff --git a/kernel/src/kernel/player/ovkCPlayer.cpp b/kernel/src/kernel/player/ovkCPlayer.cpp index 8bd3204612812c3a4532ea0163b444d193d88b01..9ee52d0f845e17850c5a31f6ef5e5c7c8d74dfe4 100644 --- a/kernel/src/kernel/player/ovkCPlayer.cpp +++ b/kernel/src/kernel/player/ovkCPlayer.cpp @@ -1,4 +1,3 @@ - #include "ovkCPlayer.h" #include "ovkCSimulatedBox.h" #include "ovkCScheduler.h" @@ -240,9 +239,7 @@ bool CPlayer::setFastForwardMaximumFactor(const double fastForwardFactor) } double CPlayer::getFastForwardMaximumFactor() const { return m_fastForwardMaximumFactor; } - double CPlayer::getCPUUsage() const { return m_scheduler.getCPUUsage(); } - bool CPlayer::isHoldingResources() const { return m_scheduler.isHoldingResources(); } bool CPlayer::loop(const uint64_t elapsedTime, const uint64_t maximumTimeToReach) diff --git a/kernel/src/kernel/player/ovkCPlayer.h b/kernel/src/kernel/player/ovkCPlayer.h index 0033c840e5cbea116b4ec4e81bc97f5508a79827..33d82ad3d791127ef0291f51b4c64de123cfcc34 100644 --- a/kernel/src/kernel/player/ovkCPlayer.h +++ b/kernel/src/kernel/player/ovkCPlayer.h @@ -9,69 +9,67 @@ #include <string> -namespace OpenViBE +namespace OpenViBE { +namespace Kernel { +class CScenarioSettingKeywordParserCallback; + +class CPlayer final : public TKernelObject<IPlayer> { - namespace Kernel - { - class CScenarioSettingKeywordParserCallback; - - class CPlayer final : public TKernelObject<IPlayer> - { - public: - - explicit CPlayer(const IKernelContext& ctx); - ~CPlayer() override; - bool setScenario(const CIdentifier& scenarioID, const CNameValuePairList* localConfigurationTokens) override; - IConfigurationManager& getRuntimeConfigurationManager() const override; - IScenarioManager& getRuntimeScenarioManager() const override; - CIdentifier getRuntimeScenarioIdentifier() const override; - - - bool isHoldingResources() const; - EPlayerReturnCodes initialize() override; - bool uninitialize() override; - bool stop() override; - bool pause() override; - bool step() override; - bool play() override; - bool forward() override; - EPlayerStatus getStatus() const override; - bool setFastForwardMaximumFactor(double fastForwardFactor) override; - double getFastForwardMaximumFactor() const override; - double getCPUUsage() const override; - bool loop(uint64_t elapsedTime, uint64_t maximumTimeToReach) override; - uint64_t getCurrentSimulatedTime() const override; - uint64_t getCurrentSimulatedLateness() const; - - - _IsDerivedFromClass_Final_(TKernelObject<IPlayer>, OVK_ClassId_Kernel_Player_Player) - - protected: - - CKernelContextBridge m_kernelCtxBridge; - IConfigurationManager* m_runtimeConfigManager = nullptr; - IScenarioManager* m_runtimeScenarioManager = nullptr; - CScenarioSettingKeywordParserCallback* m_scenarioSettingKeywordParserCB = nullptr; - - CScheduler m_scheduler; - - uint64_t m_currentTimeToReach = 0; - uint64_t m_lateness = 0; - uint64_t m_innerLateness = 0; - EPlayerStatus m_status = EPlayerStatus::Stop; - bool m_isInitializing = false; - double m_fastForwardMaximumFactor = 0; - - std::string m_scenarioConfigFile; - std::string m_workspaceConfigFile; - - // Stores the identifier of the scenario that is being played - CIdentifier m_scenarioID = OV_UndefinedIdentifier; - - private: - CIdentifier m_runtimeScenarioID = OV_UndefinedIdentifier; - - System::CChrono m_benchmarkChrono; - }; - } // namespace Kernel -} // namespace OpenViBE +public: + + explicit CPlayer(const IKernelContext& ctx); + ~CPlayer() override; + bool setScenario(const CIdentifier& scenarioID, const CNameValuePairList* localConfigurationTokens) override; + IConfigurationManager& getRuntimeConfigurationManager() const override; + IScenarioManager& getRuntimeScenarioManager() const override; + CIdentifier getRuntimeScenarioIdentifier() const override; + + + bool isHoldingResources() const; + EPlayerReturnCodes initialize() override; + bool uninitialize() override; + bool stop() override; + bool pause() override; + bool step() override; + bool play() override; + bool forward() override; + EPlayerStatus getStatus() const override; + bool setFastForwardMaximumFactor(double fastForwardFactor) override; + double getFastForwardMaximumFactor() const override; + double getCPUUsage() const override; + bool loop(uint64_t elapsedTime, uint64_t maximumTimeToReach) override; + uint64_t getCurrentSimulatedTime() const override; + uint64_t getCurrentSimulatedLateness() const; + + + _IsDerivedFromClass_Final_(TKernelObject<IPlayer>, OVK_ClassId_Kernel_Player_Player) + +protected: + + CKernelContextBridge m_kernelCtxBridge; + IConfigurationManager* m_runtimeConfigManager = nullptr; + IScenarioManager* m_runtimeScenarioManager = nullptr; + CScenarioSettingKeywordParserCallback* m_scenarioSettingKeywordParserCB = nullptr; + + CScheduler m_scheduler; + + uint64_t m_currentTimeToReach = 0; + uint64_t m_lateness = 0; + uint64_t m_innerLateness = 0; + EPlayerStatus m_status = EPlayerStatus::Stop; + bool m_isInitializing = false; + double m_fastForwardMaximumFactor = 0; + + std::string m_scenarioConfigFile; + std::string m_workspaceConfigFile; + + // Stores the identifier of the scenario that is being played + CIdentifier m_scenarioID = OV_UndefinedIdentifier; + +private: + CIdentifier m_runtimeScenarioID = OV_UndefinedIdentifier; + + System::CChrono m_benchmarkChrono; +}; +} // namespace Kernel +} // namespace OpenViBE diff --git a/kernel/src/kernel/player/ovkCPlayerContext.cpp b/kernel/src/kernel/player/ovkCPlayerContext.cpp index 0784d45af5596e5416dba4c91ac3f2126535a534..6b613a722bd03b39f7a5c16dbf8dee0d4de253a1 100644 --- a/kernel/src/kernel/player/ovkCPlayerContext.cpp +++ b/kernel/src/kernel/player/ovkCPlayerContext.cpp @@ -12,41 +12,14 @@ CPlayerContext::CPlayerContext(const IKernelContext& ctx, CSimulatedBox* pSimula m_logManager(ctx.getLogManager()), m_errorManager(ctx.getErrorManager()), m_scenarioManager(ctx.getScenarioManager()), m_typeManager(ctx.getTypeManager()), m_boxLogManager(*this, m_logManager, m_simulatedBox) {} -bool CPlayerContext::sendSignal(const CMessageSignal& /*messageSignal*/) -{ - // TODO - this->getLogManager() << LogLevel_Debug << "CPlayerContext::sendSignal - Not yet implemented\n"; - return false; -} - -bool CPlayerContext::sendMessage(const CMessageEvent& /*messageEvent*/, const CIdentifier& /*dstID*/) -{ - // TODO - this->getLogManager() << LogLevel_Debug << "CPlayerContext::sendMessage - Not yet implemented\n"; - return false; -} - -bool CPlayerContext::sendMessage(const CMessageEvent& /*messageEvent*/, const CIdentifier* /*dstID*/, const size_t /*nDstID*/) -{ - // TODO - this->getLogManager() << LogLevel_Debug << "CPlayerContext::sendMessage - Not yet implemented\n"; - return false; -} - uint64_t CPlayerContext::getCurrentTime() const { return m_simulatedBox.getScheduler().getCurrentTime(); } - uint64_t CPlayerContext::getCurrentLateness() const { return m_simulatedBox.getScheduler().getCurrentLateness(); } - double CPlayerContext::getCurrentCPUUsage() const { return m_simulatedBox.getScheduler().getCPUUsage(); } - double CPlayerContext::getCurrentFastForwardMaximumFactor() const { return m_simulatedBox.getScheduler().getFastForwardMaximumFactor(); } bool CPlayerContext::stop() { return m_simulatedBox.getScheduler().getPlayer().stop(); } - bool CPlayerContext::pause() { return m_simulatedBox.getScheduler().getPlayer().pause(); } - bool CPlayerContext::play() { return m_simulatedBox.getScheduler().getPlayer().play(); } - bool CPlayerContext::forward() { return m_simulatedBox.getScheduler().getPlayer().forward(); } EPlayerStatus CPlayerContext::getStatus() const { return m_simulatedBox.getScheduler().getPlayer().getStatus(); } diff --git a/kernel/src/kernel/player/ovkCPlayerContext.h b/kernel/src/kernel/player/ovkCPlayerContext.h index 474f043471881ac944ce231d3bc4f2e1c86dc0be..23fe5c1b6b779d468664b25e7d8791e83495a84c 100644 --- a/kernel/src/kernel/player/ovkCPlayerContext.h +++ b/kernel/src/kernel/player/ovkCPlayerContext.h @@ -3,55 +3,51 @@ #include "ovkCBoxAlgorithmLogManager.h" #include "../ovkTKernelObject.h" -namespace OpenViBE +namespace OpenViBE { +namespace Kernel { +class CSimulatedBox; + +class CPlayerContext final : public TKernelObject<IPlayerContext> { - namespace Kernel - { - class CSimulatedBox; - - class CPlayerContext final : public TKernelObject<IPlayerContext> - { - public: - - CPlayerContext(const IKernelContext& ctx, CSimulatedBox* pSimulatedBox); - ~CPlayerContext() override { } - bool sendSignal(const CMessageSignal& messageSignal) override; - bool sendMessage(const CMessageEvent& messageEvent, const CIdentifier& dstID) override; - bool sendMessage(const CMessageEvent& messageEvent, const CIdentifier* dstID, const size_t nDstID) override; - uint64_t getCurrentTime() const override; - uint64_t getCurrentLateness() const override; - double getCurrentCPUUsage() const override; - double getCurrentFastForwardMaximumFactor() const override; - bool stop() override; - bool pause() override; - bool play() override; - bool forward() override; - EPlayerStatus getStatus() const override; - - //@} - IAlgorithmManager& getAlgorithmManager() const override { return m_algorithmManager; } - IConfigurationManager& getConfigurationManager() const override { return m_configManager; } - ILogManager& getLogManager() const override { return m_boxLogManager; } - IErrorManager& getErrorManager() const override { return m_errorManager; } - IScenarioManager& getScenarioManager() const override { return m_scenarioManager; } - ITypeManager& getTypeManager() const override { return m_typeManager; } - bool canCreatePluginObject(const CIdentifier& pluginID) const override { return m_pluginManager.canCreatePluginObject(pluginID); } - Plugins::IPluginObject* createPluginObject(const CIdentifier& pluginID) const override { return m_pluginManager.createPluginObject(pluginID); } - bool releasePluginObject(Plugins::IPluginObject* pluginObject) const override { return m_pluginManager.releasePluginObject(pluginObject); } - - _IsDerivedFromClass_Final_(TKernelObject<IPlayerContext>, OVK_ClassId_Kernel_Player_PlayerContext) - - private: - - CSimulatedBox& m_simulatedBox; - IPluginManager& m_pluginManager; - IAlgorithmManager& m_algorithmManager; - IConfigurationManager& m_configManager; - ILogManager& m_logManager; - IErrorManager& m_errorManager; - IScenarioManager& m_scenarioManager; - ITypeManager& m_typeManager; - mutable CBoxAlgorithmLogManager m_boxLogManager; - }; - } // namespace Kernel -} // namespace OpenViBE +public: + + CPlayerContext(const IKernelContext& ctx, CSimulatedBox* pSimulatedBox); + ~CPlayerContext() override { } + + uint64_t getCurrentTime() const override; + uint64_t getCurrentLateness() const override; + double getCurrentCPUUsage() const override; + double getCurrentFastForwardMaximumFactor() const override; + + bool stop() override; + bool pause() override; + bool play() override; + bool forward() override; + EPlayerStatus getStatus() const override; + + IAlgorithmManager& getAlgorithmManager() const override { return m_algorithmManager; } + IConfigurationManager& getConfigurationManager() const override { return m_configManager; } + ILogManager& getLogManager() const override { return m_boxLogManager; } + IErrorManager& getErrorManager() const override { return m_errorManager; } + IScenarioManager& getScenarioManager() const override { return m_scenarioManager; } + ITypeManager& getTypeManager() const override { return m_typeManager; } + bool canCreatePluginObject(const CIdentifier& pluginID) const override { return m_pluginManager.canCreatePluginObject(pluginID); } + Plugins::IPluginObject* createPluginObject(const CIdentifier& pluginID) const override { return m_pluginManager.createPluginObject(pluginID); } + bool releasePluginObject(Plugins::IPluginObject* pluginObject) const override { return m_pluginManager.releasePluginObject(pluginObject); } + + _IsDerivedFromClass_Final_(TKernelObject<IPlayerContext>, OVK_ClassId_Kernel_Player_PlayerContext) + +private: + + CSimulatedBox& m_simulatedBox; + IPluginManager& m_pluginManager; + IAlgorithmManager& m_algorithmManager; + IConfigurationManager& m_configManager; + ILogManager& m_logManager; + IErrorManager& m_errorManager; + IScenarioManager& m_scenarioManager; + ITypeManager& m_typeManager; + mutable CBoxAlgorithmLogManager m_boxLogManager; +}; +} // namespace Kernel +} // namespace OpenViBE diff --git a/kernel/src/kernel/player/ovkCPlayerManager.h b/kernel/src/kernel/player/ovkCPlayerManager.h index 01a8722b0d3febde7805f1a47f6a4ec7d6bc9ee3..493fc12ea7e03f6c3b5c4cd3253fb3712a87e4c7 100644 --- a/kernel/src/kernel/player/ovkCPlayerManager.h +++ b/kernel/src/kernel/player/ovkCPlayerManager.h @@ -4,29 +4,27 @@ #include <map> -namespace OpenViBE -{ - namespace Kernel - { - class CPlayer; +namespace OpenViBE { +namespace Kernel { +class CPlayer; - class CPlayerManager final : public TKernelObject<IPlayerManager> - { - public: +class CPlayerManager final : public TKernelObject<IPlayerManager> +{ +public: - explicit CPlayerManager(const IKernelContext& ctx) : TKernelObject<IPlayerManager>(ctx) {} - bool createPlayer(CIdentifier& playerID) override; - bool releasePlayer(const CIdentifier& playerID) override; - IPlayer& getPlayer(const CIdentifier& playerID) override; - CIdentifier getNextPlayerIdentifier(const CIdentifier& previousID) const override { return getNextIdentifier<CPlayer*>(m_players, previousID); } + explicit CPlayerManager(const IKernelContext& ctx) : TKernelObject<IPlayerManager>(ctx) {} + bool createPlayer(CIdentifier& playerID) override; + bool releasePlayer(const CIdentifier& playerID) override; + IPlayer& getPlayer(const CIdentifier& playerID) override; + CIdentifier getNextPlayerIdentifier(const CIdentifier& previousID) const override { return getNextIdentifier<CPlayer*>(m_players, previousID); } - _IsDerivedFromClass_Final_(TKernelObject<IPlayerManager>, OVK_ClassId_Kernel_Player_PlayerManager) + _IsDerivedFromClass_Final_(TKernelObject<IPlayerManager>, OVK_ClassId_Kernel_Player_PlayerManager) - protected: +protected: - CIdentifier getUnusedIdentifier() const; + CIdentifier getUnusedIdentifier() const; - std::map<CIdentifier, CPlayer*> m_players; - }; - } // namespace Kernel -} // namespace OpenViBE + std::map<CIdentifier, CPlayer*> m_players; +}; +} // namespace Kernel +} // namespace OpenViBE diff --git a/kernel/src/kernel/player/ovkCScheduler.cpp b/kernel/src/kernel/player/ovkCScheduler.cpp index d95c54c7eb57b47d9608663812e44b50b81852e4..481c8270641e186ee43ed2f646c935d14d160805 100755 --- a/kernel/src/kernel/player/ovkCScheduler.cpp +++ b/kernel/src/kernel/player/ovkCScheduler.cpp @@ -292,8 +292,7 @@ bool CScheduler::flattenScenario() CIdentifier srcBoxOutputID = OV_UndefinedIdentifier; if (srcBoxID != OV_UndefinedIdentifier) { - m_scenario->getBoxDetails(correspondenceID[srcBoxID])->getInterfacorIdentifier( - Output, srcBoxOutputIdx, srcBoxOutputID); + m_scenario->getBoxDetails(correspondenceID[srcBoxID])->getInterfacorIdentifier(Output, srcBoxOutputIdx, srcBoxOutputID); link->setSource(correspondenceID[srcBoxID], srcBoxOutputIdx, srcBoxOutputID); } @@ -488,8 +487,7 @@ bool CScheduler::uninitialize() } } - for (auto it = m_simulatedBoxes.begin(); it != m_simulatedBoxes.end(); ++ - it) { delete it->second; } + for (auto it = m_simulatedBoxes.begin(); it != m_simulatedBoxes.end(); ++it) { delete it->second; } m_simulatedBoxes.clear(); m_scenario = nullptr; diff --git a/kernel/src/kernel/player/ovkCScheduler.h b/kernel/src/kernel/player/ovkCScheduler.h index 34757c8b832e3cd9a4b6464470a6c123af9fca3c..dbcc53fa1aac91851a91e5cc5f0355930f1e478c 100644 --- a/kernel/src/kernel/player/ovkCScheduler.h +++ b/kernel/src/kernel/player/ovkCScheduler.h @@ -5,64 +5,62 @@ #include <map> #include <list> -namespace OpenViBE -{ - namespace Kernel - { - enum class ESchedulerInitialization { Success, BoxInitializationFailed, Failed }; +namespace OpenViBE { +namespace Kernel { +enum class ESchedulerInitialization { Success, BoxInitializationFailed, Failed }; - class CSimulatedBox; - class CChunk; - class CPlayer; +class CSimulatedBox; +class CChunk; +class CPlayer; - class CScheduler final : public TKernelObject<IKernelObject> - { - public: +class CScheduler final : public TKernelObject<IKernelObject> +{ +public: - CScheduler(const IKernelContext& ctx, CPlayer& player); - ~CScheduler() override; + CScheduler(const IKernelContext& ctx, CPlayer& player); + ~CScheduler() override; - bool setScenario(const CIdentifier& scenarioID); - bool setFrequency(uint64_t frequency); + bool setScenario(const CIdentifier& scenarioID); + bool setFrequency(uint64_t frequency); - bool isHoldingResources() const; + bool isHoldingResources() const; - ESchedulerInitialization initialize(); - bool uninitialize(); - bool loop(); + ESchedulerInitialization initialize(); + bool uninitialize(); + bool loop(); - bool sendInput(const CChunk& chunk, const CIdentifier& boxId, size_t index); - uint64_t getCurrentTime() const { return m_currentTime; } - uint64_t getCurrentLateness() const; - uint64_t getFrequency() const { return m_frequency; } - uint64_t getStepDuration() const { return m_stepDuration; } - double getCPUUsage() const { return (const_cast<System::CChrono&>(m_oBenchmarkChrono)).getStepInPercentage(); } - double getFastForwardMaximumFactor() const; + bool sendInput(const CChunk& chunk, const CIdentifier& boxId, size_t index); + uint64_t getCurrentTime() const { return m_currentTime; } + uint64_t getCurrentLateness() const; + uint64_t getFrequency() const { return m_frequency; } + uint64_t getStepDuration() const { return m_stepDuration; } + double getCPUUsage() const { return (const_cast<System::CChrono&>(m_oBenchmarkChrono)).getStepInPercentage(); } + double getFastForwardMaximumFactor() const; - _IsDerivedFromClass_Final_(TKernelObject<IKernelObject>, OVK_ClassId_Kernel_Player_Scheduler) + _IsDerivedFromClass_Final_(TKernelObject<IKernelObject>, OVK_ClassId_Kernel_Player_Scheduler) - CPlayer& getPlayer() const { return m_rPlayer; } + CPlayer& getPlayer() const { return m_rPlayer; } - protected: +protected: - CPlayer& m_rPlayer; - CIdentifier m_scenarioID = OV_UndefinedIdentifier; - IScenario* m_scenario = nullptr; - size_t m_steps = 0; - uint64_t m_frequency = 0; - uint64_t m_stepDuration = 0; - uint64_t m_currentTime = 0; + CPlayer& m_rPlayer; + CIdentifier m_scenarioID = OV_UndefinedIdentifier; + IScenario* m_scenario = nullptr; + size_t m_steps = 0; + uint64_t m_frequency = 0; + uint64_t m_stepDuration = 0; + uint64_t m_currentTime = 0; - std::map<std::pair<int, CIdentifier>, CSimulatedBox*> m_simulatedBoxes; - std::map<CIdentifier, System::CChrono> m_simulatedBoxChronos; - std::map<CIdentifier, std::map<size_t, std::list<CChunk>>> m_simulatedBoxInputs; + std::map<std::pair<int, CIdentifier>, CSimulatedBox*> m_simulatedBoxes; + std::map<CIdentifier, System::CChrono> m_simulatedBoxChronos; + std::map<CIdentifier, std::map<size_t, std::list<CChunk>>> m_simulatedBoxInputs; - private: +private: - void handleException(const CSimulatedBox* box, const char* errorHint, const std::exception& exception); - bool processBox(CSimulatedBox* simulatedBox, const CIdentifier& boxID); - bool flattenScenario(); - System::CChrono m_oBenchmarkChrono; - }; - } // namespace Kernel -} // namespace OpenViBE + void handleException(const CSimulatedBox* box, const char* errorHint, const std::exception& exception); + bool processBox(CSimulatedBox* simulatedBox, const CIdentifier& boxID); + bool flattenScenario(); + System::CChrono m_oBenchmarkChrono; +}; +} // namespace Kernel +} // namespace OpenViBE diff --git a/kernel/src/kernel/player/ovkCSimulatedBox.cpp b/kernel/src/kernel/player/ovkCSimulatedBox.cpp index 007026d7fdca4b8b09cd8fd18df29fdcf439ee8a..cfa0e3814d54c55429636146661447a561592bf2 100644 --- a/kernel/src/kernel/player/ovkCSimulatedBox.cpp +++ b/kernel/src/kernel/player/ovkCSimulatedBox.cpp @@ -3,9 +3,6 @@ #include "ovkCSimulatedBox.h" #include "ovkCPlayer.h" #include "ovkCBoxAlgorithmContext.h" -#include "ovkCMessageClock.h" -#include "ovkCMessageEvent.h" - #include <cstdlib> #include <algorithm> @@ -138,7 +135,7 @@ bool CSimulatedBox::processClock() if (m_lastClockActivationDate == OV_IncorrectTime) { m_lastClockActivationDate = m_scheduler.getCurrentTime(); } else { m_lastClockActivationDate = m_lastClockActivationDate + m_clockActivationStep; } - CMessageClock message(this->getKernelContext()); + Kernel::CMessageClock message; message.setTime(m_lastClockActivationDate); OV_ERROR_UNLESS_KRF(m_boxAlgorithm->processClock(context, message), diff --git a/kernel/src/kernel/player/ovkCSimulatedBox.h b/kernel/src/kernel/player/ovkCSimulatedBox.h index 457a8471f3db120d293161c04f5319c90c2936bf..a102eaac9c6dae0798b5637164f2ef4db245f450 100644 --- a/kernel/src/kernel/player/ovkCSimulatedBox.h +++ b/kernel/src/kernel/player/ovkCSimulatedBox.h @@ -8,121 +8,119 @@ #include <string> #include <deque> -namespace OpenViBE +namespace OpenViBE { +namespace Kernel { +class CScheduler; + +class CChunk { - namespace Kernel +public: + + CChunk() { } + + CChunk(const CChunk& chunk) : m_buffer(chunk.m_buffer), m_startTime(chunk.m_startTime), m_endTime(chunk.m_endTime) { } + + const CBuffer& getBuffer() const { return m_buffer; } + uint64_t getStartTime() const { return m_startTime; } + uint64_t getEndTime() const { return m_endTime; } + bool isDeprecated() const { return m_isDeprecated; } + CBuffer& getBuffer() { return m_buffer; } + + bool setStartTime(const uint64_t startTime) + { + m_startTime = startTime; + return true; + } + + bool setEndTime(const uint64_t endTime) { - class CScheduler; - - class CChunk - { - public: - - CChunk() { } - - CChunk(const CChunk& chunk) : m_buffer(chunk.m_buffer), m_startTime(chunk.m_startTime), m_endTime(chunk.m_endTime) { } - - const CBuffer& getBuffer() const { return m_buffer; } - uint64_t getStartTime() const { return m_startTime; } - uint64_t getEndTime() const { return m_endTime; } - bool isDeprecated() const { return m_isDeprecated; } - CBuffer& getBuffer() { return m_buffer; } - - bool setStartTime(const uint64_t startTime) - { - m_startTime = startTime; - return true; - } - - bool setEndTime(const uint64_t endTime) - { - m_endTime = endTime; - return true; - } - - bool markAsDeprecated(const bool isDeprecated) - { - m_isDeprecated = isDeprecated; - return true; - } - - protected: - - CBuffer m_buffer; - uint64_t m_startTime = 0; - uint64_t m_endTime = 0; - bool m_isDeprecated = false; - }; - - class CSimulatedBox final : public TKernelObject<IBoxIO> - { - public: - - CSimulatedBox(const IKernelContext& ctx, CScheduler& scheduler); - ~CSimulatedBox() override; - - bool setScenarioIdentifier(const CIdentifier& scenarioID); - bool getBoxIdentifier(CIdentifier& boxId) const; - bool setBoxIdentifier(const CIdentifier& boxId); - - bool initialize(); - bool uninitialize(); - - bool processClock(); - bool processInput(const size_t index, const CChunk& chunk); - bool process(); - bool isReadyToProcess() const; - - CString getName() const; - const IScenario& getScenario() const; - - /** \name IBoxIO inputs handling */ - //@{ - size_t getInputChunkCount(const size_t index) const override; - bool getInputChunk(const size_t inputIdx, const size_t chunkIdx, uint64_t& startTime, uint64_t& endTime, size_t& size, - const uint8_t*& buffer) const override; - const IMemoryBuffer* getInputChunk(const size_t inputIdx, const size_t chunkIdx) const override; - uint64_t getInputChunkStartTime(const size_t inputIdx, const size_t chunkIdx) const override; - uint64_t getInputChunkEndTime(const size_t inputIdx, const size_t chunkIdx) const override; - bool markInputAsDeprecated(const size_t inputIdx, const size_t chunkIdx) override; - //@} - - /** \name IBoxIO outputs handling */ - //@{ - size_t getOutputChunkSize(const size_t outputIdx) const override; - bool setOutputChunkSize(const size_t outputIdx, const size_t size, const bool discard = true) override; - uint8_t* getOutputChunkBuffer(const size_t outputIdx) override; - bool appendOutputChunkData(const size_t outputIdx, const uint8_t* buffer, const size_t size) override; - IMemoryBuffer* getOutputChunk(const size_t outputIdx) override; - bool markOutputAsReadyToSend(const size_t outputIdx, const uint64_t startTime, const uint64_t endTime) override; - //@} - - _IsDerivedFromClass_Final_(TKernelObject<IBoxIO>, OVK_ClassId_Kernel_Player_SimulatedBox) - - CScheduler& getScheduler() const { return m_scheduler; } - - protected: - - bool m_readyToProcess = false; - bool m_chunkConsistencyChecking = false; - ELogLevel m_chunkConsistencyCheckingLogLevel = LogLevel_Warning; - - Plugins::IBoxAlgorithm* m_boxAlgorithm = nullptr; - const IScenario* m_scenario = nullptr; - const IBox* m_box = nullptr; - CScheduler& m_scheduler; - - uint64_t m_lastClockActivationDate = 0; - uint64_t m_clockFrequency = 0; - uint64_t m_clockActivationStep = 0; - - public: - - std::vector<std::deque<CChunk>> m_Inputs; - std::vector<std::deque<CChunk>> m_Outputs; - std::vector<CChunk> m_CurrentOutputs; - std::vector<uint64_t> m_LastOutputStartTimes; - std::vector<uint64_t> m_LastOutputEndTimes; - }; - } // namespace Kernel -} // namespace OpenViBE + m_endTime = endTime; + return true; + } + + bool markAsDeprecated(const bool isDeprecated) + { + m_isDeprecated = isDeprecated; + return true; + } + +protected: + + CBuffer m_buffer; + uint64_t m_startTime = 0; + uint64_t m_endTime = 0; + bool m_isDeprecated = false; +}; + +class CSimulatedBox final : public TKernelObject<IBoxIO> +{ +public: + + CSimulatedBox(const IKernelContext& ctx, CScheduler& scheduler); + ~CSimulatedBox() override; + + bool setScenarioIdentifier(const CIdentifier& scenarioID); + bool getBoxIdentifier(CIdentifier& boxId) const; + bool setBoxIdentifier(const CIdentifier& boxId); + + bool initialize(); + bool uninitialize(); + + bool processClock(); + bool processInput(const size_t index, const CChunk& chunk); + bool process(); + bool isReadyToProcess() const; + + CString getName() const; + const IScenario& getScenario() const; + + /** \name IBoxIO inputs handling */ + //@{ + size_t getInputChunkCount(const size_t index) const override; + bool getInputChunk(const size_t inputIdx, const size_t chunkIdx, uint64_t& startTime, uint64_t& endTime, size_t& size, + const uint8_t*& buffer) const override; + const IMemoryBuffer* getInputChunk(const size_t inputIdx, const size_t chunkIdx) const override; + uint64_t getInputChunkStartTime(const size_t inputIdx, const size_t chunkIdx) const override; + uint64_t getInputChunkEndTime(const size_t inputIdx, const size_t chunkIdx) const override; + bool markInputAsDeprecated(const size_t inputIdx, const size_t chunkIdx) override; + //@} + + /** \name IBoxIO outputs handling */ + //@{ + size_t getOutputChunkSize(const size_t outputIdx) const override; + bool setOutputChunkSize(const size_t outputIdx, const size_t size, const bool discard = true) override; + uint8_t* getOutputChunkBuffer(const size_t outputIdx) override; + bool appendOutputChunkData(const size_t outputIdx, const uint8_t* buffer, const size_t size) override; + IMemoryBuffer* getOutputChunk(const size_t outputIdx) override; + bool markOutputAsReadyToSend(const size_t outputIdx, const uint64_t startTime, const uint64_t endTime) override; + //@} + + _IsDerivedFromClass_Final_(TKernelObject<IBoxIO>, OVK_ClassId_Kernel_Player_SimulatedBox) + + CScheduler& getScheduler() const { return m_scheduler; } + +protected: + + bool m_readyToProcess = false; + bool m_chunkConsistencyChecking = false; + ELogLevel m_chunkConsistencyCheckingLogLevel = LogLevel_Warning; + + Plugins::IBoxAlgorithm* m_boxAlgorithm = nullptr; + const IScenario* m_scenario = nullptr; + const IBox* m_box = nullptr; + CScheduler& m_scheduler; + + uint64_t m_lastClockActivationDate = 0; + uint64_t m_clockFrequency = 0; + uint64_t m_clockActivationStep = 0; + +public: + + std::vector<std::deque<CChunk>> m_Inputs; + std::vector<std::deque<CChunk>> m_Outputs; + std::vector<CChunk> m_CurrentOutputs; + std::vector<uint64_t> m_LastOutputStartTimes; + std::vector<uint64_t> m_LastOutputEndTimes; +}; +} // namespace Kernel +} // namespace OpenViBE diff --git a/kernel/src/kernel/player/ovkTMessage.h b/kernel/src/kernel/player/ovkTMessage.h deleted file mode 100644 index aa2e11393d5f5a6a082965d3cdf9be8dfd277de1..0000000000000000000000000000000000000000 --- a/kernel/src/kernel/player/ovkTMessage.h +++ /dev/null @@ -1,32 +0,0 @@ -#pragma once - -#include <openvibe/ov_all.h> - -namespace OpenViBE -{ - namespace Kernel - { - template <class T> - class TMessage : public T - { - public: - - explicit TMessage(const IKernelContext& ctx); - - CIdentifier getIdentifier() const override; - uint64_t getTime() const override; - - bool setIdentifier(const CIdentifier& id) override; - bool setTime(const uint64_t time) override; - - _IsDerivedFromClass_Final_(T, OVK_ClassId_Kernel_Player_MessageT) - - protected: - - CIdentifier m_id = OV_UndefinedIdentifier; - uint64_t m_time = 0; - }; - } // namespace Kernel -} // namespace OpenViBE - -#include "ovkTMessage.inl" diff --git a/kernel/src/kernel/player/ovkTMessage.inl b/kernel/src/kernel/player/ovkTMessage.inl deleted file mode 100644 index a2be2ce6b4640a817169e43e8bf577acf539f5f6..0000000000000000000000000000000000000000 --- a/kernel/src/kernel/player/ovkTMessage.inl +++ /dev/null @@ -1,43 +0,0 @@ -#pragma once -#include "ovkTMessage.h" - -namespace OpenViBE -{ - namespace Kernel - { - - //___________________________________________________________________// - // // - - template <class T> - TMessage<T>::TMessage(const IKernelContext& ctx) - : T(ctx), m_id(OV_UndefinedIdentifier) {} - - //___________________________________________________________________// - // // - - template <class T> - CIdentifier TMessage<T>::getIdentifier() const { return m_id; } - - template <class T> - uint64_t TMessage<T>::getTime() const { return m_time; } - - template <class T> - bool TMessage<T>::setIdentifier(const CIdentifier& id) - { - if (m_id != OV_UndefinedIdentifier || id == OV_UndefinedIdentifier) { return false; } - m_id = id; - return true; - } - - template <class T> - bool TMessage<T>::setTime(const uint64_t time) - { - m_time = time; - return true; - } - - //___________________________________________________________________// - // // - } // namespace Kernel -} // namespace OpenViBE diff --git a/kernel/src/kernel/plugins/ovkCPluginManager.cpp b/kernel/src/kernel/plugins/ovkCPluginManager.cpp index 67f459849f70a0dab2dd82cc4df8a5cdba390c25..732013d3cb735e784f259492e7d729f382fbf47c 100755 --- a/kernel/src/kernel/plugins/ovkCPluginManager.cpp +++ b/kernel/src/kernel/plugins/ovkCPluginManager.cpp @@ -17,105 +17,103 @@ using namespace /*OpenViBE::*/Kernel; using namespace /*OpenViBE::*/Plugins; using namespace std; -namespace OpenViBE +namespace OpenViBE { +namespace Kernel { +class CPluginManagerEntryEnumeratorCallBack final : public TKernelObject<IObject>, public FS::IEntryEnumeratorCallBack { - namespace Kernel +public: + + CPluginManagerEntryEnumeratorCallBack(const IKernelContext& ctx, vector<IPluginModule*>& pluginModule, + map<IPluginObjectDesc*, IPluginModule*>& pluginObjectDesc, bool& haveAllPluginsLoadedCorrectly) + : TKernelObject<IObject>(ctx), m_rPluginManager(ctx.getPluginManager()), m_rPluginModule(pluginModule), + m_rPluginObjectDesc(pluginObjectDesc), m_HaveAllPluginsLoadedCorrectly(haveAllPluginsLoadedCorrectly) { } + + bool callback(FS::IEntryEnumerator::IEntry& entry, FS::IEntryEnumerator::IAttributes& /*attributes*/) override { - class CPluginManagerEntryEnumeratorCallBack final : public TKernelObject<IObject>, public FS::IEntryEnumeratorCallBack + for (auto& pluginModule : m_rPluginModule) { - public: + CString name; + if (!pluginModule->getFileName(name)) { return true; } - CPluginManagerEntryEnumeratorCallBack(const IKernelContext& ctx, vector<IPluginModule*>& pluginModule, - map<IPluginObjectDesc*, IPluginModule*>& pluginObjectDesc, bool& haveAllPluginsLoadedCorrectly) - : TKernelObject<IObject>(ctx), m_rPluginManager(ctx.getPluginManager()), m_rPluginModule(pluginModule), - m_rPluginObjectDesc(pluginObjectDesc), m_HaveAllPluginsLoadedCorrectly(haveAllPluginsLoadedCorrectly) { } - - bool callback(FS::IEntryEnumerator::IEntry& entry, FS::IEntryEnumerator::IAttributes& /*attributes*/) override + if (FS::Files::equals(entry.getName(), name.toASCIIString())) { - for (auto& pluginModule : m_rPluginModule) - { - CString name; - if (!pluginModule->getFileName(name)) { return true; } - - if (FS::Files::equals(entry.getName(), name.toASCIIString())) - { - OV_WARNING_K(std::string("Module [") + entry.getName() + "] has already been loaded"); - return true; - } - } + OV_WARNING_K(std::string("Module [") + entry.getName() + "] has already been loaded"); + return true; + } + } - IPluginModule* module = new CPluginModule(this->getKernelContext()); - CString loadError; - if (!module->load(entry.getName(), &loadError)) - { - delete module; - OV_WARNING_K(std::string("File [") + entry.getName() + "] is not a plugin module (error:" + loadError.toASCIIString() + ")"); - m_HaveAllPluginsLoadedCorrectly = false; - return true; - } + IPluginModule* module = new CPluginModule(this->getKernelContext()); + CString loadError; + if (!module->load(entry.getName(), &loadError)) + { + delete module; + OV_WARNING_K(std::string("File [") + entry.getName() + "] is not a plugin module (error:" + loadError.toASCIIString() + ")"); + m_HaveAllPluginsLoadedCorrectly = false; + return true; + } - if (!module->initialize()) + if (!module->initialize()) + { + module->uninitialize(); + module->unload(); + delete module; + OV_WARNING_K(std::string("Module [") + entry.getName() + "] did not initialize correctly"); + m_HaveAllPluginsLoadedCorrectly = false; + return true; + } + + bool pluginObjectDescAdded = false; + size_t index = 0; + size_t n = 0; + IPluginObjectDesc* desc = nullptr; + while (module->getPluginObjectDescription(index, desc)) + { + bool found = false; + + for (const auto& pluginObjectDesc : m_rPluginObjectDesc) + { + if (pluginObjectDesc.first->getClassIdentifier() == desc->getClassIdentifier()) { - module->uninitialize(); - module->unload(); - delete module; - OV_WARNING_K(std::string("Module [") + entry.getName() + "] did not initialize correctly"); - m_HaveAllPluginsLoadedCorrectly = false; - return true; + OV_WARNING_K("Duplicate plugin object descriptor class identifier [" + pluginObjectDesc.first->getName() + + "] and [" + desc->getName() + "]... second one is ignored"); + found = true; + break; } + } - bool pluginObjectDescAdded = false; - size_t index = 0; - size_t n = 0; - IPluginObjectDesc* desc = nullptr; - while (module->getPluginObjectDescription(index, desc)) + if (!found) + { + if (!pluginObjectDescAdded) { - bool found = false; - - for (const auto& pluginObjectDesc : m_rPluginObjectDesc) - { - if (pluginObjectDesc.first->getClassIdentifier() == desc->getClassIdentifier()) - { - OV_WARNING_K("Duplicate plugin object descriptor class identifier [" + pluginObjectDesc.first->getName() - + "] and [" + desc->getName() + "]... second one is ignored"); - found = true; - break; - } - } - - if (!found) - { - if (!pluginObjectDescAdded) - { - m_rPluginModule.push_back(module); - pluginObjectDescAdded = true; - } - m_rPluginObjectDesc[desc] = module; - n++; - } - index++; - desc = nullptr; + m_rPluginModule.push_back(module); + pluginObjectDescAdded = true; } + m_rPluginObjectDesc[desc] = module; + n++; + } + index++; + desc = nullptr; + } - OV_WARNING_UNLESS_K(pluginObjectDescAdded, - std::string("No 'plugin object descriptor' found from [") + entry.getName() + "] even if it looked like a plugin module\n"); + OV_WARNING_UNLESS_K(pluginObjectDescAdded, + std::string("No 'plugin object descriptor' found from [") + entry.getName() + "] even if it looked like a plugin module\n"); - this->getLogManager() << LogLevel_Info << "Added " << n << " plugin object descriptor(s) from [" << CString(entry.getName()) << "]\n"; + this->getLogManager() << LogLevel_Info << "Added " << n << " plugin object descriptor(s) from [" << CString(entry.getName()) << "]\n"; - return true; - } + return true; + } - _IsDerivedFromClass_Final_(TKernelObject<IObject>, OV_UndefinedIdentifier) + _IsDerivedFromClass_Final_(TKernelObject<IObject>, OV_UndefinedIdentifier) - protected: +protected: - IPluginManager& m_rPluginManager; - vector<IPluginModule*>& m_rPluginModule; - map<IPluginObjectDesc*, IPluginModule*>& m_rPluginObjectDesc; - bool& m_HaveAllPluginsLoadedCorrectly; - }; - } // namespace Kernel -} // namespace OpenViBE + IPluginManager& m_rPluginManager; + vector<IPluginModule*>& m_rPluginModule; + map<IPluginObjectDesc*, IPluginModule*>& m_rPluginObjectDesc; + bool& m_HaveAllPluginsLoadedCorrectly; +}; +} // namespace Kernel +} // namespace OpenViBE CPluginManager::~CPluginManager() { @@ -176,7 +174,7 @@ bool CPluginManager::registerPluginDesc(const IPluginObjectDesc& rPluginObjectDe { std::unique_lock<std::mutex> lock(m_mutex); - m_pluginObjectDescs[const_cast<IPluginObjectDesc *>(&rPluginObjectDesc)] = nullptr; + m_pluginObjectDescs[const_cast<IPluginObjectDesc*>(&rPluginObjectDesc)] = nullptr; return true; } diff --git a/kernel/src/kernel/plugins/ovkCPluginManager.h b/kernel/src/kernel/plugins/ovkCPluginManager.h index 6240fb75b02264ac09c70b73e99600db5b55194f..c6211005d7fe5c165f78cbc11f86997b8ddc8102 100755 --- a/kernel/src/kernel/plugins/ovkCPluginManager.h +++ b/kernel/src/kernel/plugins/ovkCPluginManager.h @@ -6,44 +6,42 @@ #include <map> #include <mutex> -namespace OpenViBE +namespace OpenViBE { +namespace Kernel { +class CPluginManager final : public TKernelObject<IPluginManager> { - namespace Kernel - { - class CPluginManager final : public TKernelObject<IPluginManager> - { - public: - - explicit CPluginManager(const IKernelContext& ctx) : TKernelObject<IPluginManager>(ctx) {} - ~CPluginManager() override; - bool addPluginsFromFiles(const CString& rFileNameWildCard) override; - bool registerPluginDesc(const Plugins::IPluginObjectDesc& rPluginObjectDesc) override; - CIdentifier getNextPluginObjectDescIdentifier(const CIdentifier& previousID) const override; - CIdentifier getNextPluginObjectDescIdentifier(const CIdentifier& previousID, const CIdentifier& baseClassID) const override; - bool canCreatePluginObject(const CIdentifier& classID) override; - const Plugins::IPluginObjectDesc* getPluginObjectDesc(const CIdentifier& classID) const override; - const Plugins::IPluginObjectDesc* getPluginObjectDescCreating(const CIdentifier& classID) const override; - CIdentifier getPluginObjectHashValue(const CIdentifier& classID) const override; - CIdentifier getPluginObjectHashValue(const Plugins::IBoxAlgorithmDesc& boxAlgorithmDesc) const override; - bool isPluginObjectFlaggedAsDeprecated(const CIdentifier& classID) const override; - Plugins::IPluginObject* createPluginObject(const CIdentifier& classID) override; - bool releasePluginObject(Plugins::IPluginObject* pluginObject) override; - Plugins::IAlgorithm* createAlgorithm(const CIdentifier& classID, const Plugins::IAlgorithmDesc** algorithmDesc) override; - Plugins::IAlgorithm* createAlgorithm(const Plugins::IAlgorithmDesc& algorithmDesc) override; - Plugins::IBoxAlgorithm* createBoxAlgorithm(const CIdentifier& classID, const Plugins::IBoxAlgorithmDesc** boxAlgorithmDesc) override; - - _IsDerivedFromClass_Final_(TKernelObject<IPluginManager>, OVK_ClassId_Kernel_Plugins_PluginManager) - - protected: - - template <class TPluginObject, class TPluginObjectDesc> - TPluginObject* createPluginObjectT(const CIdentifier& classID, const TPluginObjectDesc** ppPluginObjectDescT); - - std::vector<IPluginModule*> m_pluginModules; - std::map<Plugins::IPluginObjectDesc*, IPluginModule*> m_pluginObjectDescs; - std::map<Plugins::IPluginObjectDesc*, std::vector<Plugins::IPluginObject*>> m_pluginObjects; - - mutable std::mutex m_mutex; - }; - } // namespace Kernel -} // namespace OpenViBE +public: + + explicit CPluginManager(const IKernelContext& ctx) : TKernelObject<IPluginManager>(ctx) {} + ~CPluginManager() override; + bool addPluginsFromFiles(const CString& rFileNameWildCard) override; + bool registerPluginDesc(const Plugins::IPluginObjectDesc& rPluginObjectDesc) override; + CIdentifier getNextPluginObjectDescIdentifier(const CIdentifier& previousID) const override; + CIdentifier getNextPluginObjectDescIdentifier(const CIdentifier& previousID, const CIdentifier& baseClassID) const override; + bool canCreatePluginObject(const CIdentifier& classID) override; + const Plugins::IPluginObjectDesc* getPluginObjectDesc(const CIdentifier& classID) const override; + const Plugins::IPluginObjectDesc* getPluginObjectDescCreating(const CIdentifier& classID) const override; + CIdentifier getPluginObjectHashValue(const CIdentifier& classID) const override; + CIdentifier getPluginObjectHashValue(const Plugins::IBoxAlgorithmDesc& boxAlgorithmDesc) const override; + bool isPluginObjectFlaggedAsDeprecated(const CIdentifier& classID) const override; + Plugins::IPluginObject* createPluginObject(const CIdentifier& classID) override; + bool releasePluginObject(Plugins::IPluginObject* pluginObject) override; + Plugins::IAlgorithm* createAlgorithm(const CIdentifier& classID, const Plugins::IAlgorithmDesc** algorithmDesc) override; + Plugins::IAlgorithm* createAlgorithm(const Plugins::IAlgorithmDesc& algorithmDesc) override; + Plugins::IBoxAlgorithm* createBoxAlgorithm(const CIdentifier& classID, const Plugins::IBoxAlgorithmDesc** boxAlgorithmDesc) override; + + _IsDerivedFromClass_Final_(TKernelObject<IPluginManager>, OVK_ClassId_Kernel_Plugins_PluginManager) + +protected: + + template <class TPluginObject, class TPluginObjectDesc> + TPluginObject* createPluginObjectT(const CIdentifier& classID, const TPluginObjectDesc** ppPluginObjectDescT); + + std::vector<IPluginModule*> m_pluginModules; + std::map<Plugins::IPluginObjectDesc*, IPluginModule*> m_pluginObjectDescs; + std::map<Plugins::IPluginObjectDesc*, std::vector<Plugins::IPluginObject*>> m_pluginObjects; + + mutable std::mutex m_mutex; +}; +} // namespace Kernel +} // namespace OpenViBE diff --git a/kernel/src/kernel/plugins/ovkCPluginModule.cpp b/kernel/src/kernel/plugins/ovkCPluginModule.cpp index c4a3d0d94235d8ed95917154b3ec9520d6125dde..ec8541d40f2da75c8916e5c7ef2b7ba013e55e6d 100755 --- a/kernel/src/kernel/plugins/ovkCPluginModule.cpp +++ b/kernel/src/kernel/plugins/ovkCPluginModule.cpp @@ -15,68 +15,63 @@ using namespace OpenViBE; using namespace /*OpenViBE::*/Kernel; using namespace /*OpenViBE::*/Plugins; -namespace OpenViBE +namespace OpenViBE { +namespace Kernel { +class CPluginModuleBase : public TKernelObject<IPluginModule> { - namespace Kernel - { - class CPluginModuleBase : public TKernelObject<IPluginModule> - { - public: - explicit CPluginModuleBase(const IKernelContext& ctx) - : TKernelObject<IPluginModule>(ctx), m_onInitializeCB(nullptr), m_onGetPluginObjectDescCB(nullptr), m_onUninitializeCB(nullptr) {} +public: + explicit CPluginModuleBase(const IKernelContext& ctx) + : TKernelObject<IPluginModule>(ctx), m_onInitializeCB(nullptr), m_onGetPluginObjectDescCB(nullptr), m_onUninitializeCB(nullptr) {} - ~CPluginModuleBase() override { } - bool initialize() override; - bool getPluginObjectDescription(size_t index, IPluginObjectDesc*& pluginObjectDesc) override; - bool uninitialize() override; - bool getFileName(CString& fileName) const override; + ~CPluginModuleBase() override { } + bool initialize() override; + bool getPluginObjectDescription(size_t index, IPluginObjectDesc*& pluginObjectDesc) override; + bool uninitialize() override; + bool getFileName(CString& fileName) const override; - _IsDerivedFromClass_Final_(TKernelObject<IPluginModule>, OV_UndefinedIdentifier) + _IsDerivedFromClass_Final_(TKernelObject<IPluginModule>, OV_UndefinedIdentifier) - protected: +protected: - virtual bool isOpen() const = 0; + virtual bool isOpen() const = 0; - vector<IPluginObjectDesc*> m_pluginObjectDescs; - CString m_filename; - bool m_gotDesc = false; + vector<IPluginObjectDesc*> m_pluginObjectDescs; + CString m_filename; + bool m_gotDesc = false; - bool (*m_onInitializeCB)(const IPluginModuleContext&); - bool (*m_onGetPluginObjectDescCB)(const IPluginModuleContext&, size_t, IPluginObjectDesc*&); - bool (*m_onUninitializeCB)(const IPluginModuleContext&); - }; - } // namespace Kernel -} // namespace OpenViBE + bool (*m_onInitializeCB)(const IPluginModuleContext&); + bool (*m_onGetPluginObjectDescCB)(const IPluginModuleContext&, size_t, IPluginObjectDesc*&); + bool (*m_onUninitializeCB)(const IPluginModuleContext&); +}; +} // namespace Kernel +} // namespace OpenViBE -namespace OpenViBE +namespace OpenViBE { +namespace Kernel { +namespace { +class CPluginModuleContext final : public TKernelObject<IPluginModuleContext> { - namespace Kernel - { - namespace - { - class CPluginModuleContext final : public TKernelObject<IPluginModuleContext> - { - public: +public: - explicit CPluginModuleContext(const IKernelContext& ctx) - : TKernelObject<IPluginModuleContext>(ctx), m_logManager(ctx.getLogManager()), m_typeManager(ctx.getTypeManager()), - m_scenarioManager(ctx.getScenarioManager()) { } + explicit CPluginModuleContext(const IKernelContext& ctx) + : TKernelObject<IPluginModuleContext>(ctx), m_logManager(ctx.getLogManager()), m_typeManager(ctx.getTypeManager()), + m_scenarioManager(ctx.getScenarioManager()) { } - ILogManager& getLogManager() const override { return m_logManager; } - ITypeManager& getTypeManager() const override { return m_typeManager; } - IScenarioManager& getScenarioManager() const override { return m_scenarioManager; } + ILogManager& getLogManager() const override { return m_logManager; } + ITypeManager& getTypeManager() const override { return m_typeManager; } + IScenarioManager& getScenarioManager() const override { return m_scenarioManager; } - _IsDerivedFromClass_Final_(TKernelObject<IPluginModuleContext>, OVK_ClassId_Kernel_Plugins_PluginModuleContext) + _IsDerivedFromClass_Final_(TKernelObject<IPluginModuleContext>, OVK_ClassId_Kernel_Plugins_PluginModuleContext) - protected: +protected: - ILogManager& m_logManager; - ITypeManager& m_typeManager; - IScenarioManager& m_scenarioManager; - }; - } // namespace - } // namespace Kernel -} // namespace OpenViBE + ILogManager& m_logManager; + ITypeManager& m_typeManager; + IScenarioManager& m_scenarioManager; +}; +} // namespace +} // namespace Kernel +} // namespace OpenViBE //___________________________________________________________________// // // @@ -132,79 +127,63 @@ bool CPluginModuleBase::getFileName(CString& fileName) const //___________________________________________________________________// // // -#if defined TARGET_OS_Linux || defined TARGET_OS_MacOS +namespace OpenViBE { +namespace Kernel { -namespace OpenViBE +#if defined TARGET_OS_Linux || defined TARGET_OS_MacOS +class CPluginModuleLinux : public CPluginModuleBase { - namespace Kernel - { - class CPluginModuleLinux : public CPluginModuleBase - { - public: +public: - CPluginModuleLinux(const IKernelContext& ctx); + CPluginModuleLinux(const IKernelContext& ctx); - virtual bool load(const CString& filename, CString* pError); - virtual bool unload(CString* pError); - virtual bool isOpen() const; + virtual bool load(const CString& filename, CString* pError); + virtual bool unload(CString* pError); + virtual bool isOpen() const; - protected: +protected: - void* m_fileHandle; - }; - } -} // namespace OpenViBE + void* m_fileHandle; +}; #elif defined TARGET_OS_Windows - -namespace OpenViBE +class CPluginModuleWindows final : public CPluginModuleBase { - namespace Kernel - { - class CPluginModuleWindows final : public CPluginModuleBase - { - public: +public: - explicit CPluginModuleWindows(const IKernelContext& ctx); - bool load(const CString& filename, CString* pError) override; - bool unload(CString* pError) override; + explicit CPluginModuleWindows(const IKernelContext& ctx); + bool load(const CString& filename, CString* pError) override; + bool unload(CString* pError) override; - protected: - bool isOpen() const override { return m_fileHandle != nullptr; } +protected: + bool isOpen() const override { return m_fileHandle != nullptr; } - HMODULE m_fileHandle; + HMODULE m_fileHandle; - private: +private: - static CString getLastErrorMessageString(); - }; - } // namespace Kernel -} // namespace OpenViBE + static CString getLastErrorMessageString(); +}; #else - -namespace OpenViBE +class CPluginModuleDummy : public CPluginModuleBase { - namespace Kernel - { - class CPluginModuleDummy : public CPluginModuleBase - { - public: +public: - explicit CPluginModuleDummy(const IKernelContext& ctx); + explicit CPluginModuleDummy(const IKernelContext& ctx); - virtual bool load(const CString& filename, CString* pError); - virtual bool unload(CString* pError); + virtual bool load(const CString& filename, CString* pError); + virtual bool unload(CString* pError); - protected: - - virtual bool isOpen() const; - }; - } -} // namespace OpenViBE +protected: + virtual bool isOpen() const; +}; #endif +} // namespace Kernel +} // namespace OpenViBE +// //___________________________________________________________________// // // @@ -364,9 +343,7 @@ CPluginModule::CPluginModule(const IKernelContext& ctx) CPluginModule::~CPluginModule() { delete m_impl; } bool CPluginModule::load(const CString& filename, CString* error) { return !m_impl ? false : m_impl->load(filename, error); } - bool CPluginModule::unload(CString* error) { return !m_impl ? false : m_impl->unload(error); } - bool CPluginModule::initialize() { return !m_impl ? false : m_impl->initialize(); } bool CPluginModule::getPluginObjectDescription(const size_t index, IPluginObjectDesc*& desc) @@ -375,5 +352,4 @@ bool CPluginModule::getPluginObjectDescription(const size_t index, IPluginObject } bool CPluginModule::uninitialize() { return !m_impl ? false : m_impl->uninitialize(); } - bool CPluginModule::getFileName(CString& rFileName) const { return !m_impl ? false : m_impl->getFileName(rFileName); } diff --git a/kernel/src/kernel/plugins/ovkCPluginModule.h b/kernel/src/kernel/plugins/ovkCPluginModule.h index 7830273b0012cbcf343ec654d14fed02b65cd2b8..b52423f4ec8d229f1d295f248c66a47577e370c6 100644 --- a/kernel/src/kernel/plugins/ovkCPluginModule.h +++ b/kernel/src/kernel/plugins/ovkCPluginModule.h @@ -4,28 +4,26 @@ #include <openvibe/ov_all.h> -namespace OpenViBE +namespace OpenViBE { +namespace Kernel { +class CPluginModule final : public TKernelObject<IPluginModule> { - namespace Kernel - { - class CPluginModule final : public TKernelObject<IPluginModule> - { - public: +public: - explicit CPluginModule(const IKernelContext& ctx); - ~CPluginModule() override; - bool load(const CString& filename, CString* error) override; - bool unload(CString* error) override; - bool getFileName(CString& rFileName) const override; - bool initialize() override; - bool getPluginObjectDescription(size_t index, Plugins::IPluginObjectDesc*& desc) override; - bool uninitialize() override; + explicit CPluginModule(const IKernelContext& ctx); + ~CPluginModule() override; + bool load(const CString& filename, CString* error) override; + bool unload(CString* error) override; + bool getFileName(CString& rFileName) const override; + bool initialize() override; + bool getPluginObjectDescription(size_t index, Plugins::IPluginObjectDesc*& desc) override; + bool uninitialize() override; - _IsDerivedFromClass_Final_(TKernelObject<IPluginModule>, OVK_ClassId_Kernel_Plugins_PluginModule) + _IsDerivedFromClass_Final_(TKernelObject<IPluginModule>, OVK_ClassId_Kernel_Plugins_PluginModule) - protected: +protected: - IPluginModule* m_impl = nullptr; - }; - } // namespace Kernel -} // namespace OpenViBE + IPluginModule* m_impl = nullptr; +}; +} // namespace Kernel +} // namespace OpenViBE diff --git a/kernel/src/kernel/scenario/ovkCBoxListenerContext.h b/kernel/src/kernel/scenario/ovkCBoxListenerContext.h index 2154ba220feb79fccd98c6d5ecfd89e1b6bd3c66..730d12eea5400e674323a048637f8edfc7b471a6 100755 --- a/kernel/src/kernel/scenario/ovkCBoxListenerContext.h +++ b/kernel/src/kernel/scenario/ovkCBoxListenerContext.h @@ -2,42 +2,39 @@ #include "../ovkTKernelObject.h" -namespace OpenViBE +namespace OpenViBE { +namespace Kernel { +class CBoxListenerContext final : public TKernelObject<IBoxListenerContext> { - namespace Kernel +public: + + CBoxListenerContext(const IKernelContext& ctx, IBox& box, const size_t index) + : TKernelObject<IBoxListenerContext>(ctx), m_box(box), m_idx(index) { } + + IAlgorithmManager& getAlgorithmManager() const override { return this->getKernelContext().getAlgorithmManager(); } + IPlayerManager& getPlayerManager() const override { return this->getKernelContext().getPlayerManager(); } + IPluginManager& getPluginManager() const override { return this->getKernelContext().getPluginManager(); } + IMetaboxManager& getMetaboxManager() const override { return this->getKernelContext().getMetaboxManager(); } + IScenarioManager& getScenarioManager() const override { return this->getKernelContext().getScenarioManager(); } + ITypeManager& getTypeManager() const override { return this->getKernelContext().getTypeManager(); } + ILogManager& getLogManager() const override { return this->getKernelContext().getLogManager(); } + IErrorManager& getErrorManager() const override { return this->getKernelContext().getErrorManager(); } + IConfigurationManager& getConfigurationManager() const override { return this->getKernelContext().getConfigurationManager(); } + IBox& getBox() const override { return m_box; } + + IScenario& getScenario() const override { - class CBoxListenerContext final : public TKernelObject<IBoxListenerContext> - { - public: - - CBoxListenerContext(const IKernelContext& ctx, IBox& box, const size_t index) - : TKernelObject<IBoxListenerContext>(ctx), m_box(box), m_idx(index) { } - - IAlgorithmManager& getAlgorithmManager() const override { return this->getKernelContext().getAlgorithmManager(); } - IPlayerManager& getPlayerManager() const override { return this->getKernelContext().getPlayerManager(); } - IPluginManager& getPluginManager() const override { return this->getKernelContext().getPluginManager(); } - IMetaboxManager& getMetaboxManager() const override { return this->getKernelContext().getMetaboxManager(); } - IScenarioManager& getScenarioManager() const override { return this->getKernelContext().getScenarioManager(); } - ITypeManager& getTypeManager() const override { return this->getKernelContext().getTypeManager(); } - ILogManager& getLogManager() const override { return this->getKernelContext().getLogManager(); } - IErrorManager& getErrorManager() const override { return this->getKernelContext().getErrorManager(); } - IConfigurationManager& getConfigurationManager() const override { return this->getKernelContext().getConfigurationManager(); } - IBox& getBox() const override { return m_box; } - - IScenario& getScenario() const override - { - OV_FATAL("Getting scenario from box listener context is not yet implemented", ErrorType::NotImplemented, - this->getKernelContext().getLogManager()); - } - - size_t getIndex() const override { return m_idx; } - - _IsDerivedFromClass_Final_(TKernelObject<IBoxListenerContext>, OVK_ClassId_Kernel_Scenario_BoxListenerContext) - - private: - - IBox& m_box; - size_t m_idx = 0; - }; - } // namespace Kernel -} // namespace OpenViBE + OV_FATAL("Getting scenario from box listener context is not yet implemented", ErrorType::NotImplemented, this->getKernelContext().getLogManager()); + } + + size_t getIndex() const override { return m_idx; } + + _IsDerivedFromClass_Final_(TKernelObject<IBoxListenerContext>, OVK_ClassId_Kernel_Scenario_BoxListenerContext) + +private: + + IBox& m_box; + size_t m_idx = 0; +}; +} // namespace Kernel +} // namespace OpenViBE diff --git a/kernel/src/kernel/scenario/ovkCBoxProto.h b/kernel/src/kernel/scenario/ovkCBoxProto.h index e7183335446630ad8203abcf0139e93534c56908..8db7ab1359e0bcf79e89170f1dc838ea73f524e0 100755 --- a/kernel/src/kernel/scenario/ovkCBoxProto.h +++ b/kernel/src/kernel/scenario/ovkCBoxProto.h @@ -2,37 +2,34 @@ #include "../ovkTKernelObject.h" -namespace OpenViBE +namespace OpenViBE { +namespace Kernel { +class CBoxProto : public TKernelObject<IBoxProto> { - namespace Kernel - { - class CBoxProto : public TKernelObject<IBoxProto> - { - public: - - CBoxProto(const IKernelContext& ctx, IBox& box) : TKernelObject<IBoxProto>(ctx), m_box(box) {} - ~CBoxProto() override = default; - bool addInput(const CString& name, const CIdentifier& typeID, const CIdentifier& id = OV_UndefinedIdentifier, const bool notify = true) override; - bool addOutput(const CString& name, const CIdentifier& typeID, const CIdentifier& id = OV_UndefinedIdentifier, const bool notify = true) override; - - //virtual bool addSetting(const CString& name, const CIdentifier& typeID, const CString& value); - bool addSetting(const CString& name, const CIdentifier& typeID, const CString& value, const bool modifiable = false, - const CIdentifier& id = OV_UndefinedIdentifier, - const bool notify = true) override; - bool addFlag(const EBoxFlag boxFlag) override; - bool addFlag(const CIdentifier& flagID) override; - bool addInputSupport(const CIdentifier& typeID) override { return m_box.addInputSupport(typeID); } - bool addOutputSupport(const CIdentifier& typeID) override { return m_box.addOutputSupport(typeID); } - - _IsDerivedFromClass_Final_(TKernelObject<IBoxProto>, OVK_ClassId_Kernel_Scenario_BoxProto) - - protected: - - IBox& m_box; - - private: - - CBoxProto() = delete; - }; - } // namespace Kernel -} // namespace OpenViBE +public: + + CBoxProto(const IKernelContext& ctx, IBox& box) : TKernelObject<IBoxProto>(ctx), m_box(box) {} + ~CBoxProto() override = default; + bool addInput(const CString& name, const CIdentifier& typeID, const CIdentifier& id = OV_UndefinedIdentifier, const bool notify = true) override; + bool addOutput(const CString& name, const CIdentifier& typeID, const CIdentifier& id = OV_UndefinedIdentifier, const bool notify = true) override; + + //virtual bool addSetting(const CString& name, const CIdentifier& typeID, const CString& value); + bool addSetting(const CString& name, const CIdentifier& typeID, const CString& value, + const bool modifiable = false, const CIdentifier& id = OV_UndefinedIdentifier, const bool notify = true) override; + bool addFlag(const EBoxFlag boxFlag) override; + bool addFlag(const CIdentifier& flagID) override; + bool addInputSupport(const CIdentifier& typeID) override { return m_box.addInputSupport(typeID); } + bool addOutputSupport(const CIdentifier& typeID) override { return m_box.addOutputSupport(typeID); } + + _IsDerivedFromClass_Final_(TKernelObject<IBoxProto>, OVK_ClassId_Kernel_Scenario_BoxProto) + +protected: + + IBox& m_box; + +private: + + CBoxProto() = delete; +}; +} // namespace Kernel +} // namespace OpenViBE diff --git a/kernel/src/kernel/scenario/ovkCBoxUpdater.h b/kernel/src/kernel/scenario/ovkCBoxUpdater.h index 0fe067f15917b79c600a233461cc73f1b310db37..bd0076334aa544c3bc90a9e362995cfae5c5592e 100644 --- a/kernel/src/kernel/scenario/ovkCBoxUpdater.h +++ b/kernel/src/kernel/scenario/ovkCBoxUpdater.h @@ -7,90 +7,87 @@ #include <map> #include <array> -namespace OpenViBE +namespace OpenViBE { +namespace Kernel { +typedef struct _InterfacorRequest { - namespace Kernel + size_t index = size_t(-1); + CIdentifier identifier = OV_UndefinedIdentifier; + CIdentifier typeID = OV_UndefinedIdentifier; + CString name; + bool toBeRemoved; + + // only for settings + CString defaultValue; + bool modifiability = false; + CString value; +} InterfacorRequest; + +class CBoxUpdater final : public TKernelObject<IKernelObject> +{ +public: + + CBoxUpdater(CScenario& scenario, IBox* box); + ~CBoxUpdater() override; + + bool initialize(); + + const std::map<size_t, size_t>& getOriginalToUpdatedInterfacorCorrespondence(const EBoxInterfacorType type) const + { + return m_originalToUpdatedCorrespondence.at(type); + } + + IBox& getUpdatedBox() const { return *m_updatedBox; } + + bool flaggedForManualUpdate() const { - typedef struct _InterfacorRequest - { - size_t index = size_t(-1); - CIdentifier identifier = OV_UndefinedIdentifier; - CIdentifier typeID = OV_UndefinedIdentifier; - CString name; - bool toBeRemoved; - - // only for settings - CString defaultValue; - bool modifiability = false; - CString value; - } InterfacorRequest; - - class CBoxUpdater final : public TKernelObject<IKernelObject> - { - public: - - CBoxUpdater(CScenario& scenario, IBox* box); - ~CBoxUpdater() override; - - bool initialize(); - - const std::map<size_t, size_t>& getOriginalToUpdatedInterfacorCorrespondence(const EBoxInterfacorType type) const - { - return m_originalToUpdatedCorrespondence.at(type); - } - - IBox& getUpdatedBox() const { return *m_updatedBox; } - - bool flaggedForManualUpdate() const - { - OV_FATAL_UNLESS_K(m_initialized, "Box Updater is not initialized", ErrorType::BadCall); - - return m_kernelBox->hasAttribute(OV_AttributeId_Box_FlagNeedsManualUpdate) - || m_kernelBox->hasAttribute(OV_AttributeId_Box_FlagCanAddInput) - || m_kernelBox->hasAttribute(OV_AttributeId_Box_FlagCanModifyInput) - || m_kernelBox->hasAttribute(OV_AttributeId_Box_FlagCanAddOutput) - || m_kernelBox->hasAttribute(OV_AttributeId_Box_FlagCanModifyOutput) - || m_kernelBox->hasAttribute(OV_AttributeId_Box_FlagCanAddSetting) - || m_kernelBox->hasAttribute(OV_AttributeId_Box_FlagCanModifySetting); - } - - bool isUpdateRequired() const { return m_isUpdateRequired; } - - static const std::array<CIdentifier, 10> UPDATABLE_ATTRIBUTES; - - _IsDerivedFromClass_Final_(TKernelObject<IKernelObject>, OV_ClassId_Kernel_Scenario_BoxUpdater) - - private: - - static size_t getInterfacorIndex(EBoxInterfacorType type, const IBox& box, const CIdentifier& typeID, const CIdentifier& id, - const CString& name); - bool updateInterfacors(EBoxInterfacorType interfacorType); - - /** - * \brief Check if supported type have to be updated between the box to be updated and the kernel - * \return true when at least input or output supported types have to be updated - */ - bool checkForSupportedTypesToBeUpdated() const; - - /** - * \brief Check if supported inputs, outputs or settings attributes have to be updated between the box to be updated and the kernel - * \return true when at least input, output or settings attributes have to be updated - */ - bool checkForSupportedIOSAttributesToBeUpdated() const; - - // pointer to the parent scenario - CScenario* m_scenario = nullptr; - // pointer to the original box to be updated - IBox* m_sourceBox = nullptr; - // pointer to the kernel box - const IBox* m_kernelBox = nullptr; - // pointer to the updated box. This box will be used to update the prototype of the original box - IBox* m_updatedBox = nullptr; - // true when updater has been initialized - bool m_initialized = false; - - std::map<EBoxInterfacorType, std::map<size_t, size_t>> m_originalToUpdatedCorrespondence; - bool m_isUpdateRequired = false; - }; - } // namespace Kernel -} // namespace OpenViBE + OV_FATAL_UNLESS_K(m_initialized, "Box Updater is not initialized", ErrorType::BadCall); + + return m_kernelBox->hasAttribute(OV_AttributeId_Box_FlagNeedsManualUpdate) + || m_kernelBox->hasAttribute(OV_AttributeId_Box_FlagCanAddInput) + || m_kernelBox->hasAttribute(OV_AttributeId_Box_FlagCanModifyInput) + || m_kernelBox->hasAttribute(OV_AttributeId_Box_FlagCanAddOutput) + || m_kernelBox->hasAttribute(OV_AttributeId_Box_FlagCanModifyOutput) + || m_kernelBox->hasAttribute(OV_AttributeId_Box_FlagCanAddSetting) + || m_kernelBox->hasAttribute(OV_AttributeId_Box_FlagCanModifySetting); + } + + bool isUpdateRequired() const { return m_isUpdateRequired; } + + static const std::array<CIdentifier, 10> UPDATABLE_ATTRIBUTES; + + _IsDerivedFromClass_Final_(TKernelObject<IKernelObject>, OV_ClassId_Kernel_Scenario_BoxUpdater) + +private: + + static size_t getInterfacorIndex(EBoxInterfacorType type, const IBox& box, const CIdentifier& typeID, const CIdentifier& id, const CString& name); + bool updateInterfacors(EBoxInterfacorType interfacorType); + + /** + * \brief Check if supported type have to be updated between the box to be updated and the kernel + * \return true when at least input or output supported types have to be updated + */ + bool checkForSupportedTypesToBeUpdated() const; + + /** + * \brief Check if supported inputs, outputs or settings attributes have to be updated between the box to be updated and the kernel + * \return true when at least input, output or settings attributes have to be updated + */ + bool checkForSupportedIOSAttributesToBeUpdated() const; + + // pointer to the parent scenario + CScenario* m_scenario = nullptr; + // pointer to the original box to be updated + IBox* m_sourceBox = nullptr; + // pointer to the kernel box + const IBox* m_kernelBox = nullptr; + // pointer to the updated box. This box will be used to update the prototype of the original box + IBox* m_updatedBox = nullptr; + // true when updater has been initialized + bool m_initialized = false; + + std::map<EBoxInterfacorType, std::map<size_t, size_t>> m_originalToUpdatedCorrespondence; + bool m_isUpdateRequired = false; +}; +} // namespace Kernel +} // namespace OpenViBE diff --git a/kernel/src/kernel/scenario/ovkCComment.h b/kernel/src/kernel/scenario/ovkCComment.h index 30c920ce77212a2ad04d47656550b798398a1699..a03d88081bf118f2de2fd8bf92471bc8212b47dc 100644 --- a/kernel/src/kernel/scenario/ovkCComment.h +++ b/kernel/src/kernel/scenario/ovkCComment.h @@ -6,33 +6,31 @@ #include <iostream> -namespace OpenViBE +namespace OpenViBE { +namespace Kernel { +class CScenario; + +class CComment final : public TAttributable<TKernelObject<IComment>> { - namespace Kernel - { - class CScenario; - - class CComment final : public TAttributable<TKernelObject<IComment>> - { - public: - - CComment(const IKernelContext& ctx, CScenario& rOwnerScenario); - ~CComment() override; - CIdentifier getIdentifier() const override; - CString getText() const override; - bool setIdentifier(const CIdentifier& id) override; - bool setText(const CString& sText) override; - bool initializeFromExistingComment(const IComment& rExisitingComment) override; - bool acceptVisitor(IObjectVisitor& rObjectVisitor) override; - - _IsDerivedFromClass_Final_(TAttributable<TKernelObject<IComment>>, OVK_ClassId_Kernel_Scenario_Comment) - - protected: - - CScenario& m_rOwnerScenario; - - CIdentifier m_id = OV_UndefinedIdentifier; - CString m_text; - }; - } // namespace Kernel -} // namespace OpenViBE +public: + + CComment(const IKernelContext& ctx, CScenario& rOwnerScenario); + ~CComment() override; + CIdentifier getIdentifier() const override; + CString getText() const override; + bool setIdentifier(const CIdentifier& id) override; + bool setText(const CString& sText) override; + bool initializeFromExistingComment(const IComment& rExisitingComment) override; + bool acceptVisitor(IObjectVisitor& rObjectVisitor) override; + + _IsDerivedFromClass_Final_(TAttributable<TKernelObject<IComment>>, OVK_ClassId_Kernel_Scenario_Comment) + +protected: + + CScenario& m_rOwnerScenario; + + CIdentifier m_id = OV_UndefinedIdentifier; + CString m_text; +}; +} // namespace Kernel +} // namespace OpenViBE diff --git a/kernel/src/kernel/scenario/ovkCLink.cpp b/kernel/src/kernel/scenario/ovkCLink.cpp index e7a413e4d76962ad00cfc5dea28ccefb0d0bd568..594816ffa601ce4a0c0d17dd139ba21049617e5d 100644 --- a/kernel/src/kernel/scenario/ovkCLink.cpp +++ b/kernel/src/kernel/scenario/ovkCLink.cpp @@ -65,9 +65,7 @@ bool CLink::getSource(CIdentifier& boxId, size_t& boxOutputIdx, CIdentifier& box } CIdentifier CLink::getSourceBoxIdentifier() const { return m_srcBoxID; } - size_t CLink::getSourceBoxOutputIndex() const { return m_srcOutputIdx; } - CIdentifier CLink::getSourceBoxOutputIdentifier() const { return m_srcBoxOutputID; } bool CLink::getTarget(CIdentifier& dstBoxID, size_t& boxInputIndex, CIdentifier& dstBoxInputID) const @@ -79,9 +77,7 @@ bool CLink::getTarget(CIdentifier& dstBoxID, size_t& boxInputIndex, CIdentifier& } CIdentifier CLink::getTargetBoxIdentifier() const { return m_dstBoxID; } - size_t CLink::getTargetBoxInputIndex() const { return m_dstInputIdx; } - CIdentifier CLink::getTargetBoxInputIdentifier() const { return m_dstBoxInputID; } //___________________________________________________________________// diff --git a/kernel/src/kernel/scenario/ovkCLink.h b/kernel/src/kernel/scenario/ovkCLink.h index ae5183ef8e470200efd88872cc0da92272ba6912..3074b117522e49922fa4307e8bedf5f15a35ec28 100644 --- a/kernel/src/kernel/scenario/ovkCLink.h +++ b/kernel/src/kernel/scenario/ovkCLink.h @@ -4,44 +4,42 @@ #include "ovkTAttributable.h" -namespace OpenViBE +namespace OpenViBE { +namespace Kernel { +class CScenario; + +class CLink final : public TAttributable<TKernelObject<ILink>> { - namespace Kernel - { - class CScenario; - - class CLink final : public TAttributable<TKernelObject<ILink>> - { - public: - - CLink(const IKernelContext& ctx, CScenario& ownerScenario); - bool initializeFromExistingLink(const ILink& link) override; - bool setIdentifier(const CIdentifier& identifier) override; - CIdentifier getIdentifier() const override; - bool setSource(const CIdentifier& boxId, size_t boxOutputIdx, CIdentifier boxOutputID) override; - bool setTarget(const CIdentifier& boxId, size_t boxInputIdx, CIdentifier boxInputID) override; - bool getSource(CIdentifier& boxId, size_t& boxOutputIdx, CIdentifier& boxOutputID) const override; - CIdentifier getSourceBoxIdentifier() const override; - size_t getSourceBoxOutputIndex() const override; - CIdentifier getSourceBoxOutputIdentifier() const override; - bool getTarget(CIdentifier& dstBoxID, size_t& boxInputIndex, CIdentifier& dstBoxInputID) const override; - CIdentifier getTargetBoxIdentifier() const override; - size_t getTargetBoxInputIndex() const override; - CIdentifier getTargetBoxInputIdentifier() const override; - bool acceptVisitor(IObjectVisitor& visitor) override; - - _IsDerivedFromClass_Final_(TAttributable<TKernelObject<ILink>>, OVK_ClassId_Kernel_Scenario_Link) - - protected: - - CScenario& m_ownerScenario; - CIdentifier m_id = OV_UndefinedIdentifier; - CIdentifier m_srcBoxID = OV_UndefinedIdentifier; - CIdentifier m_dstBoxID = OV_UndefinedIdentifier; - size_t m_srcOutputIdx = 0; - CIdentifier m_srcBoxOutputID = OV_UndefinedIdentifier; - size_t m_dstInputIdx = 0; - CIdentifier m_dstBoxInputID = OV_UndefinedIdentifier; - }; - } // namespace Kernel -} // namespace OpenViBE +public: + + CLink(const IKernelContext& ctx, CScenario& ownerScenario); + bool initializeFromExistingLink(const ILink& link) override; + bool setIdentifier(const CIdentifier& identifier) override; + CIdentifier getIdentifier() const override; + bool setSource(const CIdentifier& boxId, size_t boxOutputIdx, CIdentifier boxOutputID) override; + bool setTarget(const CIdentifier& boxId, size_t boxInputIdx, CIdentifier boxInputID) override; + bool getSource(CIdentifier& boxId, size_t& boxOutputIdx, CIdentifier& boxOutputID) const override; + CIdentifier getSourceBoxIdentifier() const override; + size_t getSourceBoxOutputIndex() const override; + CIdentifier getSourceBoxOutputIdentifier() const override; + bool getTarget(CIdentifier& dstBoxID, size_t& boxInputIndex, CIdentifier& dstBoxInputID) const override; + CIdentifier getTargetBoxIdentifier() const override; + size_t getTargetBoxInputIndex() const override; + CIdentifier getTargetBoxInputIdentifier() const override; + bool acceptVisitor(IObjectVisitor& visitor) override; + + _IsDerivedFromClass_Final_(TAttributable<TKernelObject<ILink>>, OVK_ClassId_Kernel_Scenario_Link) + +protected: + + CScenario& m_ownerScenario; + CIdentifier m_id = OV_UndefinedIdentifier; + CIdentifier m_srcBoxID = OV_UndefinedIdentifier; + CIdentifier m_dstBoxID = OV_UndefinedIdentifier; + size_t m_srcOutputIdx = 0; + CIdentifier m_srcBoxOutputID = OV_UndefinedIdentifier; + size_t m_dstInputIdx = 0; + CIdentifier m_dstBoxInputID = OV_UndefinedIdentifier; +}; +} // namespace Kernel +} // namespace OpenViBE diff --git a/kernel/src/kernel/scenario/ovkCMetadata.cpp b/kernel/src/kernel/scenario/ovkCMetadata.cpp index 87e1fa630b4aa2ae339851d57d82009ca56f6375..b9d3256d3ed5596ef29404b967c8e5066348f304 100644 --- a/kernel/src/kernel/scenario/ovkCMetadata.cpp +++ b/kernel/src/kernel/scenario/ovkCMetadata.cpp @@ -20,9 +20,7 @@ CMetadata::CMetadata(const IKernelContext& ctx, CScenario& ownerScenario) CMetadata::~CMetadata() {} CIdentifier CMetadata::getIdentifier() const { return m_id; } - CIdentifier CMetadata::getType() const { return m_type; } - CString CMetadata::getData() const { return m_data; } bool CMetadata::setIdentifier(const CIdentifier& identifier) diff --git a/kernel/src/kernel/scenario/ovkCMetadata.h b/kernel/src/kernel/scenario/ovkCMetadata.h index a0fce8b8c0ba2e23d191039d6df4a49b3968b2da..ec2217e1cc9eab5583988da45abc95cb81b423e0 100644 --- a/kernel/src/kernel/scenario/ovkCMetadata.h +++ b/kernel/src/kernel/scenario/ovkCMetadata.h @@ -3,39 +3,37 @@ #include <openvibe/kernel/scenario/ovIMetadata.h> #include "../ovkTKernelObject.h" -namespace OpenViBE -{ - namespace Kernel - { - class CScenario; +namespace OpenViBE { +namespace Kernel { +class CScenario; - class CMetadata final : public TKernelObject<IMetadata> - { - public: +class CMetadata final : public TKernelObject<IMetadata> +{ +public: - CMetadata(const IKernelContext& ctx, CScenario& ownerScenario); - ~CMetadata() override; + CMetadata(const IKernelContext& ctx, CScenario& ownerScenario); + ~CMetadata() override; - CIdentifier getIdentifier() const override; - CIdentifier getType() const override; - CString getData() const override; - bool setIdentifier(const CIdentifier& identifier) override; - bool setType(const CIdentifier& typeID) override; - bool setData(const CString& data) override; + CIdentifier getIdentifier() const override; + CIdentifier getType() const override; + CString getData() const override; + bool setIdentifier(const CIdentifier& identifier) override; + bool setType(const CIdentifier& typeID) override; + bool setData(const CString& data) override; - bool initializeFromExistingMetadata(const IMetadata& existingMetadata) override; + bool initializeFromExistingMetadata(const IMetadata& existingMetadata) override; - bool acceptVisitor(IObjectVisitor& objectVisitor) override; + bool acceptVisitor(IObjectVisitor& objectVisitor) override; - _IsDerivedFromClass_Final_(TKernelObject<IMetadata>, OVK_ClassId_Kernel_Scenario_Metadata) + _IsDerivedFromClass_Final_(TKernelObject<IMetadata>, OVK_ClassId_Kernel_Scenario_Metadata) - private: +private: - CScenario& m_ownerScenario; + CScenario& m_ownerScenario; - CIdentifier m_id = OV_UndefinedIdentifier; - CIdentifier m_type = OV_UndefinedIdentifier; - CString m_data; - }; - } // namespace Kernel -} // namespace OpenViBE + CIdentifier m_id = OV_UndefinedIdentifier; + CIdentifier m_type = OV_UndefinedIdentifier; + CString m_data; +}; +} // namespace Kernel +} // namespace OpenViBE diff --git a/kernel/src/kernel/scenario/ovkCScenario.cpp b/kernel/src/kernel/scenario/ovkCScenario.cpp index feab94e29eef96e879c403bf59fda91107763d9d..48510ea6ff35d930956cff6f71dd1e0d34a6cd83 100755 --- a/kernel/src/kernel/scenario/ovkCScenario.cpp +++ b/kernel/src/kernel/scenario/ovkCScenario.cpp @@ -27,103 +27,102 @@ using namespace /*OpenViBE::*/Plugins; //___________________________________________________________________// // // -namespace +namespace { +template <class T> +struct STestTrue { - template <class T> - struct STestTrue - { - bool operator()(typename map<CIdentifier, T>::const_iterator /*it*/) const { return true; } - }; - - struct STestEqSourceBox - { - explicit STestEqSourceBox(const CIdentifier& boxId) : m_BoxId(boxId) { } - bool operator()(const map<CIdentifier, CLink*>::const_iterator& it) const { return it->second->getSourceBoxIdentifier() == m_BoxId; } - const CIdentifier& m_BoxId; - }; + bool operator()(typename map<CIdentifier, T>::const_iterator /*it*/) const { return true; } +}; - struct STestEqSourceBoxOutput - { - STestEqSourceBoxOutput(const CIdentifier& boxId, const size_t index) : m_BoxId(boxId), m_OutputIdx(index) { } - - bool operator()(const map<CIdentifier, CLink*>::const_iterator& it) const - { - return it->second->getSourceBoxIdentifier() == m_BoxId && it->second->getSourceBoxOutputIndex() == m_OutputIdx; - } +struct STestEqSourceBox +{ + explicit STestEqSourceBox(const CIdentifier& boxId) : m_BoxId(boxId) { } + bool operator()(const map<CIdentifier, CLink*>::const_iterator& it) const { return it->second->getSourceBoxIdentifier() == m_BoxId; } + const CIdentifier& m_BoxId; +}; - const CIdentifier& m_BoxId; - size_t m_OutputIdx; - }; +struct STestEqSourceBoxOutput +{ + STestEqSourceBoxOutput(const CIdentifier& boxId, const size_t index) : m_BoxId(boxId), m_OutputIdx(index) { } - struct STestEqTargetBox + bool operator()(const map<CIdentifier, CLink*>::const_iterator& it) const { - explicit STestEqTargetBox(const CIdentifier& boxId) : m_BoxId(boxId) { } - bool operator()(const map<CIdentifier, CLink*>::const_iterator& it) const { return it->second->getTargetBoxIdentifier() == m_BoxId; } - const CIdentifier& m_BoxId; - }; + return it->second->getSourceBoxIdentifier() == m_BoxId && it->second->getSourceBoxOutputIndex() == m_OutputIdx; + } - struct STestEqTargetBoxInput - { - STestEqTargetBoxInput(const CIdentifier& boxId, const size_t index) : m_BoxId(boxId), m_InputIdx(index) { } + const CIdentifier& m_BoxId; + size_t m_OutputIdx; +}; - bool operator()(const map<CIdentifier, CLink*>::const_iterator& it) const - { - return it->second->getTargetBoxIdentifier() == m_BoxId && it->second->getTargetBoxInputIndex() == m_InputIdx; - } +struct STestEqTargetBox +{ + explicit STestEqTargetBox(const CIdentifier& boxId) : m_BoxId(boxId) { } + bool operator()(const map<CIdentifier, CLink*>::const_iterator& it) const { return it->second->getTargetBoxIdentifier() == m_BoxId; } + const CIdentifier& m_BoxId; +}; - const CIdentifier& m_BoxId; - size_t m_InputIdx; - }; +struct STestEqTargetBoxInput +{ + STestEqTargetBoxInput(const CIdentifier& boxId, const size_t index) : m_BoxId(boxId), m_InputIdx(index) { } - template <class T, class TTest> - CIdentifier getNextID(const map<CIdentifier, T>& elementMap, const CIdentifier& previousID, const TTest& testFunctor) + bool operator()(const map<CIdentifier, CLink*>::const_iterator& it) const { - typename map<CIdentifier, T>::const_iterator it; + return it->second->getTargetBoxIdentifier() == m_BoxId && it->second->getTargetBoxInputIndex() == m_InputIdx; + } - if (previousID == OV_UndefinedIdentifier) { it = elementMap.begin(); } - else - { - it = elementMap.find(previousID); - if (it == elementMap.end()) { return OV_UndefinedIdentifier; } - ++it; - } + const CIdentifier& m_BoxId; + size_t m_InputIdx; +}; - while (it != elementMap.end()) - { - if (testFunctor(it)) { return it->first; } - ++it; - } +template <class T, class TTest> +CIdentifier getNextID(const map<CIdentifier, T>& elementMap, const CIdentifier& previousID, const TTest& testFunctor) +{ + typename map<CIdentifier, T>::const_iterator it; - return OV_UndefinedIdentifier; + if (previousID == OV_UndefinedIdentifier) { it = elementMap.begin(); } + else + { + it = elementMap.find(previousID); + if (it == elementMap.end()) { return OV_UndefinedIdentifier; } + ++it; } - /* - template <class T, class TTest> - CIdentifier getNextID(const map<CIdentifier, T*>& elementMap, const CIdentifier& previousID, const TTest& testFunctor) + while (it != elementMap.end()) { - typename map<CIdentifier, T*>::const_iterator it; + if (testFunctor(it)) { return it->first; } + ++it; + } - if(previousID==OV_UndefinedIdentifier) - { - it=elementMap.begin(); - } - else - { - it=elementMap.find(previousID); - if(it==elementMap.end()) { return OV_UndefinedIdentifier; } - ++it; - } + return OV_UndefinedIdentifier; +} - while(it!=elementMap.end()) - { - if(testFunctor(it)) { return it->first; } - ++it; - } +/* +template <class T, class TTest> +CIdentifier getNextID(const map<CIdentifier, T*>& elementMap, const CIdentifier& previousID, const TTest& testFunctor) +{ + typename map<CIdentifier, T*>::const_iterator it; + + if(previousID==OV_UndefinedIdentifier) + { + it=elementMap.begin(); + } + else + { + it=elementMap.find(previousID); + if(it==elementMap.end()) { return OV_UndefinedIdentifier; } + ++it; + } - return OV_UndefinedIdentifier; + while(it!=elementMap.end()) + { + if(testFunctor(it)) { return it->first; } + ++it; } - */ -} // namespace + + return OV_UndefinedIdentifier; +} +*/ +} // namespace //___________________________________________________________________// // // @@ -229,12 +228,9 @@ bool CScenario::merge(const IScenario& scenario, IScenarioMergeCallback* scenari CIdentifier linkID = listID[i]; const ILink* link = scenario.getLinkDetails(linkID); CIdentifier newID; - this->connect(newID, - oldToNewIdMap[link->getSourceBoxIdentifier()], - link->getSourceBoxOutputIndex(), - oldToNewIdMap[link->getTargetBoxIdentifier()], - link->getTargetBoxInputIndex(), - OV_UndefinedIdentifier); + this->connect(newID, oldToNewIdMap[link->getSourceBoxIdentifier()], + link->getSourceBoxOutputIndex(), oldToNewIdMap[link->getTargetBoxIdentifier()], + link->getTargetBoxInputIndex(), OV_UndefinedIdentifier); if (scenarioMergeCallback) { scenarioMergeCallback->process(linkID, newID); } } @@ -1233,44 +1229,32 @@ void CScenario::releaseIdentifierList(CIdentifier* listID) const { delete[] list bool CScenario::getSourceBoxOutputIndex(const CIdentifier& srcBoxID, const CIdentifier& srcBoxOutputID, size_t& srcBoxOutputIdx) { const auto itSourceBox = m_boxes.find(srcBoxID); - OV_ERROR_UNLESS_KRF(itSourceBox != m_boxes.end(), "Source Box [" << srcBoxID.str() << "] is not part of the scenario", ErrorType::ResourceNotFound); - m_boxes[srcBoxID]->getInterfacorIndex(Output, srcBoxOutputID, srcBoxOutputIdx); - return true; } bool CScenario::getTargetBoxInputIndex(const CIdentifier& dstBoxID, const CIdentifier& dstBoxInputID, size_t& dstBoxInputIdx) { const auto itTargetBox = m_boxes.find(dstBoxID); - OV_ERROR_UNLESS_KRF(itTargetBox != m_boxes.end(), "Target Box [" << dstBoxID.str() << "] is not part of the scenario", ErrorType::ResourceNotFound); - m_boxes[dstBoxID]->getInterfacorIndex(Input, dstBoxInputID, dstBoxInputIdx); - return true; } bool CScenario::getSourceBoxOutputIdentifier(const CIdentifier& srcBoxID, const size_t& srcBoxOutputIdx, CIdentifier& srcBoxOutputID) { const auto itSourceBox = m_boxes.find(srcBoxID); - OV_ERROR_UNLESS_KRF(itSourceBox != m_boxes.end(), "Source Box [" << srcBoxID.str() << "] is not part of the scenario", ErrorType::ResourceNotFound); - m_boxes[srcBoxID]->getInterfacorIdentifier(Output, srcBoxOutputIdx, srcBoxOutputID); - return true; } bool CScenario::getTargetBoxInputIdentifier(const CIdentifier& dstBoxID, const size_t& dstBoxInputIdx, CIdentifier& dstBoxInputID) { const auto itTargetBox = m_boxes.find(dstBoxID); - OV_ERROR_UNLESS_KRF(itTargetBox != m_boxes.end(), "Target Box [" << dstBoxID.str() << "] is not part of the scenario", ErrorType::ResourceNotFound); - m_boxes[dstBoxID]->getInterfacorIdentifier(Input, dstBoxInputIdx, dstBoxInputID); - return true; } /** @@ -1351,9 +1335,7 @@ bool CScenario::updateBox(const CIdentifier& boxID) } } - OV_FATAL_UNLESS_K(this->removeBox(boxID), - "Failed to remove redundant box", - ErrorType::Internal); + OV_FATAL_UNLESS_K(this->removeBox(boxID), "Failed to remove redundant box", ErrorType::Internal); CIdentifier updatedBoxIdentifier; OV_FATAL_UNLESS_K(this->addBox(updatedBoxIdentifier, *(itUpdateBox->second.get()), boxID), "Failed to add box to the scenario", ErrorType::Internal); diff --git a/kernel/src/kernel/scenario/ovkCScenario.h b/kernel/src/kernel/scenario/ovkCScenario.h index 0ab71f64f15aea5380c33e6b8c7fd2c47ef3fc3b..93de8eee2de74bf86c06750e917927ea41454079 100644 --- a/kernel/src/kernel/scenario/ovkCScenario.h +++ b/kernel/src/kernel/scenario/ovkCScenario.h @@ -8,147 +8,141 @@ #include <map> #include <memory> -namespace OpenViBE +namespace OpenViBE { +namespace Kernel { +typedef TBox<IBox> CBox; +class CComment; +class CMetadata; +class CLink; + +class CScenario final : public TBox<IScenario> { - namespace Kernel - { - typedef TBox<IBox> CBox; - class CComment; - class CMetadata; - class CLink; - - class CScenario final : public TBox<IScenario> - { - public: - - CScenario(const IKernelContext& ctx, const CIdentifier& identifier); - ~CScenario() override; - - bool clear() override; - bool merge(const IScenario& scenario, IScenarioMergeCallback* scenarioMergeCallback, bool mergeSettings, bool preserveIDs) override; - - CIdentifier getNextBoxIdentifier(const CIdentifier& previousID) const override; - bool isBox(const CIdentifier& boxID) const override; - const IBox* getBoxDetails(const CIdentifier& boxID) const override; - IBox* getBoxDetails(const CIdentifier& boxID) override; - bool addBox(CIdentifier& boxID, const CIdentifier& suggestedBoxID) override; - bool addBox(CIdentifier& boxID, const IBox& box, const CIdentifier& suggestedBoxID) override; - bool addBox(CIdentifier& boxID, const CIdentifier& boxAlgorithmID, const CIdentifier& suggestedBoxID) override; - bool addBox(CIdentifier& boxID, const Plugins::IBoxAlgorithmDesc& boxAlgorithmDesc, const CIdentifier& suggestedBoxID) override; - bool removeBox(const CIdentifier& boxID) override; - - CIdentifier getNextCommentIdentifier(const CIdentifier& previousID) const override; - bool isComment(const CIdentifier& commentID) const override; - const IComment* getCommentDetails(const CIdentifier& commentID) const override; - IComment* getCommentDetails(const CIdentifier& commentID) override; - bool addComment(CIdentifier& commentID, const CIdentifier& suggestedCommentID) override; - bool addComment(CIdentifier& commentID, const IComment& comment, const CIdentifier& suggestedCommentID) override; - bool removeComment(const CIdentifier& commentID) override; - - CIdentifier getNextMetadataIdentifier(const CIdentifier& previousID) const override; - bool isMetadata(const CIdentifier& metadataID) const override; - const IMetadata* getMetadataDetails(const CIdentifier& metadataID) const override; - IMetadata* getMetadataDetails(const CIdentifier& metadataID) override; - bool addMetadata(CIdentifier& metadataID, const CIdentifier& suggestedMetadataID) override; - bool removeMetadata(const CIdentifier& metadataID) override; - - CIdentifier getNextLinkIdentifier(const CIdentifier& previousID) const override; - - CIdentifier getNextLinkIdentifierFromBox(const CIdentifier& previousID, const CIdentifier& boxID) const override; - CIdentifier getNextLinkIdentifierFromBoxOutput(const CIdentifier& previousID, const CIdentifier& boxID, size_t index) const override; - CIdentifier getNextLinkIdentifierToBox(const CIdentifier& previousID, const CIdentifier& boxID) const override; - CIdentifier getNextLinkIdentifierToBoxInput(const CIdentifier& previousID, const CIdentifier& boxID, size_t index) const override; - bool isLink(const CIdentifier& boxID) const override; - - bool setHasIO(bool hasIO) override; - bool hasIO() const override; - bool setScenarioInputLink(size_t scenarioInputIdx, const CIdentifier& boxID, size_t boxInputIdx) override; - bool setScenarioInputLink(size_t scenarioInputIdx, const CIdentifier& boxID, const CIdentifier& boxInputID) override; - bool setScenarioOutputLink(size_t scenarioOutputIdx, const CIdentifier& boxID, size_t boxOutputIdx) override; - bool setScenarioOutputLink(size_t scenarioOutputIdx, const CIdentifier& boxID, const CIdentifier& boxOutputID) override; - bool getScenarioInputLink(size_t scenarioInputIdx, CIdentifier& boxID, size_t& boxInputIdx) const override; - bool getScenarioInputLink(size_t scenarioInputIdx, CIdentifier& boxID, CIdentifier& boxOutputID) const override; - bool getScenarioOutputLink(size_t scenarioOutputIdx, CIdentifier& boxID, size_t& boxOutputIdx) const override; - bool getScenarioOutputLink(size_t scenarioOutputIdx, CIdentifier& boxID, CIdentifier& boxOutputID) const override; - bool removeScenarioInputLink(size_t scenarioInputIdx, const CIdentifier& boxID, size_t boxInputIdx) override; - bool removeScenarioOutputLink(size_t scenarioOutputIdx, const CIdentifier& boxID, size_t boxOutputIdx) override; - - bool removeScenarioInput(size_t index) override; - bool removeScenarioOutput(size_t index) override; - - const ILink* getLinkDetails(const CIdentifier& linkID) const override; - ILink* getLinkDetails(const CIdentifier& linkID) override; - - bool connect(CIdentifier& linkID, const CIdentifier& srcBoxID, const size_t srcBoxOutputIdx, const CIdentifier& dstBoxID, - const size_t dstBoxInputIdx, const CIdentifier& suggestedLinkID) override; - bool connect(CIdentifier& linkID, const CIdentifier& srcBoxID, const CIdentifier& srcBoxOutputID, const CIdentifier& dstBoxID, - const CIdentifier& dstBoxInputID, const CIdentifier& suggestedLinkID) override; - bool disconnect(const CIdentifier& srcBoxID, size_t srcBoxOutputIdx, const CIdentifier& dstBoxID, size_t dstBoxInputIdx) override; - bool disconnect(const CIdentifier& srcBoxID, const CIdentifier& srcBoxOutputID, const CIdentifier& dstBoxID, - const CIdentifier& dstBoxInputID) override; - bool disconnect(const CIdentifier& linkID) override; - - bool getSourceBoxOutputIndex(const CIdentifier& srcBoxID, const CIdentifier& srcBoxOutputID, size_t& srcBoxOutputIdx) override; - - bool getTargetBoxInputIndex(const CIdentifier& dstBoxID, const CIdentifier& dstBoxInputID, size_t& dstBoxInputIdx) override; - - bool getSourceBoxOutputIdentifier(const CIdentifier& srcBoxID, const size_t& srcBoxOutputIdx, CIdentifier& srcBoxOutputID) override; - - bool getTargetBoxInputIdentifier(const CIdentifier& dstBoxID, const size_t& dstBoxInputIdx, CIdentifier& dstBoxInputID) override; - - bool applyLocalSettings() override; - bool checkSettings(IConfigurationManager* configurationManager) override; - - bool isBoxOutdated(const CIdentifier& boxId); - bool checkOutdatedBoxes() override; - bool hasOutdatedBox() override; - - CIdentifier getNextOutdatedBoxIdentifier(const CIdentifier& previousID) const override; - - bool isMetabox() override; - - void getBoxIdentifierList(CIdentifier** listID, size_t* size) const override; - void getCommentIdentifierList(CIdentifier** listID, size_t* size) const override; - void getMetadataIdentifierList(CIdentifier** listID, size_t* size) const override; - void getLinkIdentifierList(CIdentifier** listID, size_t* size) const override; - void getLinkIdentifierFromBoxList(const CIdentifier& boxID, CIdentifier** listID, size_t* size) const override; - void getLinkIdentifierFromBoxOutputList(const CIdentifier& boxID, size_t index, CIdentifier** listID, size_t* size) const override; - void getLinkIdentifierToBoxList(const CIdentifier& boxID, CIdentifier** listID, size_t* size) const override; - void getLinkIdentifierToBoxInputList(const CIdentifier& boxID, size_t index, CIdentifier** listID, size_t* size) const override; - void getOutdatedBoxIdentifierList(CIdentifier** listID, size_t* size) const override; - void releaseIdentifierList(CIdentifier* listID) const override; - - - bool acceptVisitor(IObjectVisitor& objectVisitor) override; - - bool updateBox(const CIdentifier& boxID) override; - - bool containsBoxWithDeprecatedInterfacors() const override; - - bool removeDeprecatedInterfacorsFromBox(const CIdentifier& boxID) override; - - _IsDerivedFromClass_Final_(TBox<IScenario>, OVK_ClassId_Kernel_Scenario_Scenario) - - private: - CIdentifier getUnusedIdentifier(const CIdentifier& suggestedID) const; - - std::map<CIdentifier, CBox*> m_boxes; - std::map<CIdentifier, CComment*> m_comments; - std::map<CIdentifier, CMetadata*> m_metadatas; - std::map<CIdentifier, CLink*> m_links; - std::map<CIdentifier, std::shared_ptr<CBox>> m_outdatedBoxes; - std::map<EBoxInterfacorType, std::map<CIdentifier, std::map<size_t, size_t>>> m_updatedBoxIOCorrespondence; - - - bool m_hasIO = false; - - mutable std::vector<std::pair<CIdentifier, size_t>> m_scenarioInputLinks; - mutable std::vector<std::pair<CIdentifier, size_t>> m_scenarioOutputLinks; - - // Helper members. These are used for quick lookup of next identifiers for the purpose - // of the getNextMetadataIdentifier function. - std::map<CIdentifier, CIdentifier> m_nextMetadataID; - CIdentifier m_firstMetadataID = OV_UndefinedIdentifier; - }; - } // namespace Kernel -} // namespace OpenViBE +public: + + CScenario(const IKernelContext& ctx, const CIdentifier& identifier); + ~CScenario() override; + + bool clear() override; + bool merge(const IScenario& scenario, IScenarioMergeCallback* scenarioMergeCallback, bool mergeSettings, bool preserveIDs) override; + + CIdentifier getNextBoxIdentifier(const CIdentifier& previousID) const override; + bool isBox(const CIdentifier& boxID) const override; + const IBox* getBoxDetails(const CIdentifier& boxID) const override; + IBox* getBoxDetails(const CIdentifier& boxID) override; + bool addBox(CIdentifier& boxID, const CIdentifier& suggestedBoxID) override; + bool addBox(CIdentifier& boxID, const IBox& box, const CIdentifier& suggestedBoxID) override; + bool addBox(CIdentifier& boxID, const CIdentifier& boxAlgorithmID, const CIdentifier& suggestedBoxID) override; + bool addBox(CIdentifier& boxID, const Plugins::IBoxAlgorithmDesc& boxAlgorithmDesc, const CIdentifier& suggestedBoxID) override; + bool removeBox(const CIdentifier& boxID) override; + + CIdentifier getNextCommentIdentifier(const CIdentifier& previousID) const override; + bool isComment(const CIdentifier& commentID) const override; + const IComment* getCommentDetails(const CIdentifier& commentID) const override; + IComment* getCommentDetails(const CIdentifier& commentID) override; + bool addComment(CIdentifier& commentID, const CIdentifier& suggestedCommentID) override; + bool addComment(CIdentifier& commentID, const IComment& comment, const CIdentifier& suggestedCommentID) override; + bool removeComment(const CIdentifier& commentID) override; + + CIdentifier getNextMetadataIdentifier(const CIdentifier& previousID) const override; + bool isMetadata(const CIdentifier& metadataID) const override; + const IMetadata* getMetadataDetails(const CIdentifier& metadataID) const override; + IMetadata* getMetadataDetails(const CIdentifier& metadataID) override; + bool addMetadata(CIdentifier& metadataID, const CIdentifier& suggestedMetadataID) override; + bool removeMetadata(const CIdentifier& metadataID) override; + + CIdentifier getNextLinkIdentifier(const CIdentifier& previousID) const override; + + CIdentifier getNextLinkIdentifierFromBox(const CIdentifier& previousID, const CIdentifier& boxID) const override; + CIdentifier getNextLinkIdentifierFromBoxOutput(const CIdentifier& previousID, const CIdentifier& boxID, size_t index) const override; + CIdentifier getNextLinkIdentifierToBox(const CIdentifier& previousID, const CIdentifier& boxID) const override; + CIdentifier getNextLinkIdentifierToBoxInput(const CIdentifier& previousID, const CIdentifier& boxID, size_t index) const override; + bool isLink(const CIdentifier& boxID) const override; + + bool setHasIO(bool hasIO) override; + bool hasIO() const override; + bool setScenarioInputLink(size_t scenarioInputIdx, const CIdentifier& boxID, size_t boxInputIdx) override; + bool setScenarioInputLink(size_t scenarioInputIdx, const CIdentifier& boxID, const CIdentifier& boxInputID) override; + bool setScenarioOutputLink(size_t scenarioOutputIdx, const CIdentifier& boxID, size_t boxOutputIdx) override; + bool setScenarioOutputLink(size_t scenarioOutputIdx, const CIdentifier& boxID, const CIdentifier& boxOutputID) override; + bool getScenarioInputLink(size_t scenarioInputIdx, CIdentifier& boxID, size_t& boxInputIdx) const override; + bool getScenarioInputLink(size_t scenarioInputIdx, CIdentifier& boxID, CIdentifier& boxOutputID) const override; + bool getScenarioOutputLink(size_t scenarioOutputIdx, CIdentifier& boxID, size_t& boxOutputIdx) const override; + bool getScenarioOutputLink(size_t scenarioOutputIdx, CIdentifier& boxID, CIdentifier& boxOutputID) const override; + bool removeScenarioInputLink(size_t scenarioInputIdx, const CIdentifier& boxID, size_t boxInputIdx) override; + bool removeScenarioOutputLink(size_t scenarioOutputIdx, const CIdentifier& boxID, size_t boxOutputIdx) override; + + bool removeScenarioInput(size_t index) override; + bool removeScenarioOutput(size_t index) override; + + const ILink* getLinkDetails(const CIdentifier& linkID) const override; + ILink* getLinkDetails(const CIdentifier& linkID) override; + + bool connect(CIdentifier& linkID, const CIdentifier& srcBoxID, const size_t srcBoxOutputIdx, const CIdentifier& dstBoxID, + const size_t dstBoxInputIdx, const CIdentifier& suggestedLinkID) override; + bool connect(CIdentifier& linkID, const CIdentifier& srcBoxID, const CIdentifier& srcBoxOutputID, const CIdentifier& dstBoxID, + const CIdentifier& dstBoxInputID, const CIdentifier& suggestedLinkID) override; + bool disconnect(const CIdentifier& srcBoxID, size_t srcBoxOutputIdx, const CIdentifier& dstBoxID, size_t dstBoxInputIdx) override; + bool disconnect(const CIdentifier& srcBoxID, const CIdentifier& srcBoxOutputID, const CIdentifier& dstBoxID, const CIdentifier& dstBoxInputID) override; + bool disconnect(const CIdentifier& linkID) override; + + bool getSourceBoxOutputIndex(const CIdentifier& srcBoxID, const CIdentifier& srcBoxOutputID, size_t& srcBoxOutputIdx) override; + bool getTargetBoxInputIndex(const CIdentifier& dstBoxID, const CIdentifier& dstBoxInputID, size_t& dstBoxInputIdx) override; + bool getSourceBoxOutputIdentifier(const CIdentifier& srcBoxID, const size_t& srcBoxOutputIdx, CIdentifier& srcBoxOutputID) override; + bool getTargetBoxInputIdentifier(const CIdentifier& dstBoxID, const size_t& dstBoxInputIdx, CIdentifier& dstBoxInputID) override; + + bool applyLocalSettings() override; + bool checkSettings(IConfigurationManager* configurationManager) override; + + bool isBoxOutdated(const CIdentifier& boxId); + bool checkOutdatedBoxes() override; + bool hasOutdatedBox() override; + + CIdentifier getNextOutdatedBoxIdentifier(const CIdentifier& previousID) const override; + + bool isMetabox() override; + + void getBoxIdentifierList(CIdentifier** listID, size_t* size) const override; + void getCommentIdentifierList(CIdentifier** listID, size_t* size) const override; + void getMetadataIdentifierList(CIdentifier** listID, size_t* size) const override; + void getLinkIdentifierList(CIdentifier** listID, size_t* size) const override; + void getLinkIdentifierFromBoxList(const CIdentifier& boxID, CIdentifier** listID, size_t* size) const override; + void getLinkIdentifierFromBoxOutputList(const CIdentifier& boxID, size_t index, CIdentifier** listID, size_t* size) const override; + void getLinkIdentifierToBoxList(const CIdentifier& boxID, CIdentifier** listID, size_t* size) const override; + void getLinkIdentifierToBoxInputList(const CIdentifier& boxID, size_t index, CIdentifier** listID, size_t* size) const override; + void getOutdatedBoxIdentifierList(CIdentifier** listID, size_t* size) const override; + void releaseIdentifierList(CIdentifier* listID) const override; + + + bool acceptVisitor(IObjectVisitor& objectVisitor) override; + + bool updateBox(const CIdentifier& boxID) override; + + bool containsBoxWithDeprecatedInterfacors() const override; + + bool removeDeprecatedInterfacorsFromBox(const CIdentifier& boxID) override; + + _IsDerivedFromClass_Final_(TBox<IScenario>, OVK_ClassId_Kernel_Scenario_Scenario) + +private: + CIdentifier getUnusedIdentifier(const CIdentifier& suggestedID) const; + + std::map<CIdentifier, CBox*> m_boxes; + std::map<CIdentifier, CComment*> m_comments; + std::map<CIdentifier, CMetadata*> m_metadatas; + std::map<CIdentifier, CLink*> m_links; + std::map<CIdentifier, std::shared_ptr<CBox>> m_outdatedBoxes; + std::map<EBoxInterfacorType, std::map<CIdentifier, std::map<size_t, size_t>>> m_updatedBoxIOCorrespondence; + + + bool m_hasIO = false; + + mutable std::vector<std::pair<CIdentifier, size_t>> m_scenarioInputLinks; + mutable std::vector<std::pair<CIdentifier, size_t>> m_scenarioOutputLinks; + + // Helper members. These are used for quick lookup of next identifiers for the purpose + // of the getNextMetadataIdentifier function. + std::map<CIdentifier, CIdentifier> m_nextMetadataID; + CIdentifier m_firstMetadataID = OV_UndefinedIdentifier; +}; +} // namespace Kernel +} // namespace OpenViBE diff --git a/kernel/src/kernel/scenario/ovkCScenarioManager.cpp b/kernel/src/kernel/scenario/ovkCScenarioManager.cpp index 28ddb07fa206aeadb88799dd07f2bdfbc37764c1..51fb5af08733619fd624dc9e12af8b968603019d 100755 --- a/kernel/src/kernel/scenario/ovkCScenarioManager.cpp +++ b/kernel/src/kernel/scenario/ovkCScenarioManager.cpp @@ -12,8 +12,7 @@ using namespace OpenViBE; using namespace /*OpenViBE::*/Kernel; using namespace std; -CScenarioManager::CScenarioManager(const IKernelContext& ctx) - : TKernelObject<IScenarioManager>(ctx) {} +CScenarioManager::CScenarioManager(const IKernelContext& ctx) : TKernelObject<IScenarioManager>(ctx) {} CScenarioManager::~CScenarioManager() { for (auto i = m_scenarios.begin(); i != m_scenarios.end(); ++i) { delete i->second; } } @@ -72,8 +71,7 @@ bool CScenarioManager::createScenario(CIdentifier& scenarioID) return true; } -bool CScenarioManager::importScenario(CIdentifier& scenarioID, const IMemoryBuffer& iMemoryBuffer, - const CIdentifier& scenarioImporterAlgorithmID) +bool CScenarioManager::importScenario(CIdentifier& scenarioID, const IMemoryBuffer& iMemoryBuffer, const CIdentifier& scenarioImporterAlgorithmID) { scenarioID = OV_UndefinedIdentifier; @@ -175,8 +173,7 @@ bool CScenarioManager::importScenario(CIdentifier& scenarioID, const IMemoryBuff return true; } -bool CScenarioManager::importScenarioFromFile(CIdentifier& scenarioID, const CString& fileName, - const CIdentifier& scenarioImporterAlgorithmID) +bool CScenarioManager::importScenarioFromFile(CIdentifier& scenarioID, const CString& fileName, const CIdentifier& scenarioImporterAlgorithmID) { scenarioID = OV_UndefinedIdentifier; diff --git a/kernel/src/kernel/scenario/ovkCScenarioManager.h b/kernel/src/kernel/scenario/ovkCScenarioManager.h index 0c95a43bd705594b2dc527599371aa8e73f11e3f..2e2834e2529e677ce48a9125845b6eb7dcbe08a7 100644 --- a/kernel/src/kernel/scenario/ovkCScenarioManager.h +++ b/kernel/src/kernel/scenario/ovkCScenarioManager.h @@ -4,57 +4,55 @@ #include <map> -namespace OpenViBE +namespace OpenViBE { +namespace Kernel { +class CScenario; + +class CScenarioManager final : public TKernelObject<IScenarioManager> { - namespace Kernel - { - class CScenario; - - class CScenarioManager final : public TKernelObject<IScenarioManager> - { - public: - - explicit CScenarioManager(const IKernelContext& ctx); - ~CScenarioManager() override; - void cloneScenarioImportersAndExporters(const IScenarioManager& scenarioManager) override; - CIdentifier getNextScenarioIdentifier(const CIdentifier& previousID) const override; - bool isScenario(const CIdentifier& scenarioID) const override; - bool createScenario(CIdentifier& scenarioID) override; - bool importScenario(CIdentifier& scenarioID, const IMemoryBuffer& iMemoryBuffer, const CIdentifier& scenarioImporterAlgorithmID) override; - bool importScenarioFromFile(CIdentifier& scenarioID, const CString& fileName, const CIdentifier& scenarioImporterAlgorithmID) override; - bool importScenarioFromFile(CIdentifier& scenarioID, const CIdentifier& importContext, const CString& fileName) override; - bool registerScenarioImporter(const CIdentifier& importContext, const CString& fileNameExtension, - const CIdentifier& scenarioImporterAlgorithmIdentifier) override; - bool unregisterScenarioImporter(const CIdentifier& importContext, const CString& fileNameExtension) override; - CIdentifier getNextScenarioImportContext(const CIdentifier& importContext) const override; - CString getNextScenarioImporter(const CIdentifier& importContext, const CString& fileNameExtension) const override; - CIdentifier getScenarioImporterAlgorithmIdentifier(const CIdentifier& importContext, const CString& fileNameExtension) const override; - bool exportScenario(IMemoryBuffer& oMemoryBuffer, const CIdentifier& scenarioID, const CIdentifier& scenarioExporterAlgorithmID) const override; - bool exportScenarioToFile(const CString& fileName, const CIdentifier& scenarioID, const CIdentifier& scenarioExporterAlgorithmID) const override; - bool exportScenarioToFile(const CIdentifier& exportContext, const CString& fileName, const CIdentifier& scenarioID) override; - bool registerScenarioExporter(const CIdentifier& exportContext, const CString& fileNameExtension, - const CIdentifier& scenarioExporterAlgorithmIdentifier) override; - bool unregisterScenarioExporter(const CIdentifier& exportContext, const CString& fileNameExtension) override; - CIdentifier getNextScenarioExportContext(const CIdentifier& exportContext) const override; - CString getNextScenarioExporter(const CIdentifier& exportContext, const CString& fileNameExtension) const override; - CIdentifier getScenarioExporterAlgorithmIdentifier(const CIdentifier& exportContext, const CString& fileNameExtension) const override; - bool releaseScenario(const CIdentifier& scenarioID) override; - IScenario& getScenario(const CIdentifier& scenarioID) override; - - _IsDerivedFromClass_Final_(TKernelObject<IScenarioManager>, OVK_ClassId_Kernel_Scenario_ScenarioManager) - - protected: - - CIdentifier getUnusedIdentifier() const; - - std::map<CIdentifier, CScenario*> m_scenarios; - private: - /// Scenario Import Context -> File Name Extension -> Scenario Importer Identifier - std::map<CIdentifier, std::map<std::string, CIdentifier>> m_importers; - /// Scenario Export Context -> File Name Extension -> Scenario Exporter Identifier - std::map<CIdentifier, std::map<std::string, CIdentifier>> m_exporters; - - IScenario& getScenario(const CIdentifier& scenarioID) const; - }; - } // namespace Kernel -} // namespace OpenViBE +public: + + explicit CScenarioManager(const IKernelContext& ctx); + ~CScenarioManager() override; + void cloneScenarioImportersAndExporters(const IScenarioManager& scenarioManager) override; + CIdentifier getNextScenarioIdentifier(const CIdentifier& previousID) const override; + bool isScenario(const CIdentifier& scenarioID) const override; + bool createScenario(CIdentifier& scenarioID) override; + bool importScenario(CIdentifier& scenarioID, const IMemoryBuffer& iMemoryBuffer, const CIdentifier& scenarioImporterAlgorithmID) override; + bool importScenarioFromFile(CIdentifier& scenarioID, const CString& fileName, const CIdentifier& scenarioImporterAlgorithmID) override; + bool importScenarioFromFile(CIdentifier& scenarioID, const CIdentifier& importContext, const CString& fileName) override; + bool registerScenarioImporter(const CIdentifier& importContext, const CString& fileNameExtension, + const CIdentifier& scenarioImporterAlgorithmIdentifier) override; + bool unregisterScenarioImporter(const CIdentifier& importContext, const CString& fileNameExtension) override; + CIdentifier getNextScenarioImportContext(const CIdentifier& importContext) const override; + CString getNextScenarioImporter(const CIdentifier& importContext, const CString& fileNameExtension) const override; + CIdentifier getScenarioImporterAlgorithmIdentifier(const CIdentifier& importContext, const CString& fileNameExtension) const override; + bool exportScenario(IMemoryBuffer& oMemoryBuffer, const CIdentifier& scenarioID, const CIdentifier& scenarioExporterAlgorithmID) const override; + bool exportScenarioToFile(const CString& fileName, const CIdentifier& scenarioID, const CIdentifier& scenarioExporterAlgorithmID) const override; + bool exportScenarioToFile(const CIdentifier& exportContext, const CString& fileName, const CIdentifier& scenarioID) override; + bool registerScenarioExporter(const CIdentifier& exportContext, const CString& fileNameExtension, + const CIdentifier& scenarioExporterAlgorithmIdentifier) override; + bool unregisterScenarioExporter(const CIdentifier& exportContext, const CString& fileNameExtension) override; + CIdentifier getNextScenarioExportContext(const CIdentifier& exportContext) const override; + CString getNextScenarioExporter(const CIdentifier& exportContext, const CString& fileNameExtension) const override; + CIdentifier getScenarioExporterAlgorithmIdentifier(const CIdentifier& exportContext, const CString& fileNameExtension) const override; + bool releaseScenario(const CIdentifier& scenarioID) override; + IScenario& getScenario(const CIdentifier& scenarioID) override; + + _IsDerivedFromClass_Final_(TKernelObject<IScenarioManager>, OVK_ClassId_Kernel_Scenario_ScenarioManager) + +protected: + + CIdentifier getUnusedIdentifier() const; + + std::map<CIdentifier, CScenario*> m_scenarios; +private: + /// Scenario Import Context -> File Name Extension -> Scenario Importer Identifier + std::map<CIdentifier, std::map<std::string, CIdentifier>> m_importers; + /// Scenario Export Context -> File Name Extension -> Scenario Exporter Identifier + std::map<CIdentifier, std::map<std::string, CIdentifier>> m_exporters; + + IScenario& getScenario(const CIdentifier& scenarioID) const; +}; +} // namespace Kernel +} // namespace OpenViBE diff --git a/kernel/src/kernel/scenario/ovkCScenarioSettingKeywordParserCallback.h b/kernel/src/kernel/scenario/ovkCScenarioSettingKeywordParserCallback.h index 99cff0812f1c80dbb1976a177ce996c9d9dbb650..0fde9969f9935f944bb8938bfd5bc3e5872ec5ac 100644 --- a/kernel/src/kernel/scenario/ovkCScenarioSettingKeywordParserCallback.h +++ b/kernel/src/kernel/scenario/ovkCScenarioSettingKeywordParserCallback.h @@ -2,21 +2,19 @@ #include <openvibe/ov_all.h> -namespace OpenViBE +namespace OpenViBE { +namespace Kernel { +class CScenarioSettingKeywordParserCallback final : public IConfigurationKeywordExpandCallback { - namespace Kernel - { - class CScenarioSettingKeywordParserCallback final : public IConfigurationKeywordExpandCallback - { - public: - explicit CScenarioSettingKeywordParserCallback(const IScenario& scenario) - : m_rScenario(scenario) {} +public: + explicit CScenarioSettingKeywordParserCallback(const IScenario& scenario) + : m_rScenario(scenario) {} - ~CScenarioSettingKeywordParserCallback() override {} - bool expand(const CString& rStringToExpand, CString& rExpandedString) const override; + ~CScenarioSettingKeywordParserCallback() override {} + bool expand(const CString& rStringToExpand, CString& rExpandedString) const override; - private: - const IScenario& m_rScenario; - }; - } // namespace Kernel -} // namespace OpenViBE +private: + const IScenario& m_rScenario; +}; +} // namespace Kernel +} // namespace OpenViBE diff --git a/kernel/src/kernel/scenario/ovkTAttributable.h b/kernel/src/kernel/scenario/ovkTAttributable.h index d6cfa532ee00079110476f11439e4767920dff31..392f17af139ee059607be597e7fb91460f15751a 100644 --- a/kernel/src/kernel/scenario/ovkTAttributable.h +++ b/kernel/src/kernel/scenario/ovkTAttributable.h @@ -6,77 +6,72 @@ #include <map> -namespace OpenViBE +namespace OpenViBE { +namespace Kernel { +template <class T> +class TAttributable : public T { - namespace Kernel +public: + + explicit TAttributable(const IKernelContext& ctx) : T(ctx) { } + + bool addAttribute(const CIdentifier& attributeID, const CString& sAttributeValue) override + { + const auto itAttribute = m_attributes.find(attributeID); + if (itAttribute != m_attributes.end()) { return false; } + m_attributes[attributeID] = sAttributeValue; + return true; + } + + bool removeAttribute(const CIdentifier& attributeID) override + { + const auto itAttribute = m_attributes.find(attributeID); + if (itAttribute == m_attributes.end()) { return false; } + m_attributes.erase(itAttribute); + return true; + } + + bool removeAllAttributes() override + { + m_attributes.clear(); + return true; + } + + CString getAttributeValue(const CIdentifier& attributeID) const override { - template <class T> - class TAttributable : public T + const auto itAttribute = m_attributes.find(attributeID); + if (itAttribute == m_attributes.end()) { return CString(""); } + return itAttribute->second; + } + + bool setAttributeValue(const CIdentifier& attributeID, const CString& value) override + { + auto itAttribute = m_attributes.find(attributeID); + if (itAttribute == m_attributes.end()) { - public: - - explicit TAttributable(const IKernelContext& ctx) : T(ctx) { } - - bool addAttribute(const CIdentifier& attributeID, const CString& sAttributeValue) override - { - const auto itAttribute = m_attributes.find(attributeID); - if (itAttribute != m_attributes.end()) { return false; } - m_attributes[attributeID] = sAttributeValue; - return true; - } - - bool removeAttribute(const CIdentifier& attributeID) override - { - const auto itAttribute = m_attributes.find(attributeID); - if (itAttribute == m_attributes.end()) { return false; } - m_attributes.erase(itAttribute); - return true; - } - - bool removeAllAttributes() override - { - m_attributes.clear(); - return true; - } - - CString getAttributeValue(const CIdentifier& attributeID) const override - { - const auto itAttribute = m_attributes.find(attributeID); - if (itAttribute == m_attributes.end()) { return CString(""); } - return itAttribute->second; - } - - bool setAttributeValue(const CIdentifier& attributeID, const CString& value) override - { - auto itAttribute = m_attributes.find(attributeID); - if (itAttribute == m_attributes.end()) - { - m_attributes[attributeID] = value; - return true; - } - itAttribute->second = value; - return true; - } - - bool hasAttribute(const CIdentifier& attributeID) const override - { - const auto itAttribute = m_attributes.find(attributeID); - if (itAttribute == m_attributes.end()) { return false; } - return true; - } - - bool hasAttributes() const override { return !m_attributes.empty(); } - - CIdentifier getNextAttributeIdentifier(const CIdentifier& previousID) const override - { - return getNextIdentifier<CString>(m_attributes, previousID); - } - - _IsDerivedFromClass_(T, OVK_ClassId_Kernel_Scenario_AttributableT) - - protected: - - std::map<CIdentifier, CString> m_attributes; - }; - } // namespace Kernel -} // namespace OpenViBE + m_attributes[attributeID] = value; + return true; + } + itAttribute->second = value; + return true; + } + + bool hasAttribute(const CIdentifier& attributeID) const override + { + const auto itAttribute = m_attributes.find(attributeID); + if (itAttribute == m_attributes.end()) { return false; } + return true; + } + + bool hasAttributes() const override { return !m_attributes.empty(); } + + CIdentifier getNextAttributeIdentifier(const CIdentifier& previousID) const override { return getNextIdentifier<CString>(m_attributes, previousID); } + + _IsDerivedFromClass_(T, OVK_ClassId_Kernel_Scenario_AttributableT) + +protected: + + std::map<CIdentifier, CString> m_attributes; +}; +} // namespace Kernel +} // namespace OpenViBE diff --git a/kernel/src/kernel/scenario/ovkTBox.hpp b/kernel/src/kernel/scenario/ovkTBox.hpp index 6381d45fac101af91e284a7d39e38220a383dbc6..46236b8443585f2f6e262c08f427286544ae8792 100755 --- a/kernel/src/kernel/scenario/ovkTBox.hpp +++ b/kernel/src/kernel/scenario/ovkTBox.hpp @@ -67,9 +67,7 @@ class CInputOutput : public CInterfacor { public: CInputOutput() { } - CInputOutput(const CInputOutput& i) : CInterfacor(i) { this->m_Deprecated = false; } - CInputOutput(const OpenViBE::CString& name, const OpenViBE::CIdentifier& idType, const OpenViBE::CIdentifier& id) : CInterfacor(name, idType, id) { } }; @@ -77,11 +75,8 @@ class CSetting : public CInterfacor { public: CSetting() { } - CSetting(const CSetting& s) : CInterfacor(s), m_DefaultValue(s.m_DefaultValue), m_Value(s.m_Value), m_Mod(s.m_Mod) { this->m_Deprecated = false; } - - CSetting(const OpenViBE::CString& name, const OpenViBE::CIdentifier& idType, const OpenViBE::CIdentifier& id, const OpenViBE::CString& defaultValue, - const bool modifiable) + CSetting(const OpenViBE::CString& name, const OpenViBE::CIdentifier& idType, const OpenViBE::CIdentifier& id, const OpenViBE::CString& defaultValue, const bool modifiable) : CInterfacor(name, idType, id), m_DefaultValue(defaultValue), m_Value(defaultValue), m_Mod(modifiable) { } OpenViBE::CString m_DefaultValue; @@ -90,1433 +85,1425 @@ public: }; -namespace OpenViBE +namespace OpenViBE { +namespace Kernel { +template <class T> +class TBox : public TAttributable<TKernelObject<T>> { - namespace Kernel +public: + + explicit TBox(const IKernelContext& ctx) : TAttributable<TKernelObject<T>>(ctx), m_identifier(OV_UndefinedIdentifier), + m_algorithmClassID(OV_UndefinedIdentifier) { - template <class T> - class TBox : public TAttributable<TKernelObject<T>> + for (auto i : { Input, Output, Setting }) { - public: - - explicit TBox(const IKernelContext& ctx) : TAttributable<TKernelObject<T>>(ctx), m_identifier(OV_UndefinedIdentifier), - m_algorithmClassID(OV_UndefinedIdentifier) - { - for (auto i : { Input, Output, Setting }) - { - m_interfacors[i] = std::vector<std::shared_ptr<CInterfacor>>(); - m_interfacorIDToIdx[i] = std::map<CIdentifier, size_t>(); - m_interfacorNameToIdx[i] = std::map<CString, size_t>(); - } - } + m_interfacors[i] = std::vector<std::shared_ptr<CInterfacor>>(); + m_interfacorIDToIdx[i] = std::map<CIdentifier, size_t>(); + m_interfacorNameToIdx[i] = std::map<CString, size_t>(); + } + } - ~TBox() override - { - if (m_boxAlgorithmDesc && m_boxListener) - { - CBoxListenerContext ctx(this->getKernelContext(), *this, 0xffffffff); - m_boxListener->uninitialize(ctx); - m_boxAlgorithmDesc->releaseBoxListener(m_boxListener); - } - } - - void setOwnerScenario(IScenario* ownerScenario) { m_ownerScenario = ownerScenario; } - CIdentifier getIdentifier() const override { return m_identifier; } - CString getName() const override { return m_name; } - CIdentifier getAlgorithmClassIdentifier() const override { return m_algorithmClassID; } - - bool setIdentifier(const CIdentifier& identifier) override - { - OV_ERROR_UNLESS_KRF(m_identifier == OV_UndefinedIdentifier, "Trying to overwrite an already set indentifier", ErrorType::BadCall); - OV_ERROR_UNLESS_KRF(identifier != OV_UndefinedIdentifier, "Trying to set an undefined identifier", ErrorType::BadArgument); - - m_identifier = identifier; - this->notify(EBoxModification::IdentifierChanged); - - return true; - } - - bool setName(const CString& name) override - { - m_name = name; - this->notify(EBoxModification::NameChanged); - return true; - } - - bool setAlgorithmClassIdentifier(const CIdentifier& algorithmClassID) override - { - // We need to set the box algorithm identifier in any case. This is because OpenViBE should be able to load - // a scenario with non-existing boxes and save it without modifying them. - m_algorithmClassID = algorithmClassID; + ~TBox() override + { + if (m_boxAlgorithmDesc && m_boxListener) + { + CBoxListenerContext ctx(this->getKernelContext(), *this, 0xffffffff); + m_boxListener->uninitialize(ctx); + m_boxAlgorithmDesc->releaseBoxListener(m_boxListener); + } + } + + void setOwnerScenario(IScenario* ownerScenario) { m_ownerScenario = ownerScenario; } + CIdentifier getIdentifier() const override { return m_identifier; } + CString getName() const override { return m_name; } + CIdentifier getAlgorithmClassIdentifier() const override { return m_algorithmClassID; } + + bool setIdentifier(const CIdentifier& identifier) override + { + OV_ERROR_UNLESS_KRF(m_identifier == OV_UndefinedIdentifier, "Trying to overwrite an already set indentifier", ErrorType::BadCall); + OV_ERROR_UNLESS_KRF(identifier != OV_UndefinedIdentifier, "Trying to set an undefined identifier", ErrorType::BadArgument); - if (!(algorithmClassID == OVP_ClassId_BoxAlgorithm_Metabox || this - ->getKernelContext().getPluginManager().canCreatePluginObject(algorithmClassID))) - { - // OV_WARNING_K("Box algorithm descriptor not found " << algorithmClassID.str()); - return true; - } + m_identifier = identifier; + this->notify(EBoxModification::IdentifierChanged); - if (m_boxAlgorithmDesc && m_boxListener) - { - CBoxListenerContext context(this->getKernelContext(), *this, 0xffffffff); - m_boxListener->uninitialize(context); - m_boxAlgorithmDesc->releaseBoxListener(m_boxListener); - } + return true; + } - const Plugins::IPluginObjectDesc* pluginObjectDesc = this->getKernelContext().getPluginManager().getPluginObjectDescCreating(algorithmClassID); - m_boxAlgorithmDesc = dynamic_cast<const Plugins::IBoxAlgorithmDesc*>(pluginObjectDesc); + bool setName(const CString& name) override + { + m_name = name; + this->notify(EBoxModification::NameChanged); + return true; + } - if (m_boxAlgorithmDesc) - { - m_boxListener = m_boxAlgorithmDesc->createBoxListener(); - if (m_boxListener) - { - CBoxListenerContext context(this->getKernelContext(), *this, 0xffffffff); - m_boxListener->initialize(context); - } - } + bool setAlgorithmClassIdentifier(const CIdentifier& algorithmClassID) override + { + // We need to set the box algorithm identifier in any case. This is because OpenViBE should be able to load + // a scenario with non-existing boxes and save it without modifying them. + m_algorithmClassID = algorithmClassID; - if (algorithmClassID != OVP_ClassId_BoxAlgorithm_Metabox) - { - //We use the neutralized version of CBoxProto to just initialize the stream restriction mecanism - CBoxProtoRestriction oTempProto(this->getKernelContext(), *this); - m_boxAlgorithmDesc->getBoxPrototype(oTempProto); - } + if (!(algorithmClassID == OVP_ClassId_BoxAlgorithm_Metabox || this + ->getKernelContext().getPluginManager().canCreatePluginObject(algorithmClassID))) + { + // OV_WARNING_K("Box algorithm descriptor not found " << algorithmClassID.str()); + return true; + } - this->notify(EBoxModification::AlgorithmClassIdentifierChanged); + if (m_boxAlgorithmDesc && m_boxListener) + { + CBoxListenerContext context(this->getKernelContext(), *this, 0xffffffff); + m_boxListener->uninitialize(context); + m_boxAlgorithmDesc->releaseBoxListener(m_boxListener); + } - return true; - } + const Plugins::IPluginObjectDesc* pluginObjectDesc = this->getKernelContext().getPluginManager().getPluginObjectDescCreating(algorithmClassID); + m_boxAlgorithmDesc = dynamic_cast<const Plugins::IBoxAlgorithmDesc*>(pluginObjectDesc); - bool initializeFromAlgorithmClassIdentifier(const CIdentifier& algorithmClassID) override + if (m_boxAlgorithmDesc) + { + m_boxListener = m_boxAlgorithmDesc->createBoxListener(); + if (m_boxListener) { - if (!this->initializeFromAlgorithmClassIdentifierNoInit(algorithmClassID)) { return false; } - - this->notify(EBoxModification::Initialized); - this->notify(EBoxModification::DefaultInitialized); - return true; + CBoxListenerContext context(this->getKernelContext(), *this, 0xffffffff); + m_boxListener->initialize(context); } + } - bool initializeFromAlgorithmClassIdentifierNoInit(const CIdentifier& algorithmClassID) - { - this->disableNotification(); + if (algorithmClassID != OVP_ClassId_BoxAlgorithm_Metabox) + { + //We use the neutralized version of CBoxProto to just initialize the stream restriction mecanism + CBoxProtoRestriction oTempProto(this->getKernelContext(), *this); + m_boxAlgorithmDesc->getBoxPrototype(oTempProto); + } - const Plugins::IBoxAlgorithmDesc* desc = dynamic_cast<const Plugins::IBoxAlgorithmDesc*>(this - ->getKernelContext().getPluginManager(). - getPluginObjectDescCreating(algorithmClassID)); - if (!desc) - { - this->enableNotification(); - OV_ERROR_KRF("Algorithm descriptor not found " << algorithmClassID.str(), ErrorType::ResourceNotFound); - } + this->notify(EBoxModification::AlgorithmClassIdentifierChanged); - this->clearBox(); - this->setName(desc->getName()); - this->setAlgorithmClassIdentifier(algorithmClassID); + return true; + } - CBoxProto proto(this->getKernelContext(), *this); - desc->getBoxPrototype(proto); + bool initializeFromAlgorithmClassIdentifier(const CIdentifier& algorithmClassID) override + { + if (!this->initializeFromAlgorithmClassIdentifierNoInit(algorithmClassID)) { return false; } - if (this->hasAttribute(OV_AttributeId_Box_InitialPrototypeHashValue)) - { - this->setAttributeValue( - OV_AttributeId_Box_InitialPrototypeHashValue, this->getPluginManager().getPluginObjectHashValue(algorithmClassID).toString()); - } - else - { - this->addAttribute( - OV_AttributeId_Box_InitialPrototypeHashValue, this->getPluginManager().getPluginObjectHashValue(algorithmClassID).toString()); - } + this->notify(EBoxModification::Initialized); + this->notify(EBoxModification::DefaultInitialized); + return true; + } - this->enableNotification(); + bool initializeFromAlgorithmClassIdentifierNoInit(const CIdentifier& algorithmClassID) + { + this->disableNotification(); - return true; - } + const Plugins::IBoxAlgorithmDesc* desc = dynamic_cast<const Plugins::IBoxAlgorithmDesc*>(this + ->getKernelContext().getPluginManager(). + getPluginObjectDescCreating(algorithmClassID)); + if (!desc) + { + this->enableNotification(); + OV_ERROR_KRF("Algorithm descriptor not found " << algorithmClassID.str(), ErrorType::ResourceNotFound); + } - bool initializeFromBoxAlgorithmDesc(const Plugins::IBoxAlgorithmDesc& boxAlgorithmDesc) - { - this->clearBox(); - this->setName(boxAlgorithmDesc.getName()); - this->setAlgorithmClassIdentifier(boxAlgorithmDesc.getCreatedClassIdentifier()); + this->clearBox(); + this->setName(desc->getName()); + this->setAlgorithmClassIdentifier(algorithmClassID); - CBoxProto boxProto(this->getKernelContext(), *this); - boxAlgorithmDesc.getBoxPrototype(boxProto); + CBoxProto proto(this->getKernelContext(), *this); + desc->getBoxPrototype(proto); - if (this->hasAttribute(OV_AttributeId_Box_InitialPrototypeHashValue)) - { - this->setAttributeValue( - OV_AttributeId_Box_InitialPrototypeHashValue, this->getPluginManager().getPluginObjectHashValue(boxAlgorithmDesc).toString()); - } - else - { - this->addAttribute( - OV_AttributeId_Box_InitialPrototypeHashValue, this->getPluginManager().getPluginObjectHashValue(boxAlgorithmDesc).toString()); - } + if (this->hasAttribute(OV_AttributeId_Box_InitialPrototypeHashValue)) + { + this->setAttributeValue( + OV_AttributeId_Box_InitialPrototypeHashValue, this->getPluginManager().getPluginObjectHashValue(algorithmClassID).toString()); + } + else + { + this->addAttribute( + OV_AttributeId_Box_InitialPrototypeHashValue, this->getPluginManager().getPluginObjectHashValue(algorithmClassID).toString()); + } - this->enableNotification(); + this->enableNotification(); - this->notify(EBoxModification::Initialized); - this->notify(EBoxModification::DefaultInitialized); - return true; - } + return true; + } - bool initializeFromExistingBox(const IBox& rExistingBox) override - { - this->disableNotification(); - m_isObserverNotificationActive = false; + bool initializeFromBoxAlgorithmDesc(const Plugins::IBoxAlgorithmDesc& boxAlgorithmDesc) + { + this->clearBox(); + this->setName(boxAlgorithmDesc.getName()); + this->setAlgorithmClassIdentifier(boxAlgorithmDesc.getCreatedClassIdentifier()); - this->clearBox(); - this->setName(rExistingBox.getName()); - this->setAlgorithmClassIdentifier(rExistingBox.getAlgorithmClassIdentifier()); + CBoxProto boxProto(this->getKernelContext(), *this); + boxAlgorithmDesc.getBoxPrototype(boxProto); - for (const auto interfacorType : { Input, Output, Setting }) - { - for (size_t i = 0; i < rExistingBox.getInterfacorCountIncludingDeprecated(interfacorType); ++i) - { - CIdentifier identifier = OV_UndefinedIdentifier; - CIdentifier type = OV_UndefinedIdentifier; - CString name; - bool isDeprecated; - rExistingBox.getInterfacorIdentifier(interfacorType, i, identifier); - rExistingBox.getInterfacorType(interfacorType, i, type); - rExistingBox.getInterfacorName(interfacorType, i, name); - rExistingBox.getInterfacorDeprecatedStatus(interfacorType, i, isDeprecated); - this->addInterfacor(interfacorType, name, type, identifier, true); - this->setInterfacorDeprecatedStatus(interfacorType, i, isDeprecated); - - if (interfacorType == Setting) - { - CString value; - CString defaultValue; - bool isModifiable; - rExistingBox.getSettingValue(i, value); - rExistingBox.getSettingDefaultValue(i, defaultValue); - rExistingBox.getSettingMod(i, isModifiable); - this->setSettingDefaultValue(i, defaultValue); - this->setSettingValue(i, value); - this->setSettingMod(i, isModifiable); - if (isModifiable) { m_modifiableSettingIndexes.push_back(i); } - } - } - } + if (this->hasAttribute(OV_AttributeId_Box_InitialPrototypeHashValue)) + { + this->setAttributeValue( + OV_AttributeId_Box_InitialPrototypeHashValue, this->getPluginManager().getPluginObjectHashValue(boxAlgorithmDesc).toString()); + } + else + { + this->addAttribute( + OV_AttributeId_Box_InitialPrototypeHashValue, this->getPluginManager().getPluginObjectHashValue(boxAlgorithmDesc).toString()); + } - CIdentifier id = rExistingBox.getNextAttributeIdentifier(OV_UndefinedIdentifier); - while (id != OV_UndefinedIdentifier) - { - this->addAttribute(id, rExistingBox.getAttributeValue(id)); - id = rExistingBox.getNextAttributeIdentifier(id); - } + this->enableNotification(); - CIdentifier streamTypeID = OV_UndefinedIdentifier; - while ((streamTypeID = this->getKernelContext().getTypeManager().getNextTypeIdentifier(streamTypeID)) != - OV_UndefinedIdentifier) - { - if (this->getKernelContext().getTypeManager().isStream(streamTypeID)) - { - //First check if it is a stream - if (rExistingBox.hasInputSupport(streamTypeID)) { this->addInputSupport(streamTypeID); } - if (rExistingBox.hasOutputSupport(streamTypeID)) { this->addOutputSupport(streamTypeID); } - } - } + this->notify(EBoxModification::Initialized); + this->notify(EBoxModification::DefaultInitialized); + return true; + } - this->enableNotification(); + bool initializeFromExistingBox(const IBox& rExistingBox) override + { + this->disableNotification(); + m_isObserverNotificationActive = false; - this->notify(EBoxModification::Initialized); + this->clearBox(); + this->setName(rExistingBox.getName()); + this->setAlgorithmClassIdentifier(rExistingBox.getAlgorithmClassIdentifier()); - return true; + for (const auto interfacorType : { Input, Output, Setting }) + { + for (size_t i = 0; i < rExistingBox.getInterfacorCountIncludingDeprecated(interfacorType); ++i) + { + CIdentifier identifier = OV_UndefinedIdentifier; + CIdentifier type = OV_UndefinedIdentifier; + CString name; + bool isDeprecated; + rExistingBox.getInterfacorIdentifier(interfacorType, i, identifier); + rExistingBox.getInterfacorType(interfacorType, i, type); + rExistingBox.getInterfacorName(interfacorType, i, name); + rExistingBox.getInterfacorDeprecatedStatus(interfacorType, i, isDeprecated); + this->addInterfacor(interfacorType, name, type, identifier, true); + this->setInterfacorDeprecatedStatus(interfacorType, i, isDeprecated); + + if (interfacorType == Setting) + { + CString value; + CString defaultValue; + bool isModifiable; + rExistingBox.getSettingValue(i, value); + rExistingBox.getSettingDefaultValue(i, defaultValue); + rExistingBox.getSettingMod(i, isModifiable); + this->setSettingDefaultValue(i, defaultValue); + this->setSettingValue(i, value); + this->setSettingMod(i, isModifiable); + if (isModifiable) { m_modifiableSettingIndexes.push_back(i); } + } } + } - //___________________________________________________________________// - // // - + CIdentifier id = rExistingBox.getNextAttributeIdentifier(OV_UndefinedIdentifier); + while (id != OV_UndefinedIdentifier) + { + this->addAttribute(id, rExistingBox.getAttributeValue(id)); + id = rExistingBox.getNextAttributeIdentifier(id); + } - bool addInterfacor(const EBoxInterfacorType interfacorType, const CString& newName, const CIdentifier& typeID, const CIdentifier& identifier, - const bool notify) override + CIdentifier streamTypeID = OV_UndefinedIdentifier; + while ((streamTypeID = this->getKernelContext().getTypeManager().getNextTypeIdentifier(streamTypeID)) != + OV_UndefinedIdentifier) + { + if (this->getKernelContext().getTypeManager().isStream(streamTypeID)) { - switch (interfacorType) - { - case Input: - case Output: - OV_ERROR_UNLESS_KRF(this->getTypeManager().isStream(typeID), - "While adding " << INTERFACOR_TYPE_TO_NAME.at(interfacorType) << " '" << newName << "' to box '" << this->getName() - << "', unknown stream type identifier " << typeID.str(), - ErrorType::BadArgument); - break; - case Setting: break; - default: break; - } - - const size_t position = size_t(m_interfacors[interfacorType].size()); - switch (interfacorType) - { - case Input: - case Output: - m_interfacors[interfacorType].push_back(std::make_shared<CInputOutput>(newName, typeID, identifier)); - break; - case Setting: - m_interfacors[interfacorType].push_back(std::make_shared<CSetting>(newName, typeID, identifier, "", false)); - break; - default: break; - } + //First check if it is a stream + if (rExistingBox.hasInputSupport(streamTypeID)) { this->addInputSupport(streamTypeID); } + if (rExistingBox.hasOutputSupport(streamTypeID)) { this->addOutputSupport(streamTypeID); } + } + } - if (identifier != OV_UndefinedIdentifier) { m_interfacorIDToIdx[interfacorType][identifier] = position; } + this->enableNotification(); - const CString uniqueName = this->getUnusedName(m_interfacorNameToIdx[interfacorType], newName); + this->notify(EBoxModification::Initialized); - m_interfacors[interfacorType][position]->m_Name = uniqueName; - m_interfacorNameToIdx[interfacorType][uniqueName] = position; + return true; + } - OV_ERROR_UNLESS_KRF(m_interfacorNameToIdx[interfacorType].size() == m_interfacors[interfacorType].size(), - "Box " << m_name << " has corrupted name map storage", ErrorType::BadResourceCreation); + //___________________________________________________________________// + // // - if (notify) - { - auto newCount = this->getInterfacorCount(interfacorType) - 1; - switch (interfacorType) - { - case Input: - this->notify(EBoxModification::InputAdded, newCount); - break; - case Output: - this->notify(EBoxModification::OutputAdded, newCount); - break; - case Setting: - this->notify(EBoxModification::SettingAdded, newCount); - break; - default: break; - } - } - return true; - } - bool removeInterfacor(const EBoxInterfacorType interfacorType, const size_t index, const bool shouldNotify = true) override - { - switch (interfacorType) - { - case Input: return this->removeInput(index, shouldNotify); - case Output: return this->removeOutput(index, shouldNotify); - case Setting: return this->removeSetting(index, shouldNotify); - default: return false; - } - } + bool addInterfacor(const EBoxInterfacorType interfacorType, const CString& newName, const CIdentifier& typeID, const CIdentifier& identifier, + const bool notify) override + { + switch (interfacorType) + { + case Input: + case Output: + OV_ERROR_UNLESS_KRF(this->getTypeManager().isStream(typeID), + "While adding " << INTERFACOR_TYPE_TO_NAME.at(interfacorType) << " '" << newName << "' to box '" << this->getName() + << "', unknown stream type identifier " << typeID.str(), + ErrorType::BadArgument); + break; + case Setting: break; + default: break; + } - size_t getInterfacorCount(const EBoxInterfacorType interfacorType) const override - { - auto interfacors = m_interfacors.at(interfacorType); - return size_t(std::count_if(interfacors.begin(), interfacors.end(), [](const std::shared_ptr<CInterfacor>& i) { return !i->m_Deprecated; })); - } + const size_t position = size_t(m_interfacors[interfacorType].size()); + switch (interfacorType) + { + case Input: + case Output: + m_interfacors[interfacorType].push_back(std::make_shared<CInputOutput>(newName, typeID, identifier)); + break; + case Setting: + m_interfacors[interfacorType].push_back(std::make_shared<CSetting>(newName, typeID, identifier, "", false)); + break; + default: break; + } - size_t getInterfacorCountIncludingDeprecated(const EBoxInterfacorType interfacorType) const override - { - return m_interfacors.at(interfacorType).size(); - } + if (identifier != OV_UndefinedIdentifier) { m_interfacorIDToIdx[interfacorType][identifier] = position; } - bool getInterfacorIdentifier(const EBoxInterfacorType interfacorType, const size_t index, CIdentifier& identifier) const override - { - identifier = OV_UndefinedIdentifier; - OV_ERROR_UNLESS_KRF(index < m_interfacors.at(interfacorType).size(), - INTERFACOR_TYPE_TO_NAME.at(interfacorType) << " index = [" << index << "] is out of range (max index = [" << m_interfacors. - at( - interfacorType).size() - 1 << "])", - ErrorType::OutOfBound); - - identifier = m_interfacors.at(interfacorType)[index]->m_ID; - return true; - } + const CString uniqueName = this->getUnusedName(m_interfacorNameToIdx[interfacorType], newName); - bool getInterfacorIndex(const EBoxInterfacorType interfacorType, const CIdentifier& identifier, size_t& index) const override - { - index = size_t(-1); - const auto it = m_interfacorIDToIdx.at(interfacorType).find(identifier); - OV_ERROR_UNLESS_KRF(it != m_interfacorIDToIdx.at(interfacorType).end(), - "Failed to find " << INTERFACOR_TYPE_TO_NAME.at(interfacorType) << " with identifier " << identifier.str(), - ErrorType::ResourceNotFound); - - index = it->second; - return true; - } + m_interfacors[interfacorType][position]->m_Name = uniqueName; + m_interfacorNameToIdx[interfacorType][uniqueName] = position; - bool getInterfacorIndex(const EBoxInterfacorType interfacorType, const CString& name, size_t& index) const override - { - index = size_t(-1); - const auto it = m_interfacorNameToIdx.at(interfacorType).find(name); - OV_ERROR_UNLESS_KRF(it != m_interfacorNameToIdx.at(interfacorType).end(), - "Failed to find " << INTERFACOR_TYPE_TO_NAME.at(interfacorType) << " with name " << name, ErrorType::ResourceNotFound); + OV_ERROR_UNLESS_KRF(m_interfacorNameToIdx[interfacorType].size() == m_interfacors[interfacorType].size(), + "Box " << m_name << " has corrupted name map storage", ErrorType::BadResourceCreation); - index = it->second; - return true; - } + if (notify) + { + auto newCount = this->getInterfacorCount(interfacorType) - 1; + switch (interfacorType) + { + case Input: + this->notify(EBoxModification::InputAdded, newCount); + break; + case Output: + this->notify(EBoxModification::OutputAdded, newCount); + break; + case Setting: + this->notify(EBoxModification::SettingAdded, newCount); + break; + default: break; + } + } + return true; + } + + bool removeInterfacor(const EBoxInterfacorType interfacorType, const size_t index, const bool shouldNotify = true) override + { + switch (interfacorType) + { + case Input: return this->removeInput(index, shouldNotify); + case Output: return this->removeOutput(index, shouldNotify); + case Setting: return this->removeSetting(index, shouldNotify); + default: return false; + } + } + + size_t getInterfacorCount(const EBoxInterfacorType interfacorType) const override + { + auto interfacors = m_interfacors.at(interfacorType); + return size_t(std::count_if(interfacors.begin(), interfacors.end(), [](const std::shared_ptr<CInterfacor>& i) { return !i->m_Deprecated; })); + } - bool getInterfacorType(const EBoxInterfacorType interfacorType, const size_t index, CIdentifier& typeID) const override - { - OV_ERROR_UNLESS_KRF(index < m_interfacors.at(interfacorType).size(), - INTERFACOR_TYPE_TO_NAME.at(interfacorType) << " index = [" << index << "] is out of range (max index = [" - << m_interfacors.at(interfacorType).size() - 1 << "])", ErrorType::OutOfBound); + size_t getInterfacorCountIncludingDeprecated(const EBoxInterfacorType interfacorType) const override { return m_interfacors.at(interfacorType).size(); } - typeID = m_interfacors.at(interfacorType)[index]->m_TypeID; - return true; - } + bool getInterfacorIdentifier(const EBoxInterfacorType interfacorType, const size_t index, CIdentifier& identifier) const override + { + identifier = OV_UndefinedIdentifier; + OV_ERROR_UNLESS_KRF(index < m_interfacors.at(interfacorType).size(), + INTERFACOR_TYPE_TO_NAME.at(interfacorType) << " index = [" << index << "] is out of range (max index = [" << m_interfacors. + at( + interfacorType).size() - 1 << "])", + ErrorType::OutOfBound); + + identifier = m_interfacors.at(interfacorType)[index]->m_ID; + return true; + } + + bool getInterfacorIndex(const EBoxInterfacorType interfacorType, const CIdentifier& identifier, size_t& index) const override + { + index = size_t(-1); + const auto it = m_interfacorIDToIdx.at(interfacorType).find(identifier); + OV_ERROR_UNLESS_KRF(it != m_interfacorIDToIdx.at(interfacorType).end(), + "Failed to find " << INTERFACOR_TYPE_TO_NAME.at(interfacorType) << " with identifier " << identifier.str(), + ErrorType::ResourceNotFound); - bool getInterfacorType(const EBoxInterfacorType interfacorType, const CIdentifier& identifier, CIdentifier& typeID) const override - { - const auto it = m_interfacorIDToIdx.at(interfacorType).find(identifier); - OV_ERROR_UNLESS_KRF(it != m_interfacorIDToIdx.at(interfacorType).end(), - "Failed to find " << INTERFACOR_TYPE_TO_NAME.at(interfacorType) << " with id " << identifier.str(), - ErrorType::ResourceNotFound); + index = it->second; + return true; + } - return this->getInterfacorType(interfacorType, it->second, typeID); - } + bool getInterfacorIndex(const EBoxInterfacorType interfacorType, const CString& name, size_t& index) const override + { + index = size_t(-1); + const auto it = m_interfacorNameToIdx.at(interfacorType).find(name); + OV_ERROR_UNLESS_KRF(it != m_interfacorNameToIdx.at(interfacorType).end(), + "Failed to find " << INTERFACOR_TYPE_TO_NAME.at(interfacorType) << " with name " << name, ErrorType::ResourceNotFound); - bool getInterfacorType(const EBoxInterfacorType interfacorType, const CString& name, CIdentifier& typeID) const override - { - const auto it = m_interfacorNameToIdx.at(interfacorType).find(name); - OV_ERROR_UNLESS_KRF(it != m_interfacorNameToIdx.at(interfacorType).end(), - "Failed to find " << INTERFACOR_TYPE_TO_NAME.at(interfacorType) << " with name " << name, ErrorType::ResourceNotFound); + index = it->second; + return true; + } - return this->getInterfacorType(interfacorType, it->second, typeID); - } + bool getInterfacorType(const EBoxInterfacorType interfacorType, const size_t index, CIdentifier& typeID) const override + { + OV_ERROR_UNLESS_KRF(index < m_interfacors.at(interfacorType).size(), + INTERFACOR_TYPE_TO_NAME.at(interfacorType) << " index = [" << index << "] is out of range (max index = [" + << m_interfacors.at(interfacorType).size() - 1 << "])", ErrorType::OutOfBound); + typeID = m_interfacors.at(interfacorType)[index]->m_TypeID; + return true; + } - bool getInterfacorName(const EBoxInterfacorType interfacorType, const size_t index, CString& name) const override - { - OV_ERROR_UNLESS_KRF(index < m_interfacors.at(interfacorType).size(), - INTERFACOR_TYPE_TO_NAME.at(interfacorType) << " index = [" << index << "] is out of range (max index = [" << m_interfacors. - at( - interfacorType).size() - 1 << "])", - ErrorType::OutOfBound); - - name = m_interfacors.at(interfacorType)[index]->m_Name; - return true; - } + bool getInterfacorType(const EBoxInterfacorType interfacorType, const CIdentifier& identifier, CIdentifier& typeID) const override + { + const auto it = m_interfacorIDToIdx.at(interfacorType).find(identifier); + OV_ERROR_UNLESS_KRF(it != m_interfacorIDToIdx.at(interfacorType).end(), + "Failed to find " << INTERFACOR_TYPE_TO_NAME.at(interfacorType) << " with id " << identifier.str(), + ErrorType::ResourceNotFound); - bool getInterfacorName(const EBoxInterfacorType interfacorType, const CIdentifier& identifier, CString& name) const override - { - const auto it = m_interfacorIDToIdx.at(interfacorType).find(identifier); - OV_ERROR_UNLESS_KRF(it != m_interfacorIDToIdx.at(interfacorType).end(), - "Failed to find " << INTERFACOR_TYPE_TO_NAME.at(interfacorType) << " with id " << identifier.str(), - ErrorType::ResourceNotFound); + return this->getInterfacorType(interfacorType, it->second, typeID); + } - return this->getInputName(it->second, name); - } + bool getInterfacorType(const EBoxInterfacorType interfacorType, const CString& name, CIdentifier& typeID) const override + { + const auto it = m_interfacorNameToIdx.at(interfacorType).find(name); + OV_ERROR_UNLESS_KRF(it != m_interfacorNameToIdx.at(interfacorType).end(), + "Failed to find " << INTERFACOR_TYPE_TO_NAME.at(interfacorType) << " with name " << name, ErrorType::ResourceNotFound); - bool getInterfacorDeprecatedStatus(const EBoxInterfacorType interfacorType, const size_t index, bool& value) const override - { - if (index >= m_interfacors.at(interfacorType).size()) { OV_WARNING_K("DUH"); } - OV_ERROR_UNLESS_KRF(index < m_interfacors.at(interfacorType).size(), - INTERFACOR_TYPE_TO_NAME.at(interfacorType) << " index = [" << index << "] is out of range (max index = [" << m_interfacors. - at( - interfacorType).size() - 1 << "])", - ErrorType::OutOfBound); - - value = m_interfacors.at(interfacorType)[index]->m_Deprecated; - return true; - } + return this->getInterfacorType(interfacorType, it->second, typeID); + } - bool getInterfacorDeprecatedStatus(const EBoxInterfacorType interfacorType, const CIdentifier& identifier, bool& value) const override - { - const auto it = m_interfacorIDToIdx.at(interfacorType).find(identifier); - OV_ERROR_UNLESS_KRF(it != m_interfacorIDToIdx.at(interfacorType).end(), - "Failed to find " << INTERFACOR_TYPE_TO_NAME.at(interfacorType) << " with id " << identifier.str(), - ErrorType::ResourceNotFound); - return this->getInterfacorDeprecatedStatus(interfacorType, it->second, value); - } + bool getInterfacorName(const EBoxInterfacorType interfacorType, const size_t index, CString& name) const override + { + OV_ERROR_UNLESS_KRF(index < m_interfacors.at(interfacorType).size(), + INTERFACOR_TYPE_TO_NAME.at(interfacorType) << " index = [" << index << "] is out of range (max index = [" << m_interfacors. + at( + interfacorType).size() - 1 << "])", + ErrorType::OutOfBound); - bool hasInterfacorWithIdentifier(const EBoxInterfacorType interfacorType, const CIdentifier& identifier) const override - { - return m_interfacorIDToIdx.at(interfacorType).find(identifier) != m_interfacorIDToIdx.at(interfacorType).end(); - } + name = m_interfacors.at(interfacorType)[index]->m_Name; + return true; + } - bool hasInterfacorWithNameAndType(const EBoxInterfacorType interfacorType, const CString& name, const CIdentifier& /*typeID*/) const override - { - return m_interfacorNameToIdx.at(interfacorType).find(name) != m_interfacorNameToIdx.at(interfacorType).end(); - } + bool getInterfacorName(const EBoxInterfacorType interfacorType, const CIdentifier& identifier, CString& name) const override + { + const auto it = m_interfacorIDToIdx.at(interfacorType).find(identifier); + OV_ERROR_UNLESS_KRF(it != m_interfacorIDToIdx.at(interfacorType).end(), + "Failed to find " << INTERFACOR_TYPE_TO_NAME.at(interfacorType) << " with id " << identifier.str(), + ErrorType::ResourceNotFound); - bool hasInterfacorWithType(const EBoxInterfacorType interfacorType, const size_t index, const CIdentifier& typeID) const override - { - if (index < this->getInterfacorCount(interfacorType)) - { - CIdentifier type = OV_UndefinedIdentifier; - this->getInterfacorType(interfacorType, index, type); - return (type == typeID); - } - return false; - } + return this->getInputName(it->second, name); + } + bool getInterfacorDeprecatedStatus(const EBoxInterfacorType interfacorType, const size_t index, bool& value) const override + { + if (index >= m_interfacors.at(interfacorType).size()) { OV_WARNING_K("DUH"); } + OV_ERROR_UNLESS_KRF(index < m_interfacors.at(interfacorType).size(), + INTERFACOR_TYPE_TO_NAME.at(interfacorType) << " index = [" << index << "] is out of range (max index = [" << m_interfacors. + at( + interfacorType).size() - 1 << "])", + ErrorType::OutOfBound); + + value = m_interfacors.at(interfacorType)[index]->m_Deprecated; + return true; + } + + bool getInterfacorDeprecatedStatus(const EBoxInterfacorType interfacorType, const CIdentifier& identifier, bool& value) const override + { + const auto it = m_interfacorIDToIdx.at(interfacorType).find(identifier); + OV_ERROR_UNLESS_KRF(it != m_interfacorIDToIdx.at(interfacorType).end(), + "Failed to find " << INTERFACOR_TYPE_TO_NAME.at(interfacorType) << " with id " << identifier.str(), + ErrorType::ResourceNotFound); - bool setInterfacorType(const EBoxInterfacorType interfacorType, const size_t index, const CIdentifier& typeID) override - { - switch (interfacorType) - { - case Input: - case Output: - OV_ERROR_UNLESS_KRF(this->getTypeManager().isStream(typeID), - "While changing box '" << this->getName() << "' " << INTERFACOR_TYPE_TO_NAME.at(interfacorType) << - " type, unknown stream type identifier " << typeID.str(), - ErrorType::BadArgument); - break; - case Setting: - break; - } + return this->getInterfacorDeprecatedStatus(interfacorType, it->second, value); + } - OV_ERROR_UNLESS_KRF(index < m_interfacors.at(interfacorType).size(), - INTERFACOR_TYPE_TO_NAME.at(interfacorType) << " index = [" << index << "] is out of range (max index = [" << m_interfacors. - at( - interfacorType).size() - 1 << "])", - ErrorType::OutOfBound); + bool hasInterfacorWithIdentifier(const EBoxInterfacorType interfacorType, const CIdentifier& identifier) const override + { + return m_interfacorIDToIdx.at(interfacorType).find(identifier) != m_interfacorIDToIdx.at(interfacorType).end(); + } - if (m_interfacors[interfacorType][index]->m_TypeID == typeID) { return true; } + bool hasInterfacorWithNameAndType(const EBoxInterfacorType interfacorType, const CString& name, const CIdentifier& /*typeID*/) const override + { + return m_interfacorNameToIdx.at(interfacorType).find(name) != m_interfacorNameToIdx.at(interfacorType).end(); + } - m_interfacors[interfacorType][index]->m_TypeID = typeID; + bool hasInterfacorWithType(const EBoxInterfacorType interfacorType, const size_t index, const CIdentifier& typeID) const override + { + if (index < this->getInterfacorCount(interfacorType)) + { + CIdentifier type = OV_UndefinedIdentifier; + this->getInterfacorType(interfacorType, index, type); + return (type == typeID); + } + return false; + } - switch (interfacorType) - { - case Input: - this->notify(EBoxModification::InputTypeChanged, index); - break; - case Output: - this->notify(EBoxModification::OutputTypeChanged, index); - break; - case Setting: - this->notify(EBoxModification::SettingTypeChanged, index); - this->notifySettingChange(SettingChange, int(index)); - break; - } - return true; - } + bool setInterfacorType(const EBoxInterfacorType interfacorType, const size_t index, const CIdentifier& typeID) override + { + switch (interfacorType) + { + case Input: + case Output: + OV_ERROR_UNLESS_KRF(this->getTypeManager().isStream(typeID), + "While changing box '" << this->getName() << "' " << INTERFACOR_TYPE_TO_NAME.at(interfacorType) << + " type, unknown stream type identifier " << typeID.str(), + ErrorType::BadArgument); + break; + case Setting: + break; + } - bool setInterfacorType(const EBoxInterfacorType interfacorType, const CIdentifier& identifier, const CIdentifier& typeID) override - { - const auto it = m_interfacorIDToIdx[interfacorType].find(identifier); - OV_ERROR_UNLESS_KRF(it != m_interfacorIDToIdx[interfacorType].end(), - "Failed to find " << INTERFACOR_TYPE_TO_NAME.at(interfacorType) << " with id " << identifier.str(), - ErrorType::ResourceNotFound); + OV_ERROR_UNLESS_KRF(index < m_interfacors.at(interfacorType).size(), + INTERFACOR_TYPE_TO_NAME.at(interfacorType) << " index = [" << index << "] is out of range (max index = [" << m_interfacors. + at( + interfacorType).size() - 1 << "])", + ErrorType::OutOfBound); - return this->setInterfacorType(interfacorType, it->second, typeID); - } + if (m_interfacors[interfacorType][index]->m_TypeID == typeID) { return true; } - bool setInterfacorType(const EBoxInterfacorType interfacorType, const CString& name, const CIdentifier& typeID) override - { - const auto it = m_interfacorNameToIdx[interfacorType].find(name); - OV_ERROR_UNLESS_KRF(it != m_interfacorNameToIdx[interfacorType].end(), - "Failed to find " << INTERFACOR_TYPE_TO_NAME.at(interfacorType) << " with name " << name, ErrorType::ResourceNotFound); + m_interfacors[interfacorType][index]->m_TypeID = typeID; - return this->setInterfacorType(interfacorType, it->second, typeID); - } + switch (interfacorType) + { + case Input: + this->notify(EBoxModification::InputTypeChanged, index); + break; + case Output: + this->notify(EBoxModification::OutputTypeChanged, index); + break; + case Setting: + this->notify(EBoxModification::SettingTypeChanged, index); + this->notifySettingChange(SettingChange, int(index)); + break; + } + + return true; + } + + bool setInterfacorType(const EBoxInterfacorType interfacorType, const CIdentifier& identifier, const CIdentifier& typeID) override + { + const auto it = m_interfacorIDToIdx[interfacorType].find(identifier); + OV_ERROR_UNLESS_KRF(it != m_interfacorIDToIdx[interfacorType].end(), + "Failed to find " << INTERFACOR_TYPE_TO_NAME.at(interfacorType) << " with id " << identifier.str(), + ErrorType::ResourceNotFound); + return this->setInterfacorType(interfacorType, it->second, typeID); + } - bool setInterfacorName(const EBoxInterfacorType interfacorType, const size_t index, const CString& newName) override - { - OV_ERROR_UNLESS_KRF(index < m_interfacors[interfacorType].size(), - INTERFACOR_TYPE_TO_NAME.at(interfacorType) << " index = [" << index << "] is out of range (max index = [" << m_interfacors[ - interfacorType].size() - 1 << "])", - ErrorType::OutOfBound); + bool setInterfacorType(const EBoxInterfacorType interfacorType, const CString& name, const CIdentifier& typeID) override + { + const auto it = m_interfacorNameToIdx[interfacorType].find(name); + OV_ERROR_UNLESS_KRF(it != m_interfacorNameToIdx[interfacorType].end(), + "Failed to find " << INTERFACOR_TYPE_TO_NAME.at(interfacorType) << " with name " << name, ErrorType::ResourceNotFound); - if (m_interfacors[interfacorType][index]->m_Name == newName) - { - // no change, don't bother notifying - return true; - } + return this->setInterfacorType(interfacorType, it->second, typeID); + } - // remove entry from name key map - const auto it = m_interfacorNameToIdx[interfacorType].find(m_interfacors[interfacorType][index]->m_Name); - OV_ERROR_UNLESS_KRF(it != m_interfacorNameToIdx[interfacorType].end(), - "Failed to find " << INTERFACOR_TYPE_TO_NAME.at(interfacorType) << " with name " << m_interfacors[interfacorType][index]-> - m_Name, - ErrorType::ResourceNotFound); - m_interfacorNameToIdx[interfacorType].erase(it); - // check for duplicated name key and update if necessary - const CString uniqueName = this->getUnusedName(m_interfacorNameToIdx[interfacorType], newName); - m_interfacorNameToIdx[interfacorType][uniqueName] = index; - m_interfacors[interfacorType][index]->m_Name = uniqueName; + bool setInterfacorName(const EBoxInterfacorType interfacorType, const size_t index, const CString& newName) override + { + OV_ERROR_UNLESS_KRF(index < m_interfacors[interfacorType].size(), + INTERFACOR_TYPE_TO_NAME.at(interfacorType) << " index = [" << index << "] is out of range (max index = [" << m_interfacors[ + interfacorType].size() - 1 << "])", + ErrorType::OutOfBound); - OV_ERROR_UNLESS_KRF(m_interfacorNameToIdx[interfacorType].size() == m_interfacors[interfacorType].size(), - "Box " << m_name << " has corrupted name map storage", ErrorType::BadResourceCreation); + if (m_interfacors[interfacorType][index]->m_Name == newName) + { + // no change, don't bother notifying + return true; + } + + // remove entry from name key map + const auto it = m_interfacorNameToIdx[interfacorType].find(m_interfacors[interfacorType][index]->m_Name); + OV_ERROR_UNLESS_KRF(it != m_interfacorNameToIdx[interfacorType].end(), + "Failed to find " << INTERFACOR_TYPE_TO_NAME.at(interfacorType) << " with name " << m_interfacors[interfacorType][index]-> + m_Name, + ErrorType::ResourceNotFound); + m_interfacorNameToIdx[interfacorType].erase(it); + + // check for duplicated name key and update if necessary + const CString uniqueName = this->getUnusedName(m_interfacorNameToIdx[interfacorType], newName); + m_interfacorNameToIdx[interfacorType][uniqueName] = index; + m_interfacors[interfacorType][index]->m_Name = uniqueName; + + OV_ERROR_UNLESS_KRF(m_interfacorNameToIdx[interfacorType].size() == m_interfacors[interfacorType].size(), + "Box " << m_name << " has corrupted name map storage", ErrorType::BadResourceCreation); + + switch (interfacorType) + { + case Input: + this->notify(EBoxModification::InputNameChanged, index); + break; + case Output: + this->notify(EBoxModification::OutputNameChanged, index); + break; + case Setting: + this->notify(EBoxModification::SettingNameChanged, index); + break; + } + + return true; + } + + bool setInterfacorName(const EBoxInterfacorType interfacorType, const CIdentifier& identifier, const CString& newName) override + { + const auto it = m_interfacorIDToIdx[interfacorType].find(identifier); + OV_ERROR_UNLESS_KRF(it != m_interfacorIDToIdx[interfacorType].end(), + "Failed to find " << INTERFACOR_TYPE_TO_NAME.at(interfacorType) << " with id " << identifier.str(), + ErrorType::ResourceNotFound); - switch (interfacorType) - { - case Input: - this->notify(EBoxModification::InputNameChanged, index); - break; - case Output: - this->notify(EBoxModification::OutputNameChanged, index); - break; - case Setting: - this->notify(EBoxModification::SettingNameChanged, index); - break; - } + return this->setInterfacorName(interfacorType, it->second, newName); + } - return true; - } + bool setInterfacorDeprecatedStatus(const EBoxInterfacorType interfacorType, const size_t index, const bool newValue) override + { + OV_ERROR_UNLESS_KRF(index < m_interfacors[interfacorType].size(), + INTERFACOR_TYPE_TO_NAME.at(interfacorType) << " index = [" << index << "] is out of range (max index = [" << m_interfacors[ + interfacorType].size() - 1 << "])", + ErrorType::OutOfBound); - bool setInterfacorName(const EBoxInterfacorType interfacorType, const CIdentifier& identifier, const CString& newName) override - { - const auto it = m_interfacorIDToIdx[interfacorType].find(identifier); - OV_ERROR_UNLESS_KRF(it != m_interfacorIDToIdx[interfacorType].end(), - "Failed to find " << INTERFACOR_TYPE_TO_NAME.at(interfacorType) << " with id " << identifier.str(), - ErrorType::ResourceNotFound); + m_interfacors[interfacorType][index]->m_Deprecated = newValue; - return this->setInterfacorName(interfacorType, it->second, newName); - } + return true; + } - bool setInterfacorDeprecatedStatus(const EBoxInterfacorType interfacorType, const size_t index, const bool newValue) override - { - OV_ERROR_UNLESS_KRF(index < m_interfacors[interfacorType].size(), - INTERFACOR_TYPE_TO_NAME.at(interfacorType) << " index = [" << index << "] is out of range (max index = [" << m_interfacors[ - interfacorType].size() - 1 << "])", - ErrorType::OutOfBound); + bool setInterfacorDeprecatedStatus(const EBoxInterfacorType interfacorType, const CIdentifier& identifier, const bool newValue) override + { + const auto it = m_interfacorIDToIdx[interfacorType].find(identifier); + OV_ERROR_UNLESS_KRF(it != m_interfacorIDToIdx[interfacorType].end(), + "Failed to find " << INTERFACOR_TYPE_TO_NAME.at(interfacorType) << " with id " << identifier.str(), + ErrorType::ResourceNotFound); - m_interfacors[interfacorType][index]->m_Deprecated = newValue; + return this->setInterfacorDeprecatedStatus(interfacorType, it->second, newValue); + } - return true; - } + //___________________________________________________________________// + // // - bool setInterfacorDeprecatedStatus(const EBoxInterfacorType interfacorType, const CIdentifier& identifier, const bool newValue) override - { - const auto it = m_interfacorIDToIdx[interfacorType].find(identifier); - OV_ERROR_UNLESS_KRF(it != m_interfacorIDToIdx[interfacorType].end(), - "Failed to find " << INTERFACOR_TYPE_TO_NAME.at(interfacorType) << " with id " << identifier.str(), - ErrorType::ResourceNotFound); + bool addInput(const CString& name, const CIdentifier& typeID, const CIdentifier& identifier, const bool notify) override + { + return this->addInterfacor(Input, name, typeID, identifier, notify); + } - return this->setInterfacorDeprecatedStatus(interfacorType, it->second, newValue); - } + bool removeInput(const size_t index, const bool notify = true) override + { + OV_ERROR_UNLESS_KRF(index < m_interfacors[Input].size(), + "Input index = [" << index << "] is out of range (max index = [" << m_interfacors[Input].size() - 1 << "])", + ErrorType::OutOfBound); + { + CIdentifier* listID = nullptr; + size_t nbElems = 0; + m_ownerScenario->getLinkIdentifierToBoxInputList(m_identifier, index, &listID, &nbElems); + for (size_t i = 0; i < nbElems; ++i) { m_ownerScenario->disconnect(listID[i]); } + m_ownerScenario->releaseIdentifierList(listID); + } + + // $$$ + // The way the links are removed here + // is not correct because they are all + // collected and then all removed. In case + // the box listener callback on box removal, + // the nextcoming links would potentially be + // invalid + std::vector<std::pair<std::pair<uint64_t, size_t>, std::pair<uint64_t, size_t>>> links; - //___________________________________________________________________// - // // + { + CIdentifier* listID = nullptr; + size_t nbElems = 0; + m_ownerScenario->getLinkIdentifierToBoxList(m_identifier, &listID, &nbElems); + for (size_t i = 0; i < nbElems; ++i) + { + CIdentifier id = listID[i]; + ILink* link = m_ownerScenario->getLinkDetails(id); + if (link->getTargetBoxInputIndex() > index) + { + links.push_back(std::make_pair(std::make_pair(link->getSourceBoxIdentifier().toUInteger(), link->getSourceBoxOutputIndex()), + std::make_pair(link->getTargetBoxIdentifier().toUInteger(), link->getTargetBoxInputIndex()))); - bool addInput(const CString& name, const CIdentifier& typeID, const CIdentifier& identifier, const bool notify) override - { - return this->addInterfacor(Input, name, typeID, identifier, notify); + if (m_ownerScenario->isLink(id)) { m_ownerScenario->disconnect(id); } + } } + m_ownerScenario->releaseIdentifierList(listID); + } - bool removeInput(const size_t index, const bool notify = true) override + // This reorganizes the parent's scenario links if this box is not actually a scenario itself + if (m_identifier != OV_UndefinedIdentifier) + { + std::vector<std::pair<size_t, std::pair<uint64_t, size_t>>> scenarioLinks; + for (size_t scenarioInputIdx = 0; scenarioInputIdx < m_ownerScenario->getInterfacorCount(Input); ++scenarioInputIdx) { - OV_ERROR_UNLESS_KRF(index < m_interfacors[Input].size(), - "Input index = [" << index << "] is out of range (max index = [" << m_interfacors[Input].size() - 1 << "])", - ErrorType::OutOfBound); - { - CIdentifier* listID = nullptr; - size_t nbElems = 0; - m_ownerScenario->getLinkIdentifierToBoxInputList(m_identifier, index, &listID, &nbElems); - for (size_t i = 0; i < nbElems; ++i) { m_ownerScenario->disconnect(listID[i]); } - m_ownerScenario->releaseIdentifierList(listID); - } - - // $$$ - // The way the links are removed here - // is not correct because they are all - // collected and then all removed. In case - // the box listener callback on box removal, - // the nextcoming links would potentially be - // invalid - std::vector<std::pair<std::pair<uint64_t, size_t>, std::pair<uint64_t, size_t>>> links; - + CIdentifier boxID = OV_UndefinedIdentifier; + size_t boxConnectorIdx = size_t(-1); + m_ownerScenario->getScenarioInputLink(scenarioInputIdx, boxID, boxConnectorIdx); + if (boxID == m_identifier) { - CIdentifier* listID = nullptr; - size_t nbElems = 0; - m_ownerScenario->getLinkIdentifierToBoxList(m_identifier, &listID, &nbElems); - for (size_t i = 0; i < nbElems; ++i) + if (boxConnectorIdx > index) { - CIdentifier id = listID[i]; - ILink* link = m_ownerScenario->getLinkDetails(id); - if (link->getTargetBoxInputIndex() > index) - { - links.push_back(std::make_pair(std::make_pair(link->getSourceBoxIdentifier().toUInteger(), link->getSourceBoxOutputIndex()), - std::make_pair(link->getTargetBoxIdentifier().toUInteger(), link->getTargetBoxInputIndex()))); - - if (m_ownerScenario->isLink(id)) { m_ownerScenario->disconnect(id); } - } + scenarioLinks.push_back(std::make_pair(scenarioInputIdx, std::make_pair(boxID.toUInteger(), boxConnectorIdx))); } - m_ownerScenario->releaseIdentifierList(listID); + if (boxConnectorIdx >= index) { m_ownerScenario->removeScenarioInputLink(scenarioInputIdx, boxID, boxConnectorIdx); } } + } - // This reorganizes the parent's scenario links if this box is not actually a scenario itself - if (m_identifier != OV_UndefinedIdentifier) - { - std::vector<std::pair<size_t, std::pair<uint64_t, size_t>>> scenarioLinks; - for (size_t scenarioInputIdx = 0; scenarioInputIdx < m_ownerScenario->getInterfacorCount(Input); ++scenarioInputIdx) - { - CIdentifier boxID = OV_UndefinedIdentifier; - size_t boxConnectorIdx = size_t(-1); - m_ownerScenario->getScenarioInputLink(scenarioInputIdx, boxID, boxConnectorIdx); - if (boxID == m_identifier) - { - if (boxConnectorIdx > index) - { - scenarioLinks.push_back(std::make_pair(scenarioInputIdx, std::make_pair(boxID.toUInteger(), boxConnectorIdx))); - } - if (boxConnectorIdx >= index) { m_ownerScenario->removeScenarioInputLink(scenarioInputIdx, boxID, boxConnectorIdx); } - } - } - - // Reconnects scenario links - for (const auto& link : scenarioLinks) { m_ownerScenario->setScenarioInputLink(link.first, link.second.first, link.second.second - 1); } - } + // Reconnects scenario links + for (const auto& link : scenarioLinks) { m_ownerScenario->setScenarioInputLink(link.first, link.second.first, link.second.second - 1); } + } - const CIdentifier toBeRemovedId = m_interfacors[Input][index]->m_ID; - CString toBeRemovedName = m_interfacors[Input][index]->m_Name; + const CIdentifier toBeRemovedId = m_interfacors[Input][index]->m_ID; + CString toBeRemovedName = m_interfacors[Input][index]->m_Name; - // Erases actual input - m_interfacors[Input].erase(m_interfacors[Input].begin() + index); + // Erases actual input + m_interfacors[Input].erase(m_interfacors[Input].begin() + index); - // Reconnects box links - for (const auto& link : links) - { - CIdentifier newId = OV_UndefinedIdentifier; - m_ownerScenario->connect(newId, link.first.first, link.first.second, link.second.first, link.second.second - 1, OV_UndefinedIdentifier); - } + // Reconnects box links + for (const auto& link : links) + { + CIdentifier newId = OV_UndefinedIdentifier; + m_ownerScenario->connect(newId, link.first.first, link.first.second, link.second.first, link.second.second - 1, OV_UndefinedIdentifier); + } + + // erase name key + const auto itName = m_interfacorNameToIdx[Input].find(toBeRemovedName); + OV_ERROR_UNLESS_KRF(itName != m_interfacorNameToIdx[Input].end(), "No input found with name " << toBeRemovedName, + ErrorType::ResourceNotFound); + m_interfacorNameToIdx[Input].erase(itName); + + // erase identifier key if defined + if (toBeRemovedId != OV_UndefinedIdentifier) + { + const auto itIdent = m_interfacorIDToIdx[Input].find(toBeRemovedId); + OV_ERROR_UNLESS_KRF(itIdent != m_interfacorIDToIdx[Input].end(), "No input found with id " << toBeRemovedId.str(), + ErrorType::ResourceNotFound); + m_interfacorIDToIdx[Input].erase(itIdent); + } - // erase name key - const auto itName = m_interfacorNameToIdx[Input].find(toBeRemovedName); - OV_ERROR_UNLESS_KRF(itName != m_interfacorNameToIdx[Input].end(), "No input found with name " << toBeRemovedName, - ErrorType::ResourceNotFound); - m_interfacorNameToIdx[Input].erase(itName); + if (notify) { this->notify(EBoxModification::InputRemoved, index); } - // erase identifier key if defined - if (toBeRemovedId != OV_UndefinedIdentifier) - { - const auto itIdent = m_interfacorIDToIdx[Input].find(toBeRemovedId); - OV_ERROR_UNLESS_KRF(itIdent != m_interfacorIDToIdx[Input].end(), "No input found with id " << toBeRemovedId.str(), - ErrorType::ResourceNotFound); - m_interfacorIDToIdx[Input].erase(itIdent); - } + return true; + } - if (notify) { this->notify(EBoxModification::InputRemoved, index); } + size_t getInputCount() const override { return this->getInterfacorCount(Input); } + bool getInputType(const size_t index, CIdentifier& typeID) const override { return this->getInterfacorType(Input, index, typeID); } + bool getInputName(const size_t index, CString& name) const override { return this->getInterfacorName(Input, index, name); } - return true; - } + bool getInputName(const CIdentifier& rInputIdentifier, CString& name) const { return this->getInterfacorName(Input, rInputIdentifier, name); } - size_t getInputCount() const override { return this->getInterfacorCount(Input); } - bool getInputType(const size_t index, CIdentifier& typeID) const override { return this->getInterfacorType(Input, index, typeID); } - bool getInputName(const size_t index, CString& name) const override { return this->getInterfacorName(Input, index, name); } + bool setInputType(const size_t index, const CIdentifier& typeID) override { return this->setInterfacorType(Input, index, typeID); } + bool setInputName(const size_t index, const CString& name) override { return this->setInterfacorName(Input, index, name); } - bool getInputName(const CIdentifier& rInputIdentifier, CString& name) const { return this->getInterfacorName(Input, rInputIdentifier, name); } + //___________________________________________________________________// + // // - bool setInputType(const size_t index, const CIdentifier& typeID) override { return this->setInterfacorType(Input, index, typeID); } - bool setInputName(const size_t index, const CString& name) override { return this->setInterfacorName(Input, index, name); } + bool addOutput(const CString& name, const CIdentifier& typeID, const CIdentifier& identifier, const bool notify) override + { + return this->addInterfacor(Output, name, typeID, identifier, notify); + } - //___________________________________________________________________// - // // + bool removeOutput(const size_t index, const bool notify = true) override + { + OV_ERROR_UNLESS_KRF(index < m_interfacors[Output].size(), + "Output index = [" << index << "] is out of range (max index = [" << size_t(m_interfacors[Output].size() - 1) << "])", + ErrorType::OutOfBound); - bool addOutput(const CString& name, const CIdentifier& typeID, const CIdentifier& identifier, const bool notify) override - { - return this->addInterfacor(Output, name, typeID, identifier, notify); - } + std::vector<std::pair<std::pair<uint64_t, size_t>, std::pair<uint64_t, size_t>>> links; - bool removeOutput(const size_t index, const bool notify = true) override - { - OV_ERROR_UNLESS_KRF(index < m_interfacors[Output].size(), - "Output index = [" << index << "] is out of range (max index = [" << size_t(m_interfacors[Output].size() - 1) << "])", - ErrorType::OutOfBound); + if (m_ownerScenario) + { + CIdentifier* listID = nullptr; + size_t nbElems = 0; - std::vector<std::pair<std::pair<uint64_t, size_t>, std::pair<uint64_t, size_t>>> links; + m_ownerScenario->getLinkIdentifierFromBoxOutputList(m_identifier, index, &listID, &nbElems); + for (size_t i = 0; i < nbElems; ++i) { m_ownerScenario->disconnect(listID[i]); } + m_ownerScenario->releaseIdentifierList(listID); - if (m_ownerScenario) + // $$$ + // The way the links are removed here is not correct because they are all collected and then all removed. In case + // the box listener callback on box removal, the nextcoming links would potentially be invalid + { + listID = nullptr; + nbElems = 0; + m_ownerScenario->getLinkIdentifierFromBoxOutputList(m_identifier, index, &listID, &nbElems); + for (size_t i = 0; i < nbElems; ++i) { - CIdentifier* listID = nullptr; - size_t nbElems = 0; - - m_ownerScenario->getLinkIdentifierFromBoxOutputList(m_identifier, index, &listID, &nbElems); - for (size_t i = 0; i < nbElems; ++i) { m_ownerScenario->disconnect(listID[i]); } - m_ownerScenario->releaseIdentifierList(listID); - - // $$$ - // The way the links are removed here is not correct because they are all collected and then all removed. In case - // the box listener callback on box removal, the nextcoming links would potentially be invalid + const CIdentifier& curID = listID[i]; + ILink* link = m_ownerScenario->getLinkDetails(curID); + if (link->getSourceBoxOutputIndex() > index) { - listID = nullptr; - nbElems = 0; - m_ownerScenario->getLinkIdentifierFromBoxOutputList(m_identifier, index, &listID, &nbElems); - for (size_t i = 0; i < nbElems; ++i) - { - const CIdentifier& curID = listID[i]; - ILink* link = m_ownerScenario->getLinkDetails(curID); - if (link->getSourceBoxOutputIndex() > index) - { - links.push_back(std::make_pair(std::make_pair(link->getSourceBoxIdentifier().toUInteger(), link->getSourceBoxOutputIndex()), - std::make_pair(link->getTargetBoxIdentifier().toUInteger(), link->getTargetBoxInputIndex()))); - if (m_ownerScenario->isLink(curID)) { m_ownerScenario->disconnect(curID); } - } - } - m_ownerScenario->releaseIdentifierList(listID); - } - - // This reorganizes the parent's scenario links if this box is not actually a scenario - if (m_identifier != OV_UndefinedIdentifier) - { - std::vector<std::pair<size_t, std::pair<uint64_t, size_t>>> scenarioLinks; - for (size_t scenarioOutputIdx = 0; scenarioOutputIdx < m_ownerScenario->getOutputCount(); ++scenarioOutputIdx) - { - CIdentifier boxID = OV_UndefinedIdentifier; - size_t boxConnectorIdx = size_t(-1); - m_ownerScenario->getScenarioOutputLink(scenarioOutputIdx, boxID, boxConnectorIdx); - if (boxID == m_identifier) - { - if (boxConnectorIdx > index) - { - scenarioLinks.push_back(std::make_pair(scenarioOutputIdx, std::make_pair(boxID.toUInteger(), boxConnectorIdx))); - } - if (boxConnectorIdx >= index) { m_ownerScenario->removeScenarioOutputLink(scenarioOutputIdx, boxID, boxConnectorIdx); } - } - } - - // Reconnects scenario links - for (const auto& link : scenarioLinks) - { - m_ownerScenario->setScenarioOutputLink(link.first, link.second.first, link.second.second - 1); - } + links.push_back(std::make_pair(std::make_pair(link->getSourceBoxIdentifier().toUInteger(), link->getSourceBoxOutputIndex()), + std::make_pair(link->getTargetBoxIdentifier().toUInteger(), link->getTargetBoxInputIndex()))); + if (m_ownerScenario->isLink(curID)) { m_ownerScenario->disconnect(curID); } } } - const CIdentifier toBeRemovedId = m_interfacors.at(Output)[index]->m_ID; - CString toBeRemovedName = m_interfacors.at(Output)[index]->m_Name; - - // Erases actual output - m_interfacors[Output].erase(m_interfacors.at(Output).begin() + index); + m_ownerScenario->releaseIdentifierList(listID); + } - // Reconnects box links - if (m_ownerScenario) + // This reorganizes the parent's scenario links if this box is not actually a scenario + if (m_identifier != OV_UndefinedIdentifier) + { + std::vector<std::pair<size_t, std::pair<uint64_t, size_t>>> scenarioLinks; + for (size_t scenarioOutputIdx = 0; scenarioOutputIdx < m_ownerScenario->getOutputCount(); ++scenarioOutputIdx) { - for (const auto& link : links) + CIdentifier boxID = OV_UndefinedIdentifier; + size_t boxConnectorIdx = size_t(-1); + m_ownerScenario->getScenarioOutputLink(scenarioOutputIdx, boxID, boxConnectorIdx); + if (boxID == m_identifier) { - CIdentifier newId = OV_UndefinedIdentifier; - m_ownerScenario->connect(newId, link.first.first, link.first.second - 1, link.second.first, link.second.second, - OV_UndefinedIdentifier); + if (boxConnectorIdx > index) + { + scenarioLinks.push_back(std::make_pair(scenarioOutputIdx, std::make_pair(boxID.toUInteger(), boxConnectorIdx))); + } + if (boxConnectorIdx >= index) { m_ownerScenario->removeScenarioOutputLink(scenarioOutputIdx, boxID, boxConnectorIdx); } } } - - // erase name key - const auto itName = m_interfacorNameToIdx.at(Output).find(toBeRemovedName); - OV_ERROR_UNLESS_KRF(itName != m_interfacorNameToIdx.at(Output).end(), "No output found with name " << toBeRemovedName, - ErrorType::ResourceNotFound); - m_interfacorNameToIdx.at(Output).erase(itName); - - // erase identifier key if defined - if (toBeRemovedId != OV_UndefinedIdentifier) - { - const auto itIdent = m_interfacorIDToIdx.at(Output).find(toBeRemovedId); - OV_ERROR_UNLESS_KRF(itIdent != m_interfacorIDToIdx.at(Output).end(), "No output found with id " << toBeRemovedId.str(), - ErrorType::ResourceNotFound); - - m_interfacorIDToIdx.at(Output).erase(itIdent); - } - - if (notify) { this->notify(EBoxModification::OutputRemoved, index); } - - return true; + // Reconnects scenario links + for (const auto& link : scenarioLinks) { m_ownerScenario->setScenarioOutputLink(link.first, link.second.first, link.second.second - 1); } } + } + const CIdentifier toBeRemovedId = m_interfacors.at(Output)[index]->m_ID; + CString toBeRemovedName = m_interfacors.at(Output)[index]->m_Name; - size_t getOutputCount() const override { return this->getInterfacorCount(Output); } - bool getOutputType(const size_t index, CIdentifier& typeID) const override { return this->getInterfacorType(Output, index, typeID); } - bool getOutputName(const size_t index, CString& name) const override { return this->getInterfacorName(Output, index, name); } - bool setOutputType(const size_t index, const CIdentifier& typeID) override { return this->setInterfacorType(Output, index, typeID); } - bool setOutputName(const size_t index, const CString& name) override { return this->setInterfacorName(Output, index, name); } + // Erases actual output + m_interfacors[Output].erase(m_interfacors.at(Output).begin() + index); - bool addInterfacorTypeSupport(const EBoxInterfacorType interfacorType, const CIdentifier& typeID) override + // Reconnects box links + if (m_ownerScenario) + { + for (const auto& link : links) { - if (interfacorType == Input) { m_supportInputTypes.push_back(typeID); } - else if (interfacorType == Output) { m_supportOutputTypes.push_back(typeID); } - - return false; + CIdentifier newId = OV_UndefinedIdentifier; + m_ownerScenario->connect(newId, link.first.first, link.first.second - 1, link.second.first, link.second.second, + OV_UndefinedIdentifier); } + } - bool hasInterfacorTypeSupport(const EBoxInterfacorType interfacorType, const CIdentifier& typeID) const override - { - if (interfacorType == Input) - { - if (m_supportInputTypes.empty()) { return true; } - for (size_t i = 0; i < m_supportInputTypes.size(); ++i) { if (m_supportInputTypes[i] == typeID) { return true; } } - } - else if (interfacorType == Output) - { - //If there is no type specify, we allow all - if (m_supportOutputTypes.empty()) { return true; } + // erase name key + const auto itName = m_interfacorNameToIdx.at(Output).find(toBeRemovedName); + OV_ERROR_UNLESS_KRF(itName != m_interfacorNameToIdx.at(Output).end(), "No output found with name " << toBeRemovedName, + ErrorType::ResourceNotFound); + m_interfacorNameToIdx.at(Output).erase(itName); - for (size_t i = 0; i < m_supportOutputTypes.size(); ++i) { if (m_supportOutputTypes[i] == typeID) { return true; } } - } - else - { - // Settings are always all supported, in a way - return true; - } + // erase identifier key if defined + if (toBeRemovedId != OV_UndefinedIdentifier) + { + const auto itIdent = m_interfacorIDToIdx.at(Output).find(toBeRemovedId); + OV_ERROR_UNLESS_KRF(itIdent != m_interfacorIDToIdx.at(Output).end(), "No output found with id " << toBeRemovedId.str(), + ErrorType::ResourceNotFound); - return false; - } + m_interfacorIDToIdx.at(Output).erase(itIdent); + } - bool addInputSupport(const CIdentifier& typeID) override { return this->addInterfacorTypeSupport(Input, typeID); } - bool hasInputSupport(const CIdentifier& typeID) const override { return this->hasInterfacorTypeSupport(Input, typeID); } - bool addOutputSupport(const CIdentifier& typeID) override { return this->addInterfacorTypeSupport(Output, typeID); } - bool hasOutputSupport(const CIdentifier& typeID) const override { return this->hasInterfacorTypeSupport(Output, typeID); } + if (notify) { this->notify(EBoxModification::OutputRemoved, index); } - bool setSupportTypeFromAlgorithmIdentifier(const CIdentifier& typeID) override - { - const Plugins::IPluginObjectDesc* pluginObjectDesc = this->getKernelContext().getPluginManager().getPluginObjectDescCreating(typeID); - const Plugins::IBoxAlgorithmDesc* boxAlgorithmDesc = dynamic_cast<const Plugins::IBoxAlgorithmDesc*>(pluginObjectDesc); + return true; + } - OV_ERROR_UNLESS_KRF(boxAlgorithmDesc, "Tried to initialize with an unregistered algorithm", ErrorType::Internal); + size_t getOutputCount() const override { return this->getInterfacorCount(Output); } + bool getOutputType(const size_t index, CIdentifier& typeID) const override { return this->getInterfacorType(Output, index, typeID); } + bool getOutputName(const size_t index, CString& name) const override { return this->getInterfacorName(Output, index, name); } + bool setOutputType(const size_t index, const CIdentifier& typeID) override { return this->setInterfacorType(Output, index, typeID); } + bool setOutputName(const size_t index, const CString& name) override { return this->setInterfacorName(Output, index, name); } - //We use the neutralized version of CBoxProto to just initialize the stream restriction mecanism - CBoxProtoRestriction oTempProto(this->getKernelContext(), *this); - boxAlgorithmDesc->getBoxPrototype(oTempProto); - return true; - } + bool addInterfacorTypeSupport(const EBoxInterfacorType interfacorType, const CIdentifier& typeID) override + { + if (interfacorType == Input) { m_supportInputTypes.push_back(typeID); } + else if (interfacorType == Output) { m_supportOutputTypes.push_back(typeID); } - std::vector<CIdentifier> getInputSupportTypes() const override { return m_supportInputTypes; } - std::vector<CIdentifier> getOutputSupportTypes() const override { return m_supportOutputTypes; } - void clearOutputSupportTypes() override { m_supportOutputTypes.clear(); } - void clearInputSupportTypes() override { m_supportInputTypes.clear(); } + return false; + } - private: - CIdentifier getUnusedInterfacorIdentifier(const EBoxInterfacorType interfacorType, - const CIdentifier& suggestedIdentifier = OV_UndefinedIdentifier) const - { - uint64_t identifier = CIdentifier::random().toUInteger(); - if (suggestedIdentifier != OV_UndefinedIdentifier) { identifier = suggestedIdentifier.toUInteger(); } - - CIdentifier resultIdentifier = OV_UndefinedIdentifier; - std::map<CIdentifier, size_t>::const_iterator it; - do - { - resultIdentifier = CIdentifier(identifier); - it = m_interfacorIDToIdx.at(interfacorType).find(resultIdentifier); - identifier++; - } while (it != m_interfacorIDToIdx.at(interfacorType).end() || resultIdentifier == OV_UndefinedIdentifier); - return resultIdentifier; - } + bool hasInterfacorTypeSupport(const EBoxInterfacorType interfacorType, const CIdentifier& typeID) const override + { + if (interfacorType == Input) + { + if (m_supportInputTypes.empty()) { return true; } - public: + for (size_t i = 0; i < m_supportInputTypes.size(); ++i) { if (m_supportInputTypes[i] == typeID) { return true; } } + } + else if (interfacorType == Output) + { + //If there is no type specify, we allow all + if (m_supportOutputTypes.empty()) { return true; } - CIdentifier getUnusedSettingIdentifier(const CIdentifier& /*suggestedID*/ = OV_UndefinedIdentifier) const - { - return this->getUnusedInterfacorIdentifier(Setting); - } + for (size_t i = 0; i < m_supportOutputTypes.size(); ++i) { if (m_supportOutputTypes[i] == typeID) { return true; } } + } + else + { + // Settings are always all supported, in a way + return true; + } - CIdentifier getUnusedInputIdentifier(const CIdentifier& /*suggestedID*/ = OV_UndefinedIdentifier) const - { - return this->getUnusedInterfacorIdentifier(Input); - } + return false; + } - CIdentifier getUnusedOutputIdentifier(const CIdentifier& /*suggestedID*/ = OV_UndefinedIdentifier) const - { - return this->getUnusedInterfacorIdentifier(Output); - } + bool addInputSupport(const CIdentifier& typeID) override { return this->addInterfacorTypeSupport(Input, typeID); } + bool hasInputSupport(const CIdentifier& typeID) const override { return this->hasInterfacorTypeSupport(Input, typeID); } + bool addOutputSupport(const CIdentifier& typeID) override { return this->addInterfacorTypeSupport(Output, typeID); } + bool hasOutputSupport(const CIdentifier& typeID) const override { return this->hasInterfacorTypeSupport(Output, typeID); } - bool addSetting(const CString& name, const CIdentifier& typeID, const CString& sDefaultValue, const size_t index, - const bool bModifiability, const CIdentifier& identifier, const bool notify) override - { - CString value(sDefaultValue); - if (this->getTypeManager().isEnumeration(typeID)) - { - if (this->getTypeManager().getEnumerationEntryValueFromName(typeID, sDefaultValue) == OV_UndefinedIdentifier) - { - if (this->getTypeManager().getEnumerationEntryCount(typeID) != 0) - { - // get value to the first enum entry - // and eventually correct this after - uint64_t v = 0; - this->getTypeManager().getEnumerationEntry(typeID, 0, value, v); - - // Find if the default value string actually is an identifier, otherwise just keep the zero index name as default. - CIdentifier defaultValueID = OV_UndefinedIdentifier; - defaultValueID.fromString(sDefaultValue); - - // Finally, if it is an identifier, then a name should be found - // from the type manager ! Otherwise value is left to the default. - const CString candidateValue = this->getTypeManager().getEnumerationEntryNameFromValue(typeID, defaultValueID.toUInteger()); - if (candidateValue != CString("")) { value = candidateValue; } - } - } - } + bool setSupportTypeFromAlgorithmIdentifier(const CIdentifier& typeID) override + { + const Plugins::IPluginObjectDesc* pluginObjectDesc = this->getKernelContext().getPluginManager().getPluginObjectDescCreating(typeID); + const Plugins::IBoxAlgorithmDesc* boxAlgorithmDesc = dynamic_cast<const Plugins::IBoxAlgorithmDesc*>(pluginObjectDesc); - CSetting s; - s.m_Name = name; - s.m_TypeID = typeID; - s.m_DefaultValue = value; - s.m_Value = value; - s.m_Mod = bModifiability; - s.m_ID = identifier; + OV_ERROR_UNLESS_KRF(boxAlgorithmDesc, "Tried to initialize with an unregistered algorithm", ErrorType::Internal); - const size_t idx = index; + //We use the neutralized version of CBoxProto to just initialize the stream restriction mecanism + CBoxProtoRestriction oTempProto(this->getKernelContext(), *this); + boxAlgorithmDesc->getBoxPrototype(oTempProto); + return true; + } + std::vector<CIdentifier> getInputSupportTypes() const override { return m_supportInputTypes; } + std::vector<CIdentifier> getOutputSupportTypes() const override { return m_supportOutputTypes; } + void clearOutputSupportTypes() override { m_supportOutputTypes.clear(); } + void clearInputSupportTypes() override { m_supportInputTypes.clear(); } - size_t insertLocation; +private: + CIdentifier getUnusedInterfacorIdentifier(const EBoxInterfacorType interfacorType, + const CIdentifier& suggestedIdentifier = OV_UndefinedIdentifier) const + { + uint64_t identifier = CIdentifier::random().toUInteger(); + if (suggestedIdentifier != OV_UndefinedIdentifier) { identifier = suggestedIdentifier.toUInteger(); } - if (index == size_t(-1) || index == size_t(m_interfacors[Setting].size())) - { - m_interfacors[Setting].push_back(std::make_shared<CSetting>(s)); - insertLocation = (size_t(m_interfacors[Setting].size())) - 1; - } - else - { - OV_ERROR_UNLESS_KRF(index <= m_interfacors[Setting].size(), - "Tried to push '" << name << "' to slot " << index << " with the array size being " << m_interfacors[Setting].size(), - ErrorType::OutOfBound); - - auto it = m_interfacors[Setting].begin(); - it += idx; - m_interfacors[Setting].insert(it, std::make_shared<CSetting>(s)); - insertLocation = index; - } + CIdentifier resultIdentifier = OV_UndefinedIdentifier; + std::map<CIdentifier, size_t>::const_iterator it; + do + { + resultIdentifier = CIdentifier(identifier); + it = m_interfacorIDToIdx.at(interfacorType).find(resultIdentifier); + identifier++; + } while (it != m_interfacorIDToIdx.at(interfacorType).end() || resultIdentifier == OV_UndefinedIdentifier); + return resultIdentifier; + } - if (s.m_ID != OV_UndefinedIdentifier) - { - // add access by CIdentifier key if defined so that size differs from m_settings - m_interfacorIDToIdx[Setting][s.m_ID] = insertLocation; - } - // add access by name key (always done so that synchronized with m_settings - const CString newName = this->getUnusedName(m_interfacorNameToIdx.at(Setting), s.m_Name); - m_interfacors[Setting][insertLocation]->m_Name = newName; - m_interfacorNameToIdx[Setting][newName] = insertLocation; +public: - OV_ERROR_UNLESS_KRF(m_interfacorNameToIdx.at(Setting).size() == m_interfacors[Setting].size(), - "Box " << m_name << " has corrupted name map storage", ErrorType::BadResourceCreation); + CIdentifier getUnusedSettingIdentifier(const CIdentifier& /*suggestedID*/ = OV_UndefinedIdentifier) const + { + return this->getUnusedInterfacorIdentifier(Setting); + } - //if this setting is modifiable, keep its index - if (bModifiability) { m_modifiableSettingIndexes.push_back(idx); } + CIdentifier getUnusedInputIdentifier(const CIdentifier& /*suggestedID*/ = OV_UndefinedIdentifier) const + { + return this->getUnusedInterfacorIdentifier(Input); + } - this->getLogManager() << LogLevel_Debug - << "Pushed '" << m_interfacors.at(Setting)[insertLocation]->m_Name << "' : '" - << std::static_pointer_cast<CSetting>(m_interfacors.at(Setting)[insertLocation])->m_Value - << "' to slot " << insertLocation << " with the array size now " << m_interfacors.at(Setting).size() << "\n"; + CIdentifier getUnusedOutputIdentifier(const CIdentifier& /*suggestedID*/ = OV_UndefinedIdentifier) const + { + return this->getUnusedInterfacorIdentifier(Output); + } - if (notify) + bool addSetting(const CString& name, const CIdentifier& typeID, const CString& sDefaultValue, const size_t index, + const bool bModifiability, const CIdentifier& identifier, const bool notify) override + { + CString value(sDefaultValue); + if (this->getTypeManager().isEnumeration(typeID)) + { + if (this->getTypeManager().getEnumerationEntryValueFromName(typeID, sDefaultValue) == OV_UndefinedIdentifier) + { + if (this->getTypeManager().getEnumerationEntryCount(typeID) != 0) { - this->notify(EBoxModification::SettingAdded, insertLocation); - this->notifySettingChange(SettingAdd, int(insertLocation)); + // get value to the first enum entry + // and eventually correct this after + uint64_t v = 0; + this->getTypeManager().getEnumerationEntry(typeID, 0, value, v); + + // Find if the default value string actually is an identifier, otherwise just keep the zero index name as default. + CIdentifier defaultValueID = OV_UndefinedIdentifier; + defaultValueID.fromString(sDefaultValue); + + // Finally, if it is an identifier, then a name should be found + // from the type manager ! Otherwise value is left to the default. + const CString candidateValue = this->getTypeManager().getEnumerationEntryNameFromValue(typeID, defaultValueID.toUInteger()); + if (candidateValue != CString("")) { value = candidateValue; } } - - return true; } + } - bool removeSetting(const size_t index, const bool notify = true) override - { - auto it = m_interfacors[Setting].begin() + index; - OV_ERROR_UNLESS_KRF(it != m_interfacors[Setting].end(), "No setting found at index " << index, ErrorType::ResourceNotFound); + CSetting s; + s.m_Name = name; + s.m_TypeID = typeID; + s.m_DefaultValue = value; + s.m_Value = value; + s.m_Mod = bModifiability; + s.m_ID = identifier; - const CIdentifier toBeRemovedId = m_interfacors[Setting][index]->m_ID; - CString toBeRemovedName = m_interfacors[Setting][index]->m_Name; + const size_t idx = index; - it = m_interfacors[Setting].erase(it); - //update the modifiable setting indexes - for (auto it2 = m_modifiableSettingIndexes.begin(); it2 != m_modifiableSettingIndexes.end();) - { - if (*it2 == index) { it2 = m_modifiableSettingIndexes.erase(it2); } - else if (*it2 > index) - { - *it2 -= 1; - ++it2; - } - } + size_t insertLocation; - // erase name key - const auto itName = m_interfacorNameToIdx.at(Setting).find(toBeRemovedName); - OV_ERROR_UNLESS_KRF(itName != m_interfacorNameToIdx.at(Setting).end(), "No setting found with name " << toBeRemovedName, - ErrorType::ResourceNotFound); - m_interfacorNameToIdx.at(Setting).erase(itName); + if (index == size_t(-1) || index == size_t(m_interfacors[Setting].size())) + { + m_interfacors[Setting].push_back(std::make_shared<CSetting>(s)); + insertLocation = (size_t(m_interfacors[Setting].size())) - 1; + } + else + { + OV_ERROR_UNLESS_KRF(index <= m_interfacors[Setting].size(), + "Tried to push '" << name << "' to slot " << index << " with the array size being " << m_interfacors[Setting].size(), + ErrorType::OutOfBound); - // erase identifier key if defined - if (toBeRemovedId != OV_UndefinedIdentifier) - { - const auto itIdent = m_interfacorIDToIdx.at(Setting).find(toBeRemovedId); - OV_ERROR_UNLESS_KRF(itIdent != m_interfacorIDToIdx.at(Setting).end(), "No setting found with id " << toBeRemovedId.str(), - ErrorType::ResourceNotFound); - m_interfacorIDToIdx.at(Setting).erase(itIdent); - } + auto it = m_interfacors[Setting].begin(); + it += idx; + m_interfacors[Setting].insert(it, std::make_shared<CSetting>(s)); + insertLocation = index; + } - if (notify) - { - this->notify(EBoxModification::SettingRemoved, index); - this->notifySettingChange(SettingDelete, int(index)); - } + if (s.m_ID != OV_UndefinedIdentifier) + { + // add access by CIdentifier key if defined so that size differs from m_settings + m_interfacorIDToIdx[Setting][s.m_ID] = insertLocation; + } + // add access by name key (always done so that synchronized with m_settings + const CString newName = this->getUnusedName(m_interfacorNameToIdx.at(Setting), s.m_Name); + m_interfacors[Setting][insertLocation]->m_Name = newName; + m_interfacorNameToIdx[Setting][newName] = insertLocation; + + OV_ERROR_UNLESS_KRF(m_interfacorNameToIdx.at(Setting).size() == m_interfacors[Setting].size(), + "Box " << m_name << " has corrupted name map storage", ErrorType::BadResourceCreation); + + //if this setting is modifiable, keep its index + if (bModifiability) { m_modifiableSettingIndexes.push_back(idx); } + + this->getLogManager() << LogLevel_Debug + << "Pushed '" << m_interfacors.at(Setting)[insertLocation]->m_Name << "' : '" + << std::static_pointer_cast<CSetting>(m_interfacors.at(Setting)[insertLocation])->m_Value + << "' to slot " << insertLocation << " with the array size now " << m_interfacors.at(Setting).size() << "\n"; + + if (notify) + { + this->notify(EBoxModification::SettingAdded, insertLocation); + this->notifySettingChange(SettingAdd, int(insertLocation)); + } - return true; - } + return true; + } + + bool removeSetting(const size_t index, const bool notify = true) override + { + auto it = m_interfacors[Setting].begin() + index; + OV_ERROR_UNLESS_KRF(it != m_interfacors[Setting].end(), "No setting found at index " << index, ErrorType::ResourceNotFound); - size_t getSettingCount() const override { return this->getInterfacorCount(Setting); } + const CIdentifier toBeRemovedId = m_interfacors[Setting][index]->m_ID; + CString toBeRemovedName = m_interfacors[Setting][index]->m_Name; - bool hasSettingWithName(const CString& name) const override + it = m_interfacors[Setting].erase(it); + + //update the modifiable setting indexes + for (auto it2 = m_modifiableSettingIndexes.begin(); it2 != m_modifiableSettingIndexes.end();) + { + if (*it2 == index) { it2 = m_modifiableSettingIndexes.erase(it2); } + else if (*it2 > index) { - return m_interfacorNameToIdx.at(Setting).find(name) != m_interfacorNameToIdx.at(Setting).end(); + *it2 -= 1; + ++it2; } + } - bool getSettingType(const size_t index, CIdentifier& typeID) const override { return this->getInterfacorType(Setting, index, typeID); } + // erase name key + const auto itName = m_interfacorNameToIdx.at(Setting).find(toBeRemovedName); + OV_ERROR_UNLESS_KRF(itName != m_interfacorNameToIdx.at(Setting).end(), "No setting found with name " << toBeRemovedName, + ErrorType::ResourceNotFound); + m_interfacorNameToIdx.at(Setting).erase(itName); - bool getSettingName(const size_t index, CString& name) const override { return this->getInterfacorName(Setting, index, name); } + // erase identifier key if defined + if (toBeRemovedId != OV_UndefinedIdentifier) + { + const auto itIdent = m_interfacorIDToIdx.at(Setting).find(toBeRemovedId); + OV_ERROR_UNLESS_KRF(itIdent != m_interfacorIDToIdx.at(Setting).end(), "No setting found with id " << toBeRemovedId.str(), + ErrorType::ResourceNotFound); + m_interfacorIDToIdx.at(Setting).erase(itIdent); + } - bool getSettingDefaultValue(const size_t index, CString& defaultValue) const override - { - OV_ERROR_UNLESS_KRF(index < m_interfacors.at(Setting).size(), - "Setting index = [" << index << "] is out of range (max index = [" << m_interfacors.at(Setting).size() - 1 << "])", - ErrorType::OutOfBound); + if (notify) + { + this->notify(EBoxModification::SettingRemoved, index); + this->notifySettingChange(SettingDelete, int(index)); + } - defaultValue = std::static_pointer_cast<CSetting>(m_interfacors.at(Setting)[index])->m_DefaultValue; - return true; - } + return true; + } - bool getSettingDefaultValue(const CIdentifier& identifier, CString& defaultValue) const override - { - const auto it = m_interfacorIDToIdx.at(Setting).find(identifier); - OV_ERROR_UNLESS_KRF(it != m_interfacorIDToIdx.at(Setting).end(), "Failed to find setting with id " << identifier.str(), - ErrorType::ResourceNotFound); + size_t getSettingCount() const override { return this->getInterfacorCount(Setting); } - return this->getSettingDefaultValue(it->second, defaultValue); - } + bool hasSettingWithName(const CString& name) const override + { + return m_interfacorNameToIdx.at(Setting).find(name) != m_interfacorNameToIdx.at(Setting).end(); + } - bool getSettingDefaultValue(const CString& name, CString& defaultValue) const override - { - const auto it = m_interfacorNameToIdx.at(Setting).find(name); - OV_ERROR_UNLESS_KRF(it != m_interfacorNameToIdx.at(Setting).end(), "Failed to find setting with name " << name, - ErrorType::ResourceNotFound); + bool getSettingType(const size_t index, CIdentifier& typeID) const override { return this->getInterfacorType(Setting, index, typeID); } - return this->getSettingDefaultValue(it->second, defaultValue); - } + bool getSettingName(const size_t index, CString& name) const override { return this->getInterfacorName(Setting, index, name); } - bool getSettingValue(const size_t index, CString& value) const override - { - OV_ERROR_UNLESS_KRF(index < m_interfacors.at(Setting).size(), - "Setting index = [" << index << "] is out of range (max index = [" << m_interfacors.at(Setting).size() - 1 << "])", - ErrorType::OutOfBound); + bool getSettingDefaultValue(const size_t index, CString& defaultValue) const override + { + OV_ERROR_UNLESS_KRF(index < m_interfacors.at(Setting).size(), + "Setting index = [" << index << "] is out of range (max index = [" << m_interfacors.at(Setting).size() - 1 << "])", + ErrorType::OutOfBound); - value = std::static_pointer_cast<CSetting>(m_interfacors.at(Setting)[index])->m_Value; - return true; - } + defaultValue = std::static_pointer_cast<CSetting>(m_interfacors.at(Setting)[index])->m_DefaultValue; + return true; + } - bool getSettingValue(const CIdentifier& identifier, CString& value) const override - { - const auto it = m_interfacorIDToIdx.at(Setting).find(identifier); - OV_ERROR_UNLESS_KRF(it != m_interfacorIDToIdx.at(Setting).end(), "Failed to find setting with id " << identifier.str(), - ErrorType::ResourceNotFound); + bool getSettingDefaultValue(const CIdentifier& identifier, CString& defaultValue) const override + { + const auto it = m_interfacorIDToIdx.at(Setting).find(identifier); + OV_ERROR_UNLESS_KRF(it != m_interfacorIDToIdx.at(Setting).end(), "Failed to find setting with id " << identifier.str(), + ErrorType::ResourceNotFound); - return this->getSettingValue(it->second, value); - } + return this->getSettingDefaultValue(it->second, defaultValue); + } - bool getSettingValue(const CString& name, CString& value) const override - { - const auto it = m_interfacorNameToIdx.at(Setting).find(name); - OV_ERROR_UNLESS_KRF(it != m_interfacorNameToIdx.at(Setting).end(), "Failed to find setting with name " << name, - ErrorType::ResourceNotFound); + bool getSettingDefaultValue(const CString& name, CString& defaultValue) const override + { + const auto it = m_interfacorNameToIdx.at(Setting).find(name); + OV_ERROR_UNLESS_KRF(it != m_interfacorNameToIdx.at(Setting).end(), "Failed to find setting with name " << name, + ErrorType::ResourceNotFound); - return this->getSettingValue(it->second, value); - } + return this->getSettingDefaultValue(it->second, defaultValue); + } - bool getSettingMod(const size_t index, bool& value) const override - { - OV_ERROR_UNLESS_KRF(index < m_interfacors.at(Setting).size(), - "Setting index = [" << index << "] is out of range (max index = [" << m_interfacors.at(Setting).size() - 1 << "])", - ErrorType::OutOfBound); + bool getSettingValue(const size_t index, CString& value) const override + { + OV_ERROR_UNLESS_KRF(index < m_interfacors.at(Setting).size(), + "Setting index = [" << index << "] is out of range (max index = [" << m_interfacors.at(Setting).size() - 1 << "])", + ErrorType::OutOfBound); - value = std::static_pointer_cast<CSetting>(m_interfacors.at(Setting)[index])->m_Mod; - return true; - } + value = std::static_pointer_cast<CSetting>(m_interfacors.at(Setting)[index])->m_Value; + return true; + } - bool getSettingMod(const CIdentifier& identifier, bool& value) const override - { - const auto it = m_interfacorIDToIdx.at(Setting).find(identifier); - OV_ERROR_UNLESS_KRF(it != m_interfacorIDToIdx.at(Setting).end(), - "Failed to find setting with id " << identifier.str(), ErrorType::ResourceNotFound); + bool getSettingValue(const CIdentifier& identifier, CString& value) const override + { + const auto it = m_interfacorIDToIdx.at(Setting).find(identifier); + OV_ERROR_UNLESS_KRF(it != m_interfacorIDToIdx.at(Setting).end(), "Failed to find setting with id " << identifier.str(), + ErrorType::ResourceNotFound); - return this->getSettingMod(it->second, value); - } + return this->getSettingValue(it->second, value); + } - bool getSettingMod(const CString& name, bool& value) const override - { - const auto it = m_interfacorNameToIdx.at(Setting).find(name); - OV_ERROR_UNLESS_KRF(it != m_interfacorNameToIdx.at(Setting).end(), - "Failed to find setting with name " << name, ErrorType::ResourceNotFound); + bool getSettingValue(const CString& name, CString& value) const override + { + const auto it = m_interfacorNameToIdx.at(Setting).find(name); + OV_ERROR_UNLESS_KRF(it != m_interfacorNameToIdx.at(Setting).end(), "Failed to find setting with name " << name, + ErrorType::ResourceNotFound); - return this->getSettingMod(it->second, value); - } + return this->getSettingValue(it->second, value); + } - bool setSettingType(const size_t index, const CIdentifier& typeID) override { return this->setInterfacorType(Setting, index, typeID); } + bool getSettingMod(const size_t index, bool& value) const override + { + OV_ERROR_UNLESS_KRF(index < m_interfacors.at(Setting).size(), + "Setting index = [" << index << "] is out of range (max index = [" << m_interfacors.at(Setting).size() - 1 << "])", + ErrorType::OutOfBound); - bool setSettingName(const size_t index, const CString& name) override { return this->setInterfacorName(Setting, index, name); } + value = std::static_pointer_cast<CSetting>(m_interfacors.at(Setting)[index])->m_Mod; + return true; + } - bool setSettingDefaultValue(const size_t index, const CString& defaultValue) override - { - OV_ERROR_UNLESS_KRF(index < m_interfacors.at(Setting).size(), - "Setting index = [" << index << "] is out of range (max index = [" << m_interfacors.at(Setting).size() - 1 << "])", - ErrorType::OutOfBound); + bool getSettingMod(const CIdentifier& identifier, bool& value) const override + { + const auto it = m_interfacorIDToIdx.at(Setting).find(identifier); + OV_ERROR_UNLESS_KRF(it != m_interfacorIDToIdx.at(Setting).end(), + "Failed to find setting with id " << identifier.str(), ErrorType::ResourceNotFound); - std::static_pointer_cast<CSetting>(m_interfacors[Setting][index])->m_DefaultValue = defaultValue; + return this->getSettingMod(it->second, value); + } - this->notify(EBoxModification::SettingDefaultValueChanged, index); + bool getSettingMod(const CString& name, bool& value) const override + { + const auto it = m_interfacorNameToIdx.at(Setting).find(name); + OV_ERROR_UNLESS_KRF(it != m_interfacorNameToIdx.at(Setting).end(), + "Failed to find setting with name " << name, ErrorType::ResourceNotFound); - return true; - } + return this->getSettingMod(it->second, value); + } - bool setSettingDefaultValue(const CIdentifier& identifier, const CString& defaultValue) override - { - const auto it = m_interfacorIDToIdx.at(Setting).find(identifier); - OV_ERROR_UNLESS_KRF(it != m_interfacorIDToIdx.at(Setting).end(), "Failed to find setting with id " << identifier.str(), - ErrorType::ResourceNotFound); + bool setSettingType(const size_t index, const CIdentifier& typeID) override { return this->setInterfacorType(Setting, index, typeID); } - return this->setSettingDefaultValue(it->second, defaultValue); - } + bool setSettingName(const size_t index, const CString& name) override { return this->setInterfacorName(Setting, index, name); } - bool setSettingDefaultValue(const CString& name, const CString& defaultValue) override - { - const auto it = m_interfacorNameToIdx.at(Setting).find(name); - OV_ERROR_UNLESS_KRF(it != m_interfacorNameToIdx.at(Setting).end(), "Failed to find setting with name " << name, - ErrorType::ResourceNotFound); - return this->setSettingDefaultValue(it->second, defaultValue); - } + bool setSettingDefaultValue(const size_t index, const CString& defaultValue) override + { + OV_ERROR_UNLESS_KRF(index < m_interfacors.at(Setting).size(), + "Setting index = [" << index << "] is out of range (max index = [" << m_interfacors.at(Setting).size() - 1 << "])", + ErrorType::OutOfBound); - bool setSettingValue(const size_t index, const CString& value, const bool notify = true) override - { - OV_ERROR_UNLESS_KRF(index < m_interfacors.at(Setting).size(), - "Setting index = [" << index << "] is out of range (max index = [" << m_interfacors.at(Setting).size() - 1 << "])", - ErrorType::OutOfBound); + std::static_pointer_cast<CSetting>(m_interfacors[Setting][index])->m_DefaultValue = defaultValue; - auto setting = std::static_pointer_cast<CSetting>(m_interfacors[Setting][index]); - if (setting->m_Value != value) - { - setting->m_Value = value; + this->notify(EBoxModification::SettingDefaultValueChanged, index); - if (notify) - { - this->notify(EBoxModification::SettingValueChanged, index); - this->notifySettingChange(SettingValueUpdate, int(index)); - } - } + return true; + } - return true; - } + bool setSettingDefaultValue(const CIdentifier& identifier, const CString& defaultValue) override + { + const auto it = m_interfacorIDToIdx.at(Setting).find(identifier); + OV_ERROR_UNLESS_KRF(it != m_interfacorIDToIdx.at(Setting).end(), "Failed to find setting with id " << identifier.str(), + ErrorType::ResourceNotFound); - bool setSettingValue(const CIdentifier& identifier, const CString& value) override - { - const auto it = m_interfacorIDToIdx.at(Setting).find(identifier); - OV_ERROR_UNLESS_KRF(it != m_interfacorIDToIdx.at(Setting).end(), "Failed to find setting with id " << identifier.str(), - ErrorType::ResourceNotFound); + return this->setSettingDefaultValue(it->second, defaultValue); + } - return this->setSettingValue(it->second, value); - } + bool setSettingDefaultValue(const CString& name, const CString& defaultValue) override + { + const auto it = m_interfacorNameToIdx.at(Setting).find(name); + OV_ERROR_UNLESS_KRF(it != m_interfacorNameToIdx.at(Setting).end(), "Failed to find setting with name " << name, + ErrorType::ResourceNotFound); + return this->setSettingDefaultValue(it->second, defaultValue); + } - bool setSettingValue(const CString& name, const CString& value) override - { - const auto it = m_interfacorNameToIdx.at(Setting).find(name); - OV_ERROR_UNLESS_KRF(it != m_interfacorNameToIdx.at(Setting).end(), "Failed to find setting with name " << name, ErrorType::ResourceNotFound); + bool setSettingValue(const size_t index, const CString& value, const bool notify = true) override + { + OV_ERROR_UNLESS_KRF(index < m_interfacors.at(Setting).size(), + "Setting index = [" << index << "] is out of range (max index = [" << m_interfacors.at(Setting).size() - 1 << "])", + ErrorType::OutOfBound); - return this->setSettingValue(it->second, value); - } + auto setting = std::static_pointer_cast<CSetting>(m_interfacors[Setting][index]); + if (setting->m_Value != value) + { + setting->m_Value = value; - bool setSettingMod(const size_t index, const bool value) override + if (notify) { - OV_ERROR_UNLESS_KRF(index < m_interfacors.at(Setting).size(), - "Setting index = [" << index << "] is out of range (max index = [" << m_interfacors.at(Setting).size() - 1 << "])", - ErrorType::OutOfBound); - - std::static_pointer_cast<CSetting>(m_interfacors[Setting][index])->m_Mod = value; - - //this->notify(EBoxModification::SettingNameChanged, index); - return true; + this->notify(EBoxModification::SettingValueChanged, index); + this->notifySettingChange(SettingValueUpdate, int(index)); } + } - bool setSettingMod(const CString& name, const bool value) override - { - const auto it = m_interfacorNameToIdx.at(Setting).find(name); - OV_ERROR_UNLESS_KRF(it != m_interfacorNameToIdx.at(Setting).end(), "Failed to find setting with name " << name, - ErrorType::ResourceNotFound); + return true; + } - return this->setSettingMod(it->second, value); - } + bool setSettingValue(const CIdentifier& identifier, const CString& value) override + { + const auto it = m_interfacorIDToIdx.at(Setting).find(identifier); + OV_ERROR_UNLESS_KRF(it != m_interfacorIDToIdx.at(Setting).end(), "Failed to find setting with id " << identifier.str(), + ErrorType::ResourceNotFound); - bool setSettingMod(const CIdentifier& identifier, const bool value) override - { - const auto it = m_interfacorIDToIdx.at(Setting).find(identifier); - OV_ERROR_UNLESS_KRF(it != m_interfacorIDToIdx.at(Setting).end(), "Failed to find setting with id " << identifier.str(), - ErrorType::ResourceNotFound); + return this->setSettingValue(it->second, value); + } - return this->setSettingMod(it->second, value); - } + bool setSettingValue(const CString& name, const CString& value) override + { + const auto it = m_interfacorNameToIdx.at(Setting).find(name); + OV_ERROR_UNLESS_KRF(it != m_interfacorNameToIdx.at(Setting).end(), "Failed to find setting with name " << name, ErrorType::ResourceNotFound); - bool swapInterfacors(const EBoxInterfacorType interfacorType, const size_t indexA, const size_t indexB) - { - OV_ERROR_UNLESS_KRF(indexA < m_interfacors.at(interfacorType).size(), - INTERFACOR_TYPE_TO_NAME.at(interfacorType) << " index = [" << indexA << "] is out of range (max index = [" << m_interfacors. - at( - interfacorType).size() - 1 << "])", - ErrorType::OutOfBound); - OV_ERROR_UNLESS_KRF(indexB < m_interfacors.at(interfacorType).size(), - INTERFACOR_TYPE_TO_NAME.at(interfacorType) << " index = [" << indexB << "] is out of range (max index = [" << m_interfacors. - at( - interfacorType).size() - 1 << "])", - ErrorType::OutOfBound); - - CString nameA; - CIdentifier identifierA = OV_UndefinedIdentifier; - CString nameB; - CIdentifier identifierB = OV_UndefinedIdentifier; - - this->getInterfacorName(interfacorType, indexA, nameA); - this->getInterfacorIdentifier(interfacorType, indexA, identifierA); - this->getInterfacorName(interfacorType, indexB, nameB); - this->getInterfacorIdentifier(interfacorType, indexB, identifierB); - - const auto itA = m_interfacors[interfacorType].begin() + indexA; - const auto itB = m_interfacors[interfacorType].begin() + indexB; - // swap settings - std::iter_swap(itA, itB); - // update associated maps - m_interfacorNameToIdx.at(interfacorType)[nameA] = indexB; - m_interfacorNameToIdx.at(interfacorType)[nameB] = indexA; - m_interfacorIDToIdx.at(interfacorType)[identifierA] = indexB; - m_interfacorIDToIdx.at(interfacorType)[identifierB] = indexA; - - return true; - } + return this->setSettingValue(it->second, value); + } - bool swapSettings(const size_t indexA, const size_t indexB) override { return this->swapInterfacors(Setting, indexA, indexB); } - bool swapInputs(const size_t indexA, const size_t indexB) override { return this->swapInterfacors(Input, indexA, indexB); } - bool swapOutputs(const size_t indexA, const size_t indexB) override { return this->swapInterfacors(Output, indexA, indexB); } + bool setSettingMod(const size_t index, const bool value) override + { + OV_ERROR_UNLESS_KRF(index < m_interfacors.at(Setting).size(), + "Setting index = [" << index << "] is out of range (max index = [" << m_interfacors.at(Setting).size() - 1 << "])", + ErrorType::OutOfBound); - void notifySettingChange(const EBoxEventMessageType eType, const int firstIdx = -1, const int secondIdx = -1) - { - if (m_isObserverNotificationActive) - { - BoxEventMessage event; - event.m_Type = eType; - event.m_FirstIdx = firstIdx; - event.m_SecondIdx = secondIdx; + std::static_pointer_cast<CSetting>(m_interfacors[Setting][index])->m_Mod = value; - this->setChanged(); - this->notifyObservers(&event); - } - } + //this->notify(EBoxModification::SettingNameChanged, index); + return true; + } - bool hasModifiableSettings() const override - { - for (const auto& setting : m_interfacors.at(Setting)) { if (std::static_pointer_cast<CSetting>(setting)->m_Mod) { return true; } } - return false; - } + bool setSettingMod(const CString& name, const bool value) override + { + const auto it = m_interfacorNameToIdx.at(Setting).find(name); + OV_ERROR_UNLESS_KRF(it != m_interfacorNameToIdx.at(Setting).end(), "Failed to find setting with name " << name, + ErrorType::ResourceNotFound); - size_t* getModifiableSettings(size_t& count) const override - { - size_t* res = nullptr; - count = m_modifiableSettingIndexes.size(); - return res; - } + return this->setSettingMod(it->second, value); + } - bool updateInterfacorIdentifier(const EBoxInterfacorType interfacorType, const size_t index, const CIdentifier& newID) override - { - OV_ERROR_UNLESS_KRF(index < m_interfacors.at(interfacorType).size(), - INTERFACOR_TYPE_TO_NAME.at(interfacorType) << " index = [" << index << "] is out of range (max index = [" << m_interfacors. - at( - Setting).size() - 1 << "])", - ErrorType::OutOfBound); + bool setSettingMod(const CIdentifier& identifier, const bool value) override + { + const auto it = m_interfacorIDToIdx.at(Setting).find(identifier); + OV_ERROR_UNLESS_KRF(it != m_interfacorIDToIdx.at(Setting).end(), "Failed to find setting with id " << identifier.str(), + ErrorType::ResourceNotFound); - OV_ERROR_UNLESS_KRF(newID != OV_UndefinedIdentifier, INTERFACOR_TYPE_TO_NAME.at(interfacorType) << " identifier can not be undefined", - ErrorType::BadArgument); + return this->setSettingMod(it->second, value); + } - CIdentifier oldIdentifier = OV_UndefinedIdentifier; - this->getInterfacorIdentifier(interfacorType, index, oldIdentifier); + bool swapInterfacors(const EBoxInterfacorType interfacorType, const size_t indexA, const size_t indexB) + { + OV_ERROR_UNLESS_KRF(indexA < m_interfacors.at(interfacorType).size(), + INTERFACOR_TYPE_TO_NAME.at(interfacorType) << " index = [" << indexA << "] is out of range (max index = [" << m_interfacors. + at( + interfacorType).size() - 1 << "])", + ErrorType::OutOfBound); + OV_ERROR_UNLESS_KRF(indexB < m_interfacors.at(interfacorType).size(), + INTERFACOR_TYPE_TO_NAME.at(interfacorType) << " index = [" << indexB << "] is out of range (max index = [" << m_interfacors. + at( + interfacorType).size() - 1 << "])", + ErrorType::OutOfBound); + + CString nameA; + CIdentifier identifierA = OV_UndefinedIdentifier; + CString nameB; + CIdentifier identifierB = OV_UndefinedIdentifier; + + this->getInterfacorName(interfacorType, indexA, nameA); + this->getInterfacorIdentifier(interfacorType, indexA, identifierA); + this->getInterfacorName(interfacorType, indexB, nameB); + this->getInterfacorIdentifier(interfacorType, indexB, identifierB); + + const auto itA = m_interfacors[interfacorType].begin() + indexA; + const auto itB = m_interfacors[interfacorType].begin() + indexB; + // swap settings + std::iter_swap(itA, itB); + // update associated maps + m_interfacorNameToIdx.at(interfacorType)[nameA] = indexB; + m_interfacorNameToIdx.at(interfacorType)[nameB] = indexA; + m_interfacorIDToIdx.at(interfacorType)[identifierA] = indexB; + m_interfacorIDToIdx.at(interfacorType)[identifierB] = indexA; + + return true; + } + + bool swapSettings(const size_t indexA, const size_t indexB) override { return this->swapInterfacors(Setting, indexA, indexB); } + bool swapInputs(const size_t indexA, const size_t indexB) override { return this->swapInterfacors(Input, indexA, indexB); } + bool swapOutputs(const size_t indexA, const size_t indexB) override { return this->swapInterfacors(Output, indexA, indexB); } + + void notifySettingChange(const EBoxEventMessageType eType, const int firstIdx = -1, const int secondIdx = -1) + { + if (m_isObserverNotificationActive) + { + BoxEventMessage event; + event.m_Type = eType; + event.m_FirstIdx = firstIdx; + event.m_SecondIdx = secondIdx; - if (oldIdentifier != newID) - { - // identifier key update is necessary - const auto it = m_interfacorIDToIdx.at(interfacorType).find(newID); - OV_ERROR_UNLESS_KRF(it == m_interfacorIDToIdx.at(interfacorType).end(), - "Conflict in " << INTERFACOR_TYPE_TO_NAME.at(interfacorType) << - " identifiers. An entity with the same identifier exists.", - ErrorType::ResourceNotFound); - m_interfacors[interfacorType][index]->m_ID = newID; - m_interfacorIDToIdx[interfacorType][newID] = index; - // remove the old identifier key - const auto itOld = m_interfacorIDToIdx[interfacorType].find(oldIdentifier); - if (itOld != m_interfacorIDToIdx[interfacorType].end()) { m_interfacorIDToIdx[interfacorType].erase(itOld); } - } - return true; - } + this->setChanged(); + this->notifyObservers(&event); + } + } - //*/ + bool hasModifiableSettings() const override + { + for (const auto& setting : m_interfacors.at(Setting)) { if (std::static_pointer_cast<CSetting>(setting)->m_Mod) { return true; } } + return false; + } - bool acceptVisitor(IObjectVisitor& rObjectVisitor) override - { - CObjectVisitorContext context(this->getKernelContext()); - return rObjectVisitor.processBegin(context, *this) && rObjectVisitor.processEnd(context, *this); - } + size_t* getModifiableSettings(size_t& count) const override + { + size_t* res = nullptr; + count = m_modifiableSettingIndexes.size(); + return res; + } - protected: + bool updateInterfacorIdentifier(const EBoxInterfacorType interfacorType, const size_t index, const CIdentifier& newID) override + { + OV_ERROR_UNLESS_KRF(index < m_interfacors.at(interfacorType).size(), + INTERFACOR_TYPE_TO_NAME.at(interfacorType) << " index = [" << index << "] is out of range (max index = [" << m_interfacors. + at( + Setting).size() - 1 << "])", + ErrorType::OutOfBound); - void clearBox() - { - m_boxAlgorithmDesc = nullptr; - m_algorithmClassID = OV_UndefinedIdentifier; - m_name = ""; - m_interfacors[Input].clear(); - m_interfacors[Output].clear(); - m_interfacors[Setting].clear(); - m_interfacorIDToIdx[Input].clear(); - m_interfacorNameToIdx[Input].clear(); - m_interfacorIDToIdx[Output].clear(); - m_interfacorNameToIdx[Output].clear(); - m_interfacorIDToIdx.at(Setting).clear(); - m_interfacorNameToIdx.at(Setting).clear(); - - this->removeAllAttributes(); - } + OV_ERROR_UNLESS_KRF(newID != OV_UndefinedIdentifier, INTERFACOR_TYPE_TO_NAME.at(interfacorType) << " identifier can not be undefined", + ErrorType::BadArgument); - void enableNotification() { m_isNotificationActive = true; } - void disableNotification() { m_isNotificationActive = false; } + CIdentifier oldIdentifier = OV_UndefinedIdentifier; + this->getInterfacorIdentifier(interfacorType, index, oldIdentifier); - void notify(const EBoxModification eBoxModificationType, const size_t index) - { - if (m_boxListener && !m_isNotifyingDesc && m_isNotificationActive) - { - CBoxListenerContext context(this->getKernelContext(), *this, index); - m_isNotifyingDesc = true; - m_boxListener->process(context, eBoxModificationType); - m_isNotifyingDesc = false; - } - } + if (oldIdentifier != newID) + { + // identifier key update is necessary + const auto it = m_interfacorIDToIdx.at(interfacorType).find(newID); + OV_ERROR_UNLESS_KRF(it == m_interfacorIDToIdx.at(interfacorType).end(), + "Conflict in " << INTERFACOR_TYPE_TO_NAME.at(interfacorType) << + " identifiers. An entity with the same identifier exists.", + ErrorType::ResourceNotFound); + m_interfacors[interfacorType][index]->m_ID = newID; + m_interfacorIDToIdx[interfacorType][newID] = index; + // remove the old identifier key + const auto itOld = m_interfacorIDToIdx[interfacorType].find(oldIdentifier); + if (itOld != m_interfacorIDToIdx[interfacorType].end()) { m_interfacorIDToIdx[interfacorType].erase(itOld); } + } + return true; + } + + //*/ + + bool acceptVisitor(IObjectVisitor& rObjectVisitor) override + { + CObjectVisitorContext context(this->getKernelContext()); + return rObjectVisitor.processBegin(context, *this) && rObjectVisitor.processEnd(context, *this); + } - void notify(const EBoxModification boxModification) { this->notify(boxModification, 0xffffffff); } +protected: - _IsDerivedFromClass_Final_(TAttributable<TKernelObject<T>>, OVK_ClassId_Kernel_Scenario_Box) + void clearBox() + { + m_boxAlgorithmDesc = nullptr; + m_algorithmClassID = OV_UndefinedIdentifier; + m_name = ""; + m_interfacors[Input].clear(); + m_interfacors[Output].clear(); + m_interfacors[Setting].clear(); + m_interfacorIDToIdx[Input].clear(); + m_interfacorNameToIdx[Input].clear(); + m_interfacorIDToIdx[Output].clear(); + m_interfacorNameToIdx[Output].clear(); + m_interfacorIDToIdx.at(Setting).clear(); + m_interfacorNameToIdx.at(Setting).clear(); + + this->removeAllAttributes(); + } + + void enableNotification() { m_isNotificationActive = true; } + void disableNotification() { m_isNotificationActive = false; } + + void notify(const EBoxModification eBoxModificationType, const size_t index) + { + if (m_boxListener && !m_isNotifyingDesc && m_isNotificationActive) + { + CBoxListenerContext context(this->getKernelContext(), *this, index); + m_isNotifyingDesc = true; + m_boxListener->process(context, eBoxModificationType); + m_isNotifyingDesc = false; + } + } - CString getUnusedName(const std::map<CString, size_t>& nameToIndex, const CString& suggestedName) const - { - size_t idx = 1; - CString newName; - auto it = nameToIndex.find(suggestedName); - do - { - newName = suggestedName; - if (it != nameToIndex.end()) - { - newName += "(" + CString(std::to_string(idx).c_str()) + ")"; - it = nameToIndex.find(newName); - idx++; - } - } while (it != nameToIndex.end()); - return newName; - } + void notify(const EBoxModification boxModification) { this->notify(boxModification, 0xffffffff); } + + _IsDerivedFromClass_Final_(TAttributable<TKernelObject<T>>, OVK_ClassId_Kernel_Scenario_Box) - IScenario* m_ownerScenario = nullptr; - const Plugins::IBoxAlgorithmDesc* m_boxAlgorithmDesc = nullptr; - Plugins::IBoxListener* m_boxListener = nullptr; - bool m_isNotifyingDesc = false; - bool m_isNotificationActive = true; - bool m_isObserverNotificationActive = true; - - CIdentifier m_identifier = OV_UndefinedIdentifier; - CIdentifier m_algorithmClassID = OV_UndefinedIdentifier; - CString m_name = "unnamed"; - - std::map<EBoxInterfacorType, std::map<CIdentifier, size_t>> m_interfacorIDToIdx; - std::map<EBoxInterfacorType, std::map<CString, size_t>> m_interfacorNameToIdx; - - //to avoid having to recheck every setting every time - //careful to update at each setting modification - std::vector<size_t> m_modifiableSettingIndexes; - - std::vector<CIdentifier> m_supportInputTypes; - std::vector<CIdentifier> m_supportOutputTypes; - private: - std::map<EBoxInterfacorType, std::vector<std::shared_ptr<CInterfacor>>> m_interfacors; - }; - } // namespace Kernel -} // namespace OpenViBE + CString getUnusedName(const std::map<CString, size_t>& nameToIndex, const CString& suggestedName) const + { + size_t idx = 1; + CString newName; + auto it = nameToIndex.find(suggestedName); + do + { + newName = suggestedName; + if (it != nameToIndex.end()) + { + newName += "(" + CString(std::to_string(idx).c_str()) + ")"; + it = nameToIndex.find(newName); + idx++; + } + } while (it != nameToIndex.end()); + return newName; + } + + IScenario* m_ownerScenario = nullptr; + const Plugins::IBoxAlgorithmDesc* m_boxAlgorithmDesc = nullptr; + Plugins::IBoxListener* m_boxListener = nullptr; + bool m_isNotifyingDesc = false; + bool m_isNotificationActive = true; + bool m_isObserverNotificationActive = true; + + CIdentifier m_identifier = OV_UndefinedIdentifier; + CIdentifier m_algorithmClassID = OV_UndefinedIdentifier; + CString m_name = "unnamed"; + + std::map<EBoxInterfacorType, std::map<CIdentifier, size_t>> m_interfacorIDToIdx; + std::map<EBoxInterfacorType, std::map<CString, size_t>> m_interfacorNameToIdx; + + //to avoid having to recheck every setting every time + //careful to update at each setting modification + std::vector<size_t> m_modifiableSettingIndexes; + + std::vector<CIdentifier> m_supportInputTypes; + std::vector<CIdentifier> m_supportOutputTypes; +private: + std::map<EBoxInterfacorType, std::vector<std::shared_ptr<CInterfacor>>> m_interfacors; +}; +} // namespace Kernel +} // namespace OpenViBE diff --git a/kernel/src/ovk_defines.h b/kernel/src/ovk_defines.h index 219075a7edb9250ab41a884bba0b54cc7b5840e0..d686dc987fd705cc8eca8031508e5fa24c4ed568 100755 --- a/kernel/src/ovk_defines.h +++ b/kernel/src/ovk_defines.h @@ -40,8 +40,6 @@ #define OVK_ClassId_Kernel_Player_DynamicBoxContext OpenViBE::CIdentifier(0x18FC58E0, 0x505E97CD) #define OVK_ClassId_Kernel_Player_MessageT OpenViBE::CIdentifier(0x42A56E80, 0x289CBB09) #define OVK_ClassId_Kernel_Player_MessageClock OpenViBE::CIdentifier(0x3AA34472, 0x2B1F67CB) -#define OVK_ClassId_Kernel_Player_MessageEvent OpenViBE::CIdentifier(0x036401EF, 0x31E90C38) -#define OVK_ClassId_Kernel_Player_MessageSignal OpenViBE::CIdentifier(0x3BB1DDD9, 0x0B289F8D) #define OVK_ClassId_Kernel_Player_Player OpenViBE::CIdentifier(0x7C8777FF, 0x52CE89C2) #define OVK_ClassId_Kernel_Player_PlayerContext OpenViBE::CIdentifier(0x76A544A0, 0x01F508ED) #define OVK_ClassId_Kernel_Player_PlayerManager OpenViBE::CIdentifier(0x4A46A96D, 0x6D4957C5) diff --git a/kernel/src/ovk_main.cpp b/kernel/src/ovk_main.cpp index a9e25d34548821901ddce037da9cfe9959636567..832c0227053fa443e73cbb8e6aebcefac7065f05 100644 --- a/kernel/src/ovk_main.cpp +++ b/kernel/src/ovk_main.cpp @@ -5,33 +5,31 @@ using namespace OpenViBE; using namespace /*OpenViBE::*/Kernel; -namespace OpenViBE +namespace OpenViBE { +namespace Kernel { +class CKernelDesc final : public IKernelDesc { - namespace Kernel +public: + IKernelContext* createKernel(const CString& rApplicationName, const CString& rConfigurationFilename) override { - class CKernelDesc final : public IKernelDesc - { - public: - IKernelContext* createKernel(const CString& rApplicationName, const CString& rConfigurationFilename) override - { - return new CKernelContext(nullptr, rApplicationName, rConfigurationFilename); - } - - IKernelContext* createKernel(const IKernelContext& masterKernelCtx, const CString& applicationName, const CString& configFilename) - override { return new CKernelContext(&masterKernelCtx, applicationName, configFilename); } - - void releaseKernel(IKernelContext* pKernelContext) override { delete pKernelContext; } - CString getName() const override { return CString("OpenViBE Kernel Implementation"); } - CString getAuthorName() const override { return CString("Yann Renard"); } - CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } - CString getShortDescription() const override { return CString("OpenViBE Kernel Implementation"); } - CString getDetailedDescription() const override { return CString("OpenViBE Kernel Implementation"); } - CString getVersion() const override { return CString("0.5"); } - - _IsDerivedFromClass_Final_(IKernelDesc, OVK_ClassId_KernelDesc) - }; - } // namespace Kernel -} // namespace OpenViBE + return new CKernelContext(nullptr, rApplicationName, rConfigurationFilename); + } + + IKernelContext* createKernel(const IKernelContext& masterKernelCtx, const CString& applicationName, const CString& configFilename) + override { return new CKernelContext(&masterKernelCtx, applicationName, configFilename); } + + void releaseKernel(IKernelContext* pKernelContext) override { delete pKernelContext; } + CString getName() const override { return CString("OpenViBE Kernel Implementation"); } + CString getAuthorName() const override { return CString("Yann Renard"); } + CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } + CString getShortDescription() const override { return CString("OpenViBE Kernel Implementation"); } + CString getDetailedDescription() const override { return CString("OpenViBE Kernel Implementation"); } + CString getVersion() const override { return CString("0.5"); } + + _IsDerivedFromClass_Final_(IKernelDesc, OVK_ClassId_KernelDesc) +}; +} // namespace Kernel +} // namespace OpenViBE static CKernelDesc gKernelDesc; diff --git a/kernel/src/tools/ovkCKernelObjectFactoryHelper.h b/kernel/src/tools/ovkCKernelObjectFactoryHelper.h index 5a7498ca734fe9ace6c2101cfa91c3879b640e81..7f8882794034105b25ed8b25390f33e520c051aa 100644 --- a/kernel/src/tools/ovkCKernelObjectFactoryHelper.h +++ b/kernel/src/tools/ovkCKernelObjectFactoryHelper.h @@ -2,38 +2,36 @@ #include <openvibe/ov_all.h> -namespace OpenViBE +namespace OpenViBE { +namespace Tools { +class CKernelObjectFactoryHelper final : public IObject { - namespace Tools - { - class CKernelObjectFactoryHelper final : public IObject - { - public: +public: - explicit CKernelObjectFactoryHelper(Kernel::IKernelObjectFactory& rKernelObjectFactory) - : m_rKernelObjectFactory(rKernelObjectFactory) { } + explicit CKernelObjectFactoryHelper(Kernel::IKernelObjectFactory& rKernelObjectFactory) + : m_rKernelObjectFactory(rKernelObjectFactory) { } - template <class T> - T createObject(const CIdentifier& classID) - { - IObject* obj = m_rKernelObjectFactory.createObject(classID); - T res = dynamic_cast<T>(obj); - if (obj && !res) { m_rKernelObjectFactory.releaseObject(obj); } - return res; - } + template <class T> + T createObject(const CIdentifier& classID) + { + IObject* obj = m_rKernelObjectFactory.createObject(classID); + T res = dynamic_cast<T>(obj); + if (obj && !res) { m_rKernelObjectFactory.releaseObject(obj); } + return res; + } - template <class T> - bool releaseObject(T tObject) { return m_rKernelObjectFactory.releaseObject(tObject); } + template <class T> + bool releaseObject(T tObject) { return m_rKernelObjectFactory.releaseObject(tObject); } - _IsDerivedFromClass_Final_(IObject, OVK_ClassId_Tools_KernelObjectFactoryHelper) + _IsDerivedFromClass_Final_(IObject, OVK_ClassId_Tools_KernelObjectFactoryHelper) - protected: +protected: - Kernel::IKernelObjectFactory& m_rKernelObjectFactory; + Kernel::IKernelObjectFactory& m_rKernelObjectFactory; - private: +private: - CKernelObjectFactoryHelper(); - }; - } // namespace Tools -} // namespace OpenViBE + CKernelObjectFactoryHelper(); +}; +} // namespace Tools +} // namespace OpenViBE diff --git a/kernel/src/tools/ovkCScopeTester.h b/kernel/src/tools/ovkCScopeTester.h index 87a9ec5e229a79c9de8444c1fc293efe4aabe5e5..40e4093608307f4a904ffe5983dd8bd2b73474d8 100644 --- a/kernel/src/tools/ovkCScopeTester.h +++ b/kernel/src/tools/ovkCScopeTester.h @@ -4,23 +4,21 @@ #include <openvibe/ov_all.h> -namespace OpenViBE +namespace OpenViBE { +namespace Tools { +class CScopeTester final : public IObject { - namespace Tools - { - class CScopeTester final : public IObject - { - public: +public: - CScopeTester(const Kernel::IKernelContext& ctx, const CString& prefix); - ~CScopeTester() override; + CScopeTester(const Kernel::IKernelContext& ctx, const CString& prefix); + ~CScopeTester() override; - _IsDerivedFromClass_Final_(IObject, OVK_ClassId_Tools_ScopeTester) + _IsDerivedFromClass_Final_(IObject, OVK_ClassId_Tools_ScopeTester) - protected: +protected: - CString m_prefix; - const Kernel::IKernelContext& m_kernelCtx; - }; - } // namespace Tools -} // namespace OpenViBE + CString m_prefix; + const Kernel::IKernelContext& m_kernelCtx; +}; +} // namespace Tools +} // namespace OpenViBE diff --git a/kernel/src/tools/ovkSBoxProto.h b/kernel/src/tools/ovkSBoxProto.h index bbda6221d3f09f019ac0ac8417872c07c9901562..859005dfbcd9d0f852a774f32793614164074431 100755 --- a/kernel/src/tools/ovkSBoxProto.h +++ b/kernel/src/tools/ovkSBoxProto.h @@ -3,154 +3,153 @@ #include <openvibe/kernel/scenario/ovIBoxProto.h> #include <system/ovCMemory.h> -namespace +namespace { +using namespace OpenViBE; +using namespace /*OpenViBE::*/Kernel; + +struct SBoxProto final : IBoxProto { - using namespace OpenViBE; - using namespace /*OpenViBE::*/Kernel; + SBoxProto(ITypeManager& typeManager) : m_TypeManager(typeManager) { } - struct SBoxProto final : IBoxProto + bool addInput(const CString& /*name*/, const CIdentifier& typeID, const CIdentifier& id, const bool /*notify*/) override { - SBoxProto(ITypeManager& typeManager) : m_TypeManager(typeManager) { } - - bool addInput(const CString& /*name*/, const CIdentifier& typeID, const CIdentifier& id, const bool /*notify*/) override + uint64_t v = typeID.toUInteger(); + swap_byte(v, m_inputCountHash); + swap_byte(m_inputCountHash, 0x7936A0F3BD12D936LL); + m_hash = m_hash.toUInteger() ^ v; + if (id != OV_UndefinedIdentifier) { - uint64_t v = typeID.toUInteger(); - swap_byte(v, m_inputCountHash); - swap_byte(m_inputCountHash, 0x7936A0F3BD12D936LL); + v = id.toUInteger(); + swap_byte(v, 0x2BD1D158F340014D); m_hash = m_hash.toUInteger() ^ v; - if (id != OV_UndefinedIdentifier) - { - v = id.toUInteger(); - swap_byte(v, 0x2BD1D158F340014D); - m_hash = m_hash.toUInteger() ^ v; - } - return true; } + return true; + } - bool addOutput(const CString& /*name*/, const CIdentifier& typeID, const CIdentifier& id, const bool /*notify*/) override + bool addOutput(const CString& /*name*/, const CIdentifier& typeID, const CIdentifier& id, const bool /*notify*/) override + { + uint64_t v = typeID.toUInteger(); + swap_byte(v, m_outputCountHash); + swap_byte(m_outputCountHash, 0xCBB66A5B893AA4E9LL); + m_hash = m_hash.toUInteger() ^ v; + if (id != OV_UndefinedIdentifier) { - uint64_t v = typeID.toUInteger(); - swap_byte(v, m_outputCountHash); - swap_byte(m_outputCountHash, 0xCBB66A5B893AA4E9LL); + v = id.toUInteger(); + swap_byte(v, 0x87CA0F5EFC4FAC68); m_hash = m_hash.toUInteger() ^ v; - if (id != OV_UndefinedIdentifier) - { - v = id.toUInteger(); - swap_byte(v, 0x87CA0F5EFC4FAC68); - m_hash = m_hash.toUInteger() ^ v; - } - return true; } + return true; + } - bool addSetting(const CString& /*name*/, const CIdentifier& typeID, const CString& /*defaultValue*/, const bool /*modifiable*/, const CIdentifier& id, - const bool /*notify*/) override + bool addSetting(const CString& /*name*/, const CIdentifier& typeID, const CString& /*defaultValue*/, const bool /*modifiable*/, const CIdentifier& id, + const bool /*notify*/) override + { + uint64_t v = typeID.toUInteger(); + swap_byte(v, m_settingCountHash); + swap_byte(m_settingCountHash, 0x3C87F3AAE9F8303BLL); + m_hash = m_hash.toUInteger() ^ v; + if (id != OV_UndefinedIdentifier) { - uint64_t v = typeID.toUInteger(); - swap_byte(v, m_settingCountHash); - swap_byte(m_settingCountHash, 0x3C87F3AAE9F8303BLL); + v = id.toUInteger(); + swap_byte(v, 0x17185F7CDA63A9FA); m_hash = m_hash.toUInteger() ^ v; - if (id != OV_UndefinedIdentifier) - { - v = id.toUInteger(); - swap_byte(v, 0x17185F7CDA63A9FA); - m_hash = m_hash.toUInteger() ^ v; - } - return true; } + return true; + } - bool addInputSupport(const CIdentifier& typeID) override - { - uint64_t v = typeID.toUInteger(); - swap_byte(v, m_outputCountHash); - swap_byte(m_outputCountHash, 0xCBB66A5B893AA4E9LL); - m_hash = m_hash.toUInteger() ^ v; - return true; - } + bool addInputSupport(const CIdentifier& typeID) override + { + uint64_t v = typeID.toUInteger(); + swap_byte(v, m_outputCountHash); + swap_byte(m_outputCountHash, 0xCBB66A5B893AA4E9LL); + m_hash = m_hash.toUInteger() ^ v; + return true; + } - bool addInputAndDerivedSupport(const CIdentifier& typeID) - { - uint64_t v = typeID.toUInteger(); - swap_byte(v, m_outputCountHash); - swap_byte(m_outputCountHash, 0xCBB66A5B893AA4E9LL); - m_hash = m_hash.toUInteger() ^ v; - return true; - } + bool addInputAndDerivedSupport(const CIdentifier& typeID) + { + uint64_t v = typeID.toUInteger(); + swap_byte(v, m_outputCountHash); + swap_byte(m_outputCountHash, 0xCBB66A5B893AA4E9LL); + m_hash = m_hash.toUInteger() ^ v; + return true; + } - bool addOutputSupport(const CIdentifier& typeID) override - { - uint64_t v = typeID.toUInteger(); - swap_byte(v, m_outputCountHash); - swap_byte(m_outputCountHash, 0xCBB66A5B893AA4E9LL); - m_hash = m_hash.toUInteger() ^ v; - return true; - } + bool addOutputSupport(const CIdentifier& typeID) override + { + uint64_t v = typeID.toUInteger(); + swap_byte(v, m_outputCountHash); + swap_byte(m_outputCountHash, 0xCBB66A5B893AA4E9LL); + m_hash = m_hash.toUInteger() ^ v; + return true; + } - bool addOutputAndDerivedSupport(const CIdentifier& typeID) - { - uint64_t v = typeID.toUInteger(); - swap_byte(v, m_outputCountHash); - swap_byte(m_outputCountHash, 0xCBB66A5B893AA4E9LL); - m_hash = m_hash.toUInteger() ^ v; - return true; - } + bool addOutputAndDerivedSupport(const CIdentifier& typeID) + { + uint64_t v = typeID.toUInteger(); + swap_byte(v, m_outputCountHash); + swap_byte(m_outputCountHash, 0xCBB66A5B893AA4E9LL); + m_hash = m_hash.toUInteger() ^ v; + return true; + } - bool addFlag(const EBoxFlag flag) override + bool addFlag(const EBoxFlag flag) override + { + switch (flag) { - switch (flag) - { - case BoxFlag_CanAddInput: m_hash = m_hash.toUInteger() ^ CIdentifier(0x07507AC8, 0xEB643ACE).toUInteger(); - break; - case BoxFlag_CanModifyInput: m_hash = m_hash.toUInteger() ^ CIdentifier(0x5C985376, 0x8D74CDB8).toUInteger(); - break; - case BoxFlag_CanAddOutput: m_hash = m_hash.toUInteger() ^ CIdentifier(0x58DEA69B, 0x12411365).toUInteger(); - break; - case BoxFlag_CanModifyOutput: m_hash = m_hash.toUInteger() ^ CIdentifier(0x6E162C01, 0xAC979F22).toUInteger(); - break; - case BoxFlag_CanAddSetting: m_hash = m_hash.toUInteger() ^ CIdentifier(0xFA7A50DC, 0x2140C013).toUInteger(); - break; - case BoxFlag_CanModifySetting: m_hash = m_hash.toUInteger() ^ CIdentifier(0x624D7661, 0xD8DDEA0A).toUInteger(); - break; - case BoxFlag_IsDeprecated: m_isDeprecated = true; - break; - default: - return false; - } - return true; + case BoxFlag_CanAddInput: m_hash = m_hash.toUInteger() ^ CIdentifier(0x07507AC8, 0xEB643ACE).toUInteger(); + break; + case BoxFlag_CanModifyInput: m_hash = m_hash.toUInteger() ^ CIdentifier(0x5C985376, 0x8D74CDB8).toUInteger(); + break; + case BoxFlag_CanAddOutput: m_hash = m_hash.toUInteger() ^ CIdentifier(0x58DEA69B, 0x12411365).toUInteger(); + break; + case BoxFlag_CanModifyOutput: m_hash = m_hash.toUInteger() ^ CIdentifier(0x6E162C01, 0xAC979F22).toUInteger(); + break; + case BoxFlag_CanAddSetting: m_hash = m_hash.toUInteger() ^ CIdentifier(0xFA7A50DC, 0x2140C013).toUInteger(); + break; + case BoxFlag_CanModifySetting: m_hash = m_hash.toUInteger() ^ CIdentifier(0x624D7661, 0xD8DDEA0A).toUInteger(); + break; + case BoxFlag_IsDeprecated: m_isDeprecated = true; + break; + default: + return false; } + return true; + } - bool addFlag(const CIdentifier& flagId) override - { - const uint64_t value = m_TypeManager.getEnumerationEntryValueFromName(OV_TypeId_BoxAlgorithmFlag, flagId.toString()); - if (value == OV_UndefinedIdentifier) { return false; } - // Flags do not modify internal hash - //m_hash=m_hash.toUInteger() ^ flagId.toUInteger(); - return true; - } + bool addFlag(const CIdentifier& flagId) override + { + const uint64_t value = m_TypeManager.getEnumerationEntryValueFromName(OV_TypeId_BoxAlgorithmFlag, flagId.toString()); + if (value == OV_UndefinedIdentifier) { return false; } + // Flags do not modify internal hash + //m_hash=m_hash.toUInteger() ^ flagId.toUInteger(); + return true; + } - void swap_byte(uint64_t& v, const uint64_t s) + void swap_byte(uint64_t& v, const uint64_t s) + { + uint8_t v2[sizeof(v)]; + uint8_t s2[sizeof(s)]; + System::Memory::hostToLittleEndian(v, v2); + System::Memory::hostToLittleEndian(s, s2); + for (size_t i = 0; i < sizeof(s); i += 2) { - uint8_t v2[sizeof(v)]; - uint8_t s2[sizeof(s)]; - System::Memory::hostToLittleEndian(v, v2); - System::Memory::hostToLittleEndian(s, s2); - for (size_t i = 0; i < sizeof(s); i += 2) - { - const size_t j = s2[i] % sizeof(v); - const size_t k = s2[i + 1] % sizeof(v); - const uint8_t t = v2[j]; - v2[j] = v2[k]; - v2[k] = t; - } - System::Memory::littleEndianToHost(v2, &v); + const size_t j = s2[i] % sizeof(v); + const size_t k = s2[i + 1] % sizeof(v); + const uint8_t t = v2[j]; + v2[j] = v2[k]; + v2[k] = t; } + System::Memory::littleEndianToHost(v2, &v); + } - _IsDerivedFromClass_Final_(IBoxProto, OV_UndefinedIdentifier) + _IsDerivedFromClass_Final_(IBoxProto, OV_UndefinedIdentifier) - CIdentifier m_hash = OV_UndefinedIdentifier; - bool m_isDeprecated = false; - uint64_t m_inputCountHash = 0x64AC3CB54A35888CLL; - uint64_t m_outputCountHash = 0x21E0FAAFE5CAF1E1LL; - uint64_t m_settingCountHash = 0x6BDFB15B54B09F63LL; - ITypeManager& m_TypeManager; - }; -} // namespace + CIdentifier m_hash = OV_UndefinedIdentifier; + bool m_isDeprecated = false; + uint64_t m_inputCountHash = 0x64AC3CB54A35888CLL; + uint64_t m_outputCountHash = 0x21E0FAAFE5CAF1E1LL; + uint64_t m_settingCountHash = 0x6BDFB15B54B09F63LL; + ITypeManager& m_TypeManager; +}; +} // namespace diff --git a/modules/CMakeLists.txt b/modules/CMakeLists.txt index 5da9f660fc3c75b30726512fe672a95bacab77ac..25873409a386b58f26807ed7435459cc43329315 100644 --- a/modules/CMakeLists.txt +++ b/modules/CMakeLists.txt @@ -2,3 +2,6 @@ OV_SET_CUSTOM_DOCUMENTATION("ebml" "EBML parser and formater library" "src" "inc # Add all the subdirs as projects of the named branch OV_ADD_PROJECTS("MODULES") +# Sort target into directories for better visualization in IDE +SET_PROPERTY(GLOBAL PROPERTY USE_FOLDERS ON) +SET(MODULES_FOLDER Modules) \ No newline at end of file diff --git a/modules/communication/CMakeLists.txt b/modules/communication/CMakeLists.txt index 5dcb4ed769860d70bd82c02fabceb98fd75ebf75..c11b672e353bffacb246f8e0ab6de47b8c6c378b 100644 --- a/modules/communication/CMakeLists.txt +++ b/modules/communication/CMakeLists.txt @@ -9,12 +9,14 @@ ADD_LIBRARY(${PROJECT_NAME} SHARED ${SRC_FILES}) SET_TARGET_PROPERTIES(${PROJECT_NAME} PROPERTIES VERSION ${PROJECT_VERSION} SOVERSION ${PROJECT_VERSION_MAJOR} + FOLDER ${MODULES_FOLDER} COMPILE_FLAGS "-DCommunication_Shared -DCommunication_Exports") ADD_LIBRARY(${PROJECT_NAME}-static STATIC ${SRC_FILES}) SET_TARGET_PROPERTIES(${PROJECT_NAME}-static PROPERTIES VERSION ${PROJECT_VERSION} SOVERSION ${PROJECT_VERSION_MAJOR} + FOLDER ${MODULES_FOLDER} COMPILE_FLAGS "-DCommunication_Static -DCommunication_Exports") IF(UNIX) diff --git a/modules/communication/include/communication/defines.h b/modules/communication/include/communication/defines.h index 7de10d4b6faa6c2b902f8e7b8d2fa6524045312a..3c13ab6fdd306a303cf31f4deb84f2355eaf055d 100644 --- a/modules/communication/include/communication/defines.h +++ b/modules/communication/include/communication/defines.h @@ -3,23 +3,23 @@ #include <ov_common_defines.h> #if defined Communication_Shared -#if defined TARGET_OS_Windows -#define Communication_API_Export __declspec(dllexport) -#define Communication_API_Import __declspec(dllimport) -#elif defined TARGET_OS_Linux || defined TARGET_OS_MacOS - #define Communication_API_Export __attribute__((visibility("default"))) - #define Communication_API_Import __attribute__((visibility("default"))) +# if defined TARGET_OS_Windows +# define Communication_API_Export __declspec(dllexport) +# define Communication_API_Import __declspec(dllimport) +# elif defined TARGET_OS_Linux || defined TARGET_OS_MacOS +# define Communication_API_Export __attribute__((visibility("default"))) +# define Communication_API_Import __attribute__((visibility("default"))) +# else +# define Communication_API_Export +# define Communication_API_Import +# endif #else - #define Communication_API_Export - #define Communication_API_Import -#endif -#else -#define Communication_API_Export -#define Communication_API_Import +# define Communication_API_Export +# define Communication_API_Import #endif #if defined Communication_Exports -#define Communication_API Communication_API_Export +# define Communication_API Communication_API_Export #else - #define Communication_API Communication_API_Import +# define Communication_API Communication_API_Import #endif diff --git a/modules/communication/include/communication/ovCMessaging.h b/modules/communication/include/communication/ovCMessaging.h index 60982cd28654b11d15263c6d68a9b905669d9940..e2b17222a20a1ebf825b256a8b163e276aae82db 100644 --- a/modules/communication/include/communication/ovCMessaging.h +++ b/modules/communication/include/communication/ovCMessaging.h @@ -5,320 +5,319 @@ #include "defines.h" #include "ovCMessagingProtocol.h" -namespace Communication +namespace Communication { +/** + * \brief The purpose of this class is to provide a communication protocol to exchange EBML between a client and a server. + */ +class Communication_API CMessaging { +public: + /** - * \brief The purpose of this class is to provide a communication protocol to exchange EBML between a client and a server. + * \brief Library error codes */ - class Communication_API CMessaging + enum ELibraryError { - public: - - /** - * \brief Library error codes - */ - enum ELibraryError - { - NoError = 0, - Socket_NotConnected = 1, - Socket_FailedToConnect = 2, - Socket_ReceiveBufferFail = 3, - Socket_SendBufferFail = 4, - Socket_NoIncomingClientConnection = 6, - Socket_NotReadyToSend = 7, - Socket_NoDataReceived = 8, - Socket_FailedCloseClientConnection = 10, - Socket_FailedToCloseConnection = 11, - Socket_FailedConnectClient = 12, - Socket_ClientAlreadyConnected = 13, - Deserialize_BufferTooSmall = 30, - Deserialize_Header = 31, - Deserialize_ProtocolVersionMessage = 32, - Deserialize_BoxDescriptionMessage = 33, - Deserialize_EBMLMessage = 34, - Deserialize_EndMessage = 35, - Deserialize_ErrorMessage = 36, - Deserialize_LogMessage = 37, - Deserialize_AuthenticationMessage = 38, - Deserialize_MessageTypeNotSupported = 39, - BoxDescriptionAlreadyReceived = 60, - BoxDescriptionNotReceived = 61, - BadAuthenticationReceived = 70, - NoAuthenticationReceived = 71, - ThreadJoinFailed = 80 - }; - - CMessaging(); - virtual ~CMessaging(); - - /** - * \brief Get the code of the last error produced by the API - * - * \retval Error code - */ - ELibraryError getLastError() const; - - /** - * \brief Give a short description of an error. - * - * \param error the error code - * - * \return Description of the error. - */ - static std::string getErrorString(ELibraryError error); - - /** - * \brief Check that the socket is connected. - * - * \retval True if the socket is connected. - * \retval False if the socket is not connected. - */ - bool isConnected() const; - - /** - * \brief Check that the synchronization is in error state. - * - * \retval True if the synchronization is in error state. - * \retval False if the synchronization is ok. - */ - bool isInErrorState() const; - - /** - * \brief Set the connection ID to a new value - * \param connectionID The connection Id to set - */ - void setConnectionID(const std::string& connectionID) const; - - /** - * \brief Check that a End message was received. - * - * \retval True if the end message from the client is received. - * \retval False if the end message from the client is not received. - */ - virtual bool isEndReceived(); - - /** - * \brief Get the time. - */ - virtual uint64_t getTime(); - - protected: - - /** - * \brief Push a message to the send buffer. - * The message will be really sent in the socket in the next synchronization. - * - * \param message The message to send. - * - * \retval True if it succeeds. - * \retval False if library is in error state. - */ - bool pushMessage(const Message& message) const; - - /** - * \brief Set the last error code. - * - * \param libraryError The error - * - * \sa getLastError - */ - void setLastError(ELibraryError libraryError) const; - - /** - * \brief Provide the connection to the base class to communicate. - * - * \param connection The connection - */ - void setConnection(Socket::IConnection* connection) const; - - /** - * \brief Start a thread that will push the outgoing data, pull and process the incoming data. - * This sync will be stopped in cases: - * - An error raised - * - stopSyncing() function was called. - * - * \retval True if it succeeds. - * \retval False if an error occured. - * - * \sa stopSyncing - */ - bool startSyncing(); - - /** - * \brief Request to stop the sync and stop the thread. - * - * \retval True if it succeeds. - * \retval False if an error occured. - * - * \sa startSyncing - */ - bool stopSyncing() const; - - /** - * @brief Get the oldest authentication message - * @param id[out] Identifier of the message - * @param connectionID[out] Connection Id - * @return true if a message was popped, false if the queue is empty - */ - virtual bool popAuthentication(uint64_t& id, std::string& connectionID); - - /** - * @brief Get the oldest box description message - * @param id[out] Identifier of the message - * @param boxDescription[out] Descriptor of the box - * @return true if a message was popped, false if the queue is empty - */ - virtual bool popBoxDescriptions(uint64_t& id, BoxDescriptionMessage& boxDescription); - - /** - * @brief popCommunicationProtocolVersion - * @param id[out] Identifier of the message - * @param majorVersion[out] major version of the protocol - * @param minorVersion[out] minor version of the protocol - * @return true if a message was popped, false if the queue is empty - */ - virtual bool popCommunicationProtocolVersion(uint64_t& id, uint8_t& majorVersion, uint8_t& minorVersion); - - /** - * @brief Pop the oldest EBML message from the queue - * @param id[out] Identifier of the message - * @param index[out] Input index to which the EBML should be directed - * @param startTime[out] Start time of the buffer - * @param endTime[out] End time of the buffer - * @param ebml[out] The encoded EBML buffer - * @return true if a message was popped, false if the queue is empty - */ - virtual bool popEBML(uint64_t& id, size_t& index, uint64_t& startTime, uint64_t& endTime, std::shared_ptr<const std::vector<uint8_t>>& ebml); - - /** - * @brief Pop the oldest log message from the queue - * @param id[out] Identifier of the message - * @param type[out] Log level of the message - * @param message[out] Message text - * @return true if a message was popped, false if the queue is empty - */ - virtual bool popLog(uint64_t& id, ELogLevel& type, std::string& message); - - /** - * @brief Pop the oldest error message from the queue - * @param id[out] Identifier of the message - * @param type[out] Error code - * @param guiltyId[out] If of the sent message that caused this error - * @return true if a message was popped, false if the queue is empty - */ - virtual bool popError(uint64_t& id, EError& type, uint64_t& guiltyId); - - /** - * @brief Get the oldes End message - * @param id[out] Identifier of the message - * @return true if a message was popped, false if the queue is empty - */ - virtual bool popEnd(uint64_t& id); - - /** - * @brief Reset the library state. Stop sending and receiving buffers, disconnect - * and empty all buffers. - */ - void reset() const; - - /** - * \brief Checks if a sync message was received and reset it if it was. - * - * This method should be used in a busy loop to check if the other - * party has finished processing all of the data. - * - * From the external program standpoint this method will return true - * when the box has finished sending all of the data that has to be - * processed in one bulk. - * - * From the box standpoint, this means that the external program has - * finished processing and sending all of the data that the box has - * sent. - * - * \retval True if a sync message is received. - * \retval False if no sync message was received. - */ - virtual bool waitForSyncMessage(); - - private: - - /** - * \brief Receive all the available data from the socket and insert it in the rcv buffer. - * - * \retval True if it succeeds. - * \retval False if an error occured. - * Library errors: TODO - * - * \sa push - */ - bool pull() const; - - /** - * \brief Send all the data to the socket. - * - * \retval True if it succeeds. - * \retval False if an error occured. - * Library errors: - * - Socket_NotConnected - * - * - * \sa push - */ - bool push() const; - - /** - * \brief Process incoming data, unpack it and put messages in queues. - * It use processBuffer. - * - * \retval True if it succeeds. - * \retval False if an error occured. - * Library errors: Error from processBuffer - * - * \sa processBuffer - */ - bool processIncomingMessages() const; - - /** - * \brief Process buffer, pack it and put messages in queues. - * - * \param buffer Buffer with the incoming serialized data. - * \param[out] byteRead Number of bytes read and processed. - * - * \retval True if it succeeds. - * \retval False if an error occured. - * Library errors: - * - Deserialize_Header - * - Deserialize_AuthenticationMessage - * - Deserialize_ProtocolVersionMessage - * - Deserialize_BoxDescriptionMessage - * - Deserialize_EBMLMessage - * - Deserialize_LogMessage - * - Deserialize_ErrorMessage - * - Deserialize_MessageTypeNotSupported - * - * \sa processIncomingMessages - */ - bool processBuffer(const std::vector<uint8_t>& buffer, size_t& byteRead) const; - - /** - * \brief Sync fucntion that is used in a thread to pull, push and process the incoming data. - * - * \retval True if it succeeds. - * \retval False if an error occured. - * Library errors: Errors from processIncomingMessages(), push() or pull() - * - * \sa pull - * \sa push - * \sa processIncomingMessages - */ - void sync() const; - - public: - static const uint8_t s_CommunicationProtocol_MajorVersion = 1; - static const uint8_t s_CommunicationProtocol_MinorVersion = 1; - - protected: - struct SMessagingImpl; - SMessagingImpl* impl = nullptr; + NoError = 0, + Socket_NotConnected = 1, + Socket_FailedToConnect = 2, + Socket_ReceiveBufferFail = 3, + Socket_SendBufferFail = 4, + Socket_NoIncomingClientConnection = 6, + Socket_NotReadyToSend = 7, + Socket_NoDataReceived = 8, + Socket_FailedCloseClientConnection = 10, + Socket_FailedToCloseConnection = 11, + Socket_FailedConnectClient = 12, + Socket_ClientAlreadyConnected = 13, + Deserialize_BufferTooSmall = 30, + Deserialize_Header = 31, + Deserialize_ProtocolVersionMessage = 32, + Deserialize_BoxDescriptionMessage = 33, + Deserialize_EBMLMessage = 34, + Deserialize_EndMessage = 35, + Deserialize_ErrorMessage = 36, + Deserialize_LogMessage = 37, + Deserialize_AuthenticationMessage = 38, + Deserialize_MessageTypeNotSupported = 39, + BoxDescriptionAlreadyReceived = 60, + BoxDescriptionNotReceived = 61, + BadAuthenticationReceived = 70, + NoAuthenticationReceived = 71, + ThreadJoinFailed = 80 }; + + CMessaging(); + virtual ~CMessaging(); + + /** + * \brief Get the code of the last error produced by the API + * + * \retval Error code + */ + ELibraryError getLastError() const; + + /** + * \brief Give a short description of an error. + * + * \param error the error code + * + * \return Description of the error. + */ + static std::string getErrorString(ELibraryError error); + + /** + * \brief Check that the socket is connected. + * + * \retval True if the socket is connected. + * \retval False if the socket is not connected. + */ + bool isConnected() const; + + /** + * \brief Check that the synchronization is in error state. + * + * \retval True if the synchronization is in error state. + * \retval False if the synchronization is ok. + */ + bool isInErrorState() const; + + /** + * \brief Set the connection ID to a new value + * \param connectionID The connection Id to set + */ + void setConnectionID(const std::string& connectionID) const; + + /** + * \brief Check that a End message was received. + * + * \retval True if the end message from the client is received. + * \retval False if the end message from the client is not received. + */ + virtual bool isEndReceived(); + + /** + * \brief Get the time. + */ + virtual uint64_t getTime(); + +protected: + + /** + * \brief Push a message to the send buffer. + * The message will be really sent in the socket in the next synchronization. + * + * \param message The message to send. + * + * \retval True if it succeeds. + * \retval False if library is in error state. + */ + bool pushMessage(const Message& message) const; + + /** + * \brief Set the last error code. + * + * \param libraryError The error + * + * \sa getLastError + */ + void setLastError(ELibraryError libraryError) const; + + /** + * \brief Provide the connection to the base class to communicate. + * + * \param connection The connection + */ + void setConnection(Socket::IConnection* connection) const; + + /** + * \brief Start a thread that will push the outgoing data, pull and process the incoming data. + * This sync will be stopped in cases: + * - An error raised + * - stopSyncing() function was called. + * + * \retval True if it succeeds. + * \retval False if an error occured. + * + * \sa stopSyncing + */ + bool startSyncing(); + + /** + * \brief Request to stop the sync and stop the thread. + * + * \retval True if it succeeds. + * \retval False if an error occured. + * + * \sa startSyncing + */ + bool stopSyncing() const; + + /** + * @brief Get the oldest authentication message + * @param id[out] Identifier of the message + * @param connectionID[out] Connection Id + * @return true if a message was popped, false if the queue is empty + */ + virtual bool popAuthentication(uint64_t& id, std::string& connectionID); + + /** + * @brief Get the oldest box description message + * @param id[out] Identifier of the message + * @param boxDescription[out] Descriptor of the box + * @return true if a message was popped, false if the queue is empty + */ + virtual bool popBoxDescriptions(uint64_t& id, BoxDescriptionMessage& boxDescription); + + /** + * @brief popCommunicationProtocolVersion + * @param id[out] Identifier of the message + * @param majorVersion[out] major version of the protocol + * @param minorVersion[out] minor version of the protocol + * @return true if a message was popped, false if the queue is empty + */ + virtual bool popCommunicationProtocolVersion(uint64_t& id, uint8_t& majorVersion, uint8_t& minorVersion); + + /** + * @brief Pop the oldest EBML message from the queue + * @param id[out] Identifier of the message + * @param index[out] Input index to which the EBML should be directed + * @param startTime[out] Start time of the buffer + * @param endTime[out] End time of the buffer + * @param ebml[out] The encoded EBML buffer + * @return true if a message was popped, false if the queue is empty + */ + virtual bool popEBML(uint64_t& id, size_t& index, uint64_t& startTime, uint64_t& endTime, std::shared_ptr<const std::vector<uint8_t>>& ebml); + + /** + * @brief Pop the oldest log message from the queue + * @param id[out] Identifier of the message + * @param type[out] Log level of the message + * @param message[out] Message text + * @return true if a message was popped, false if the queue is empty + */ + virtual bool popLog(uint64_t& id, ELogLevel& type, std::string& message); + + /** + * @brief Pop the oldest error message from the queue + * @param id[out] Identifier of the message + * @param type[out] Error code + * @param guiltyId[out] If of the sent message that caused this error + * @return true if a message was popped, false if the queue is empty + */ + virtual bool popError(uint64_t& id, EError& type, uint64_t& guiltyId); + + /** + * @brief Get the oldes End message + * @param id[out] Identifier of the message + * @return true if a message was popped, false if the queue is empty + */ + virtual bool popEnd(uint64_t& id); + + /** + * @brief Reset the library state. Stop sending and receiving buffers, disconnect + * and empty all buffers. + */ + void reset() const; + + /** + * \brief Checks if a sync message was received and reset it if it was. + * + * This method should be used in a busy loop to check if the other + * party has finished processing all of the data. + * + * From the external program standpoint this method will return true + * when the box has finished sending all of the data that has to be + * processed in one bulk. + * + * From the box standpoint, this means that the external program has + * finished processing and sending all of the data that the box has + * sent. + * + * \retval True if a sync message is received. + * \retval False if no sync message was received. + */ + virtual bool waitForSyncMessage(); + +private: + + /** + * \brief Receive all the available data from the socket and insert it in the rcv buffer. + * + * \retval True if it succeeds. + * \retval False if an error occured. + * Library errors: TODO + * + * \sa push + */ + bool pull() const; + + /** + * \brief Send all the data to the socket. + * + * \retval True if it succeeds. + * \retval False if an error occured. + * Library errors: + * - Socket_NotConnected + * + * + * \sa push + */ + bool push() const; + + /** + * \brief Process incoming data, unpack it and put messages in queues. + * It use processBuffer. + * + * \retval True if it succeeds. + * \retval False if an error occured. + * Library errors: Error from processBuffer + * + * \sa processBuffer + */ + bool processIncomingMessages() const; + + /** + * \brief Process buffer, pack it and put messages in queues. + * + * \param buffer Buffer with the incoming serialized data. + * \param[out] byteRead Number of bytes read and processed. + * + * \retval True if it succeeds. + * \retval False if an error occured. + * Library errors: + * - Deserialize_Header + * - Deserialize_AuthenticationMessage + * - Deserialize_ProtocolVersionMessage + * - Deserialize_BoxDescriptionMessage + * - Deserialize_EBMLMessage + * - Deserialize_LogMessage + * - Deserialize_ErrorMessage + * - Deserialize_MessageTypeNotSupported + * + * \sa processIncomingMessages + */ + bool processBuffer(const std::vector<uint8_t>& buffer, size_t& byteRead) const; + + /** + * \brief Sync fucntion that is used in a thread to pull, push and process the incoming data. + * + * \retval True if it succeeds. + * \retval False if an error occured. + * Library errors: Errors from processIncomingMessages(), push() or pull() + * + * \sa pull + * \sa push + * \sa processIncomingMessages + */ + void sync() const; + +public: + static const uint8_t s_CommunicationProtocol_MajorVersion = 1; + static const uint8_t s_CommunicationProtocol_MinorVersion = 1; + +protected: + struct SMessagingImpl; + SMessagingImpl* impl = nullptr; +}; } // namespace Communication diff --git a/modules/communication/include/communication/ovCMessagingClient.h b/modules/communication/include/communication/ovCMessagingClient.h index f2702fb0cb73d898fb55e8beeabf4cb9f49d5c7c..54430c5cfe519822dc3689e97544da5a5aa411ec 100644 --- a/modules/communication/include/communication/ovCMessagingClient.h +++ b/modules/communication/include/communication/ovCMessagingClient.h @@ -5,216 +5,214 @@ #include "socket/IConnectionClient.h" -namespace Communication +namespace Communication { +class Communication_API MessagingClient : public CMessaging { - class Communication_API MessagingClient : public CMessaging - { - public: - - /** - * \brief Default constructor. - */ - MessagingClient(); - - /** - * \brief Destructor. - */ - ~MessagingClient() override; - - /** - * \brief Connect to a server. - * - * \param uri URI of the server. - * \param port The port. - * - * \retval True if it succeeds. - * \retval False there is no available error. - * Library errors: - * - FailedToConnect - * - NotConnected - * - NotReadyToSend - * - * \sa close - */ - bool connect(const std::string& uri, const size_t port); - - /** - * \brief Closes the connection to the server. - * - * \retval True if it succeeds. - * \retval False there is no available error. - * Library errors: - * - NotConnected - * - FailedToCloseConnection - * - * \sa getLastError - */ - bool close() const; - - /** - * \brief Return the number of box information's parameters available. - * - * \return The number of parameters available. - * - * \sa getParameter - */ - size_t getParameterCount() const; - - /** - * \brief Return the number of box information's input available. - * - * \return The number of input available. - * - * \sa getInput - */ - size_t getInputCount() const; - - /** - * \brief Return the number of output of the box information, available. - * - * \return The number of output available. - * - * \sa getOutput - */ - size_t getOutputCount() const; - - /** - * \brief Get parameter information. - * - * \param i The index. - * \param[out] id The id - * \param[out] type The type (corresponding to the OpenViBE CIdentifier) - * \param[out] name Name - * \param[out] value Value (to convert accordinf to the type) - * - * \retval True if it succeeds. - * \retval False if the index is out of range. - */ - bool getParameter(size_t i, uint64_t& id, uint64_t& type, std::string& name, std::string& value) const; - - /** - * \brief Get input information. - * - * \param i The index. - * \param[out] id The id - * \param[out] type The type (corresponding to the OpenViBE CIdentifier) - * \param[out] name Name - * - * \retval True if it succeeds. - * \retval False if the index is out of range. - * - * \sa getInputCount - */ - bool getInput(size_t i, uint64_t& id, uint64_t& type, std::string& name) const; - - /** - * \brief Get input information. - * - * \param i The index. - * \param[out] id The id - * \param[out] type The type (corresponding to the OpenViBE CIdentifier) - * \param[out] name Name - * - * \retval True if it succeeds. - * \retval False if the index is out of range. - * - * \sa getOutputCount - */ - bool getOutput(size_t i, uint64_t& id, uint64_t& type, std::string& name) const; - - /** - * \brief Get the oldest error message, if available. - * - * \param packetId - * \param[out] type The error's type. - * \param[out] guiltyId Identifier of the guilty message - * - * \retval True if it succeeds. - * \retval False there is no available error. - */ - bool popError(uint64_t& packetId, EError& type, uint64_t& guiltyId) override; - - /** - * \brief Get the oldest EBML message, if available. - * - * \param packetId - * \param[out] index Box input index. - * \param[out] startTime The start time. - * \param[out] endTime The end time. - * \param[out] ebml The EBML vector. - * - * \retval True if it succeeds. - * \retval False there is no available error. - */ - bool popEBML(uint64_t& packetId, size_t& index, uint64_t& startTime, uint64_t& endTime, std::shared_ptr<const std::vector<uint8_t>>& ebml) override; - - /** - * \brief Push a log message to the server. - * - * \param logLevel The log level. - * \param log The log string message. - * - * \retval True if it succeeds. - * \retval False there is no available error. - * Library errors: - * - NotConnected - * - NotReadyToSend - * - * \sa getLastError - */ - bool pushLog(ELogLevel logLevel, const std::string& log) const; - - /** - * \brief Pushes an ebml. - * - * \param index Index of the box output. - * \param startTime The start time. - * \param endTime The endtime. - * \param ebml The ebml vector. - * - * \retval True if it succeeds. - * \retval False there is no available error. - * Library errors: - * - NotConnected - * - NotReadyToSend - * - * \sa getLastError - */ - bool pushEBML(size_t index, uint64_t startTime, uint64_t endTime, const std::shared_ptr<const std::vector<uint8_t>>& ebml) const; - - /** - * \brief Push Sync message to the server. - * - * \retval True if it succeeds. - * \retval False if the library is in error state. - */ - bool pushSync() const; - - /** - * \brief Check if a sync message is received. - * - * \retval True if a sync message is received. - * \retval False if no sync message was received. - */ - bool waitForSyncMessage() override; - - private: - - /** - * \brief Pushes an authentication message). - * - * \param connectionID The connection identifier. - * - * \retval True if it succeeds. - * \retval False there is no available error. - * Library errors: - * - NotConnected - * - NotReadyToSend - */ - bool pushAuthentication(const std::string& connectionID) const; - - Socket::IConnectionClient* m_Client = nullptr; - - bool m_BoxDescriptionReceived = false; - }; +public: + + /** + * \brief Default constructor. + */ + MessagingClient(); + + /** + * \brief Destructor. + */ + ~MessagingClient() override; + + /** + * \brief Connect to a server. + * + * \param uri URI of the server. + * \param port The port. + * + * \retval True if it succeeds. + * \retval False there is no available error. + * Library errors: + * - FailedToConnect + * - NotConnected + * - NotReadyToSend + * + * \sa close + */ + bool connect(const std::string& uri, const size_t port); + + /** + * \brief Closes the connection to the server. + * + * \retval True if it succeeds. + * \retval False there is no available error. + * Library errors: + * - NotConnected + * - FailedToCloseConnection + * + * \sa getLastError + */ + bool close() const; + + /** + * \brief Return the number of box information's parameters available. + * + * \return The number of parameters available. + * + * \sa getParameter + */ + size_t getParameterCount() const; + + /** + * \brief Return the number of box information's input available. + * + * \return The number of input available. + * + * \sa getInput + */ + size_t getInputCount() const; + + /** + * \brief Return the number of output of the box information, available. + * + * \return The number of output available. + * + * \sa getOutput + */ + size_t getOutputCount() const; + + /** + * \brief Get parameter information. + * + * \param i The index. + * \param[out] id The id + * \param[out] type The type (corresponding to the OpenViBE CIdentifier) + * \param[out] name Name + * \param[out] value Value (to convert accordinf to the type) + * + * \retval True if it succeeds. + * \retval False if the index is out of range. + */ + bool getParameter(size_t i, uint64_t& id, uint64_t& type, std::string& name, std::string& value) const; + + /** + * \brief Get input information. + * + * \param i The index. + * \param[out] id The id + * \param[out] type The type (corresponding to the OpenViBE CIdentifier) + * \param[out] name Name + * + * \retval True if it succeeds. + * \retval False if the index is out of range. + * + * \sa getInputCount + */ + bool getInput(size_t i, uint64_t& id, uint64_t& type, std::string& name) const; + + /** + * \brief Get input information. + * + * \param i The index. + * \param[out] id The id + * \param[out] type The type (corresponding to the OpenViBE CIdentifier) + * \param[out] name Name + * + * \retval True if it succeeds. + * \retval False if the index is out of range. + * + * \sa getOutputCount + */ + bool getOutput(size_t i, uint64_t& id, uint64_t& type, std::string& name) const; + + /** + * \brief Get the oldest error message, if available. + * + * \param packetId + * \param[out] type The error's type. + * \param[out] guiltyId Identifier of the guilty message + * + * \retval True if it succeeds. + * \retval False there is no available error. + */ + bool popError(uint64_t& packetId, EError& type, uint64_t& guiltyId) override; + + /** + * \brief Get the oldest EBML message, if available. + * + * \param packetId + * \param[out] index Box input index. + * \param[out] startTime The start time. + * \param[out] endTime The end time. + * \param[out] ebml The EBML vector. + * + * \retval True if it succeeds. + * \retval False there is no available error. + */ + bool popEBML(uint64_t& packetId, size_t& index, uint64_t& startTime, uint64_t& endTime, std::shared_ptr<const std::vector<uint8_t>>& ebml) override; + + /** + * \brief Push a log message to the server. + * + * \param logLevel The log level. + * \param log The log string message. + * + * \retval True if it succeeds. + * \retval False there is no available error. + * Library errors: + * - NotConnected + * - NotReadyToSend + * + * \sa getLastError + */ + bool pushLog(ELogLevel logLevel, const std::string& log) const; + + /** + * \brief Pushes an ebml. + * + * \param index Index of the box output. + * \param startTime The start time. + * \param endTime The endtime. + * \param ebml The ebml vector. + * + * \retval True if it succeeds. + * \retval False there is no available error. + * Library errors: + * - NotConnected + * - NotReadyToSend + * + * \sa getLastError + */ + bool pushEBML(size_t index, uint64_t startTime, uint64_t endTime, const std::shared_ptr<const std::vector<uint8_t>>& ebml) const; + + /** + * \brief Push Sync message to the server. + * + * \retval True if it succeeds. + * \retval False if the library is in error state. + */ + bool pushSync() const; + + /** + * \brief Check if a sync message is received. + * + * \retval True if a sync message is received. + * \retval False if no sync message was received. + */ + bool waitForSyncMessage() override; + +private: + + /** + * \brief Pushes an authentication message). + * + * \param connectionID The connection identifier. + * + * \retval True if it succeeds. + * \retval False there is no available error. + * Library errors: + * - NotConnected + * - NotReadyToSend + */ + bool pushAuthentication(const std::string& connectionID) const; + + Socket::IConnectionClient* m_Client = nullptr; + bool m_BoxDescriptionReceived = false; +}; } // namespace Communication diff --git a/modules/communication/include/communication/ovCMessagingProtocol.h b/modules/communication/include/communication/ovCMessagingProtocol.h index 0c7b71a8f842aafe90149449a7a080ffd1563c5b..69c6f48506766be6735514c368f0c0497d00614a 100644 --- a/modules/communication/include/communication/ovCMessagingProtocol.h +++ b/modules/communication/include/communication/ovCMessagingProtocol.h @@ -8,418 +8,417 @@ #include <string> #include <limits> -namespace Communication +namespace Communication { +/** + * \brief Log level used by the client to log information in the server side + */ +enum ELogLevel : uint8_t { - /** - * \brief Log level used by the client to log information in the server side - */ - enum ELogLevel : uint8_t - { - LogLevel_Info = 1, - LogLevel_Warning = 2, - LogLevel_Error = 3, - LogLevel_Fatal = 4, - LogLevel_Max = 5, - LogLevel_Unknown = 0xFF - }; - - /** - * \brief Values that represent errors. - */ - enum EError : uint16_t - { - Error_AuthenticationFail = 1, - Error_AuthenticationRequested = 2, - Error_InvalidOutputIndex = 3, - Error_BadCommunicationProtocol = 4, - Error_InvalidEBML = 5, - Error_InvalidLogLevel = 6, - Error_InvalidMessageType = 7, - Error_BadMessage = 8, - Error_Max = 9, - Error_Unknown = 0xFF - }; - - /** - * \brief Message type - */ - enum EMessageType : uint8_t - { - MessageType_Authentication = 0, - MessageType_ProtocolVersion = 1, - MessageType_BoxInformation = 2, - MessageType_EBML = 3, - MessageType_Log = 4, - MessageType_End = 5, - MessageType_Error = 6, - MessageType_Time = 7, - MessageType_Sync = 8, - MessageType_Max = 9, - - MessageType_Unknown = 0xFF, - }; - - /** - * \brief A packet part is a part of a packet compound by an Header and a Message. - */ - class Communication_API CPacketPart - { - public: - - virtual ~CPacketPart() {} - - /** - * \brief Provide array of bytes that represent the object. - * - * \return A vector with the serialized information of the message that respect the communication protocol. - * - * \sa fromBytes - */ - virtual std::vector<uint8_t> toBytes() const = 0; - - /** - * \brief Transform bytes vector into an object. - * - * \param buffer The buffer. - * \param [in,out] bufferIndex Zero-based index of the buffer. - * - * \retval True if it succeeds - * \retval False if it fails. - * - * \sa toBytes - */ - virtual bool fromBytes(const std::vector<uint8_t>& buffer, size_t& bufferIndex) = 0; - - /** - * \brief Query if this object is valid. - * - * \retval True if it is valid. - * \retval False if it is invalid. - */ - bool isValid() const { return m_isValid; } - - protected: - bool m_isValid = false; - }; - - /** - * \brief A message is the second part of a packet after the header. - */ - class Message : public CPacketPart - { - public: - virtual EMessageType getMessageType() const = 0; - }; - - /** - * \brief A header is associated to a message. It give information about the message, like the type and the size. - */ - class Header final : CPacketPart - { - public: - Header(); - Header(EMessageType type, uint64_t id, size_t size); - std::vector<uint8_t> toBytes() const override; - void setId(const uint64_t id) { m_id = id; } - uint64_t getId() const { return m_id; } - EMessageType getType() const { return m_type; } - size_t getSize() const { return m_size; } - bool fromBytes(const std::vector<uint8_t>& buffer, size_t& bufferIndex) override; - - private: - EMessageType m_type; - uint64_t m_id = 0; - size_t m_size = 0; - - static const size_t TYPE_SIZE = sizeof(EMessageType); - static const size_t ID_SIZE = sizeof(uint64_t); - static const size_t SIZE_SIZE = sizeof(size_t); - static const size_t TYPE_INDEX = 0; - static const size_t ID_INDEX = TYPE_INDEX + TYPE_SIZE; - static const size_t SIZE_INDEX = ID_INDEX + ID_SIZE; - static const size_t MINIMUM_SIZE = TYPE_SIZE + ID_SIZE + SIZE_SIZE; - }; - - /** - * \brief Represent an Authentication message. - */ - class AuthenticationMessage final : public Message - { - public: - AuthenticationMessage() { m_isValid = false; } - AuthenticationMessage(const std::string& connectionID) : m_connectionID(connectionID) { m_isValid = true; } - std::vector<uint8_t> toBytes() const override; - bool fromBytes(const std::vector<uint8_t>& buffer, size_t& bufferIndex) override; - EMessageType getMessageType() const override { return MessageType_Authentication; } - std::string getConnectionID() const { return m_connectionID; } - - private: - static const size_t SIZE_SIZE = sizeof(size_t); - static const size_t SIZE_INDEX = 0; - static const size_t CONNECTION_ID_INDEX = SIZE_INDEX + SIZE_SIZE; - static const size_t MINIMUM_SIZE = SIZE_SIZE; - - std::string m_connectionID; - }; - - /** - * \brief This message is used to inform the server or the client about the current communication protocol version used. - */ - class CommunicationProtocolVersionMessage final : public Message - { - public: - - CommunicationProtocolVersionMessage() { m_isValid = false; } - - CommunicationProtocolVersionMessage(const uint8_t majorVersion, const uint8_t minorVersion) : m_minorVersion(minorVersion), m_majorVersion(majorVersion) - { - m_isValid = true; - } - - std::vector<uint8_t> toBytes() const override; - bool fromBytes(const std::vector<uint8_t>& buffer, size_t& bufferIndex) override; - EMessageType getMessageType() const override { return MessageType_ProtocolVersion; } - uint8_t getMajorVersion() const { return m_majorVersion; } - uint8_t getMinorVersion() const { return m_minorVersion; } - - private: - uint8_t m_minorVersion = 0; - uint8_t m_majorVersion = 0; - - static const size_t MAJOR_SIZE = sizeof(uint8_t); - static const size_t MINOR_SIZE = sizeof(uint8_t); - static const size_t MAJOR_INDEX = 0; - static const size_t MINOR_INDEX = MAJOR_INDEX + MAJOR_SIZE; - static const size_t MINIMUM_SIZE = MAJOR_SIZE + MINOR_SIZE; - }; - - /** - * \brief InputOutput class describes the input or output of a box. - */ - class InputOutput final : public CPacketPart - { - public: - InputOutput(); - InputOutput(uint64_t id, size_t type, const std::string& name); - std::vector<uint8_t> toBytes() const override; - bool fromBytes(const std::vector<uint8_t>& buffer, size_t& bufferIndex) override; - uint64_t getId() const { return m_id; } - size_t getType() const { return m_type; } - std::string getName() const { return m_name; } - - private: - uint64_t m_id = 0; - size_t m_type = 0; - std::string m_name; - - static const size_t ID_SIZE = sizeof(uint64_t); - static const size_t TYPE_SIZE = sizeof(size_t); - static const size_t NAME_SIZE_SIZE = sizeof(size_t); - static const size_t ID_INDEX = 0; - static const size_t TYPE_INDEX = ID_INDEX + ID_SIZE; - static const size_t NAME_SIZE_INDEX = TYPE_INDEX + TYPE_SIZE; - static const size_t NAME_INDEX = NAME_SIZE_INDEX + NAME_SIZE_SIZE; - static const size_t MINIMUM_SIZE = ID_SIZE + TYPE_SIZE + NAME_SIZE_SIZE; - }; - - class Parameter final : public CPacketPart - { - public: - Parameter(); - Parameter(uint64_t id, size_t type, const std::string& name, const std::string& value); - std::vector<uint8_t> toBytes() const override; - bool fromBytes(const std::vector<uint8_t>& buffer, size_t& bufferIndex) override; - - uint64_t getId() const { return m_id; } - size_t getType() const { return m_type; } - std::string getName() const { return m_name; } - std::string getValue() const { return m_value; } - - private: - uint64_t m_id = 0; - size_t m_type = 0; - std::string m_name; - std::string m_value; - - static const size_t ID_SIZE = sizeof(uint64_t); - static const size_t TYPE_SIZE = sizeof(size_t); - static const size_t NAME_SIZE_SIZE = sizeof(size_t); - static const size_t VALUE_SIZE_SIZE = sizeof(size_t); - static const size_t ID_INDEX = 0; - static const size_t TYPE_INDEX = ID_INDEX + ID_SIZE; - static const size_t NAME_SIZE_INDEX = TYPE_INDEX + TYPE_SIZE; - static const size_t VALUE_SIZE_INDEX = NAME_SIZE_INDEX + NAME_SIZE_SIZE; - static const size_t NAME_INDEX = VALUE_SIZE_INDEX + VALUE_SIZE_SIZE; - static const size_t MINIMUM_SIZE = ID_SIZE + TYPE_SIZE + NAME_SIZE_SIZE + VALUE_SIZE_SIZE; - }; - - /** - * \brief This message contains information about the box used in the NeuroRT pipeline. - * This message is sent by the server and received by the client. - */ - class BoxDescriptionMessage final : public Message - { - public: - std::vector<uint8_t> toBytes() const override; - bool fromBytes(const std::vector<uint8_t>& buffer, size_t& bufferIndex) override; - EMessageType getMessageType() const override; - bool addInput(uint64_t id, size_t type, const std::string& name); - bool addOutput(uint64_t id, size_t type, const std::string& name); - bool addParameter(uint64_t id, size_t type, const std::string& name, const std::string& value); - - const std::vector<InputOutput>* getInputs() const { return &m_inputs; } - const std::vector<InputOutput>* getOutputs() const { return &m_outputs; } - const std::vector<Parameter>* getParameters() const { return &m_parameters; } - - private: - std::vector<InputOutput> m_inputs; - std::vector<InputOutput> m_outputs; - std::vector<Parameter> m_parameters; - - static const size_t N_INPUT_SIZE = sizeof(size_t); - static const size_t N_OUTPUT_SIZE = sizeof(size_t); - static const size_t N_PARAMETER_SIZE = sizeof(size_t); - static const size_t N_INPUT_INDEX = 0; - static const size_t N_OUTPUT_INDEX = N_INPUT_INDEX + N_INPUT_SIZE; - static const size_t N_PARAMETER_INDEX = N_OUTPUT_INDEX + N_OUTPUT_SIZE; - static const size_t MINIMUM_SIZE = N_INPUT_SIZE + N_OUTPUT_SIZE + N_PARAMETER_SIZE; - }; - - /** - * \brief Log message is a way to communicate information from the client to the server. - */ - class LogMessage final : public Message - { - public: - LogMessage(); - LogMessage(ELogLevel type, const std::string& message); - std::vector<uint8_t> toBytes() const override; - bool fromBytes(const std::vector<uint8_t>& buffer, size_t& bufferIndex) override; - - EMessageType getMessageType() const override { return MessageType_Log; } - ELogLevel getType() const { return m_type; } - std::string getMessage() const { return m_message; } - - private: - ELogLevel m_type; - std::string m_message; - - static const size_t TYPE_SIZE = sizeof(ELogLevel); - static const size_t SIZE_SIZE = sizeof(size_t); - static const size_t TYPE_INDEX = 0; - static const size_t SIZE_INDEX = TYPE_INDEX + TYPE_SIZE; - static const size_t NAME_INDEX = SIZE_INDEX + SIZE_SIZE; - static const size_t MINIMUM_SIZE = TYPE_SIZE + SIZE_SIZE; - }; - - /** - * \brief EBML message is used to send EBML data. - */ - class EBMLMessage final : public Message - { - public: - EBMLMessage(); - - EBMLMessage(size_t index, uint64_t startTime, uint64_t endTime, const std::shared_ptr<const std::vector<uint8_t>>& ebml); - - std::vector<uint8_t> toBytes() const override; - - bool fromBytes(const std::vector<uint8_t>& buffer, size_t& bufferIndex) override; - - EMessageType getMessageType() const override { return MessageType_EBML; } - size_t getIndex() const { return m_ioIdx; } - uint64_t getStartTime() const { return m_startTime; } - uint64_t getEndTime() const { return m_endTime; } - std::shared_ptr<const std::vector<uint8_t>> getEBML() const { return m_EBML; } - - private: - size_t m_ioIdx = 0; - uint64_t m_startTime = 0; - uint64_t m_endTime = 0; - - std::shared_ptr<const std::vector<uint8_t>> m_EBML; + LogLevel_Info = 1, + LogLevel_Warning = 2, + LogLevel_Error = 3, + LogLevel_Fatal = 4, + LogLevel_Max = 5, + LogLevel_Unknown = 0xFF +}; + +/** + * \brief Values that represent errors. + */ +enum EError : uint16_t +{ + Error_AuthenticationFail = 1, + Error_AuthenticationRequested = 2, + Error_InvalidOutputIndex = 3, + Error_BadCommunicationProtocol = 4, + Error_InvalidEBML = 5, + Error_InvalidLogLevel = 6, + Error_InvalidMessageType = 7, + Error_BadMessage = 8, + Error_Max = 9, + Error_Unknown = 0xFF +}; + +/** + * \brief Message type + */ +enum EMessageType : uint8_t +{ + MessageType_Authentication = 0, + MessageType_ProtocolVersion = 1, + MessageType_BoxInformation = 2, + MessageType_EBML = 3, + MessageType_Log = 4, + MessageType_End = 5, + MessageType_Error = 6, + MessageType_Time = 7, + MessageType_Sync = 8, + MessageType_Max = 9, + + MessageType_Unknown = 0xFF, +}; + +/** + * \brief A packet part is a part of a packet compound by an Header and a Message. + */ +class Communication_API CPacketPart +{ +public: - static const size_t IO_INDEX_SIZE = sizeof(size_t); - static const size_t START_TIME_SIZE = sizeof(uint64_t); - static const size_t END_TIME_SIZE = sizeof(uint64_t); - static const size_t SIZE_SIZE = sizeof(size_t); - static const size_t IO_INDEX_INDEX = 0; - static const size_t START_TIME_INDEX = IO_INDEX_INDEX + IO_INDEX_SIZE; - static const size_t END_TIME_INDEX = START_TIME_INDEX + START_TIME_SIZE; - static const size_t SIZE_INDEX = END_TIME_INDEX + END_TIME_SIZE; - static const size_t EBML_INDEX = SIZE_INDEX + SIZE_SIZE; - static const size_t MINIMUM_SIZE = IO_INDEX_SIZE + START_TIME_SIZE + END_TIME_SIZE + SIZE_SIZE; - }; + virtual ~CPacketPart() {} /** - * \brief Error message is used to alert the client that the server raise an error due to a message by the client. + * \brief Provide array of bytes that represent the object. + * + * \return A vector with the serialized information of the message that respect the communication protocol. + * + * \sa fromBytes */ - class ErrorMessage final : public Message - { - public: - ErrorMessage() : m_type(Error_Unknown), m_guiltyId(std::numeric_limits<decltype(m_guiltyId)>::max()) {} - ErrorMessage(const EError error, const uint64_t guiltyId) : m_type(error), m_guiltyId(guiltyId) {} - - std::vector<uint8_t> toBytes() const override; - bool fromBytes(const std::vector<uint8_t>& buffer, size_t& bufferIndex) override; - - EMessageType getMessageType() const override { return MessageType_Error; } - EError getType() const { return m_type; } - uint64_t getGuiltyId() const { return m_guiltyId; } - - private: - EError m_type; - uint64_t m_guiltyId = 0; - - static const size_t TYPE_SIZE = sizeof(EError); - static const size_t GUILTY_ID_SIZE = sizeof(uint64_t); - static const size_t TYPE_INDEX = 0; - static const size_t GUILTY_ID_INDEX = TYPE_INDEX + TYPE_SIZE; - static const size_t MINIMUM_SIZE = GUILTY_ID_SIZE + TYPE_SIZE; - }; + virtual std::vector<uint8_t> toBytes() const = 0; /** - * \brief End message can be sent by the server or/and by the client to inform that the processing is stopped and the connection will be closed. + * \brief Transform bytes vector into an object. + * + * \param buffer The buffer. + * \param [in,out] bufferIndex Zero-based index of the buffer. + * + * \retval True if it succeeds + * \retval False if it fails. + * + * \sa toBytes */ - class EndMessage final : public Message - { - public: - EndMessage() {} - std::vector<uint8_t> toBytes() const override { return std::vector<uint8_t>(); } - bool fromBytes(const std::vector<uint8_t>& /*buffer*/, size_t& /*index*/) override { return false; } - EMessageType getMessageType() const override { return MessageType_End; } - }; + virtual bool fromBytes(const std::vector<uint8_t>& buffer, size_t& bufferIndex) = 0; /** - * \brief Time messages are only sent by the server to inform the client about the current time of the pipeline. + * \brief Query if this object is valid. + * + * \retval True if it is valid. + * \retval False if it is invalid. */ - class TimeMessage final : public Message - { - public: - TimeMessage(const uint64_t time = 0) : m_time(time) {} - std::vector<uint8_t> toBytes() const override; - bool fromBytes(const std::vector<uint8_t>& buffer, size_t& bufferIndex) override; + bool isValid() const { return m_isValid; } - EMessageType getMessageType() const override { return MessageType_Time; } - uint64_t getTime() const { return m_time; } +protected: + bool m_isValid = false; +}; - private: - uint64_t m_time = 0; +/** + * \brief A message is the second part of a packet after the header. + */ +class Message : public CPacketPart +{ +public: + virtual EMessageType getMessageType() const = 0; +}; + +/** + * \brief A header is associated to a message. It give information about the message, like the type and the size. + */ +class Header final : CPacketPart +{ +public: + Header(); + Header(EMessageType type, uint64_t id, size_t size); + std::vector<uint8_t> toBytes() const override; + void setId(const uint64_t id) { m_id = id; } + uint64_t getId() const { return m_id; } + EMessageType getType() const { return m_type; } + size_t getSize() const { return m_size; } + bool fromBytes(const std::vector<uint8_t>& buffer, size_t& bufferIndex) override; + +private: + EMessageType m_type; + uint64_t m_id = 0; + size_t m_size = 0; + + static const size_t TYPE_SIZE = sizeof(EMessageType); + static const size_t ID_SIZE = sizeof(uint64_t); + static const size_t SIZE_SIZE = sizeof(size_t); + static const size_t TYPE_INDEX = 0; + static const size_t ID_INDEX = TYPE_INDEX + TYPE_SIZE; + static const size_t SIZE_INDEX = ID_INDEX + ID_SIZE; + static const size_t MINIMUM_SIZE = TYPE_SIZE + ID_SIZE + SIZE_SIZE; +}; + +/** + * \brief Represent an Authentication message. + */ +class AuthenticationMessage final : public Message +{ +public: + AuthenticationMessage() { m_isValid = false; } + AuthenticationMessage(const std::string& connectionID) : m_connectionID(connectionID) { m_isValid = true; } + std::vector<uint8_t> toBytes() const override; + bool fromBytes(const std::vector<uint8_t>& buffer, size_t& bufferIndex) override; + EMessageType getMessageType() const override { return MessageType_Authentication; } + std::string getConnectionID() const { return m_connectionID; } + +private: + static const size_t SIZE_SIZE = sizeof(size_t); + static const size_t SIZE_INDEX = 0; + static const size_t CONNECTION_ID_INDEX = SIZE_INDEX + SIZE_SIZE; + static const size_t MINIMUM_SIZE = SIZE_SIZE; + + std::string m_connectionID; +}; + +/** + * \brief This message is used to inform the server or the client about the current communication protocol version used. + */ +class CommunicationProtocolVersionMessage final : public Message +{ +public: - static const size_t TIME_SIZE = sizeof(uint64_t); - static const size_t TIME_INDEX = 0; - static const size_t MINIMUM_SIZE = TIME_SIZE; - }; + CommunicationProtocolVersionMessage() { m_isValid = false; } - /** - * \brief Sync message can be sent by the server or/and by the client to inform that it's waiting the other part. - */ - class SyncMessage final : public Message + CommunicationProtocolVersionMessage(const uint8_t majorVersion, const uint8_t minorVersion) : m_minorVersion(minorVersion), m_majorVersion(majorVersion) { - public: - SyncMessage() {} - std::vector<uint8_t> toBytes() const override { return std::vector<uint8_t>(); } - bool fromBytes(const std::vector<uint8_t>& /*buffer*/, size_t& /*index*/) override { return false; } - EMessageType getMessageType() const override { return MessageType_Sync; } - }; + m_isValid = true; + } + + std::vector<uint8_t> toBytes() const override; + bool fromBytes(const std::vector<uint8_t>& buffer, size_t& bufferIndex) override; + EMessageType getMessageType() const override { return MessageType_ProtocolVersion; } + uint8_t getMajorVersion() const { return m_majorVersion; } + uint8_t getMinorVersion() const { return m_minorVersion; } + +private: + uint8_t m_minorVersion = 0; + uint8_t m_majorVersion = 0; + + static const size_t MAJOR_SIZE = sizeof(uint8_t); + static const size_t MINOR_SIZE = sizeof(uint8_t); + static const size_t MAJOR_INDEX = 0; + static const size_t MINOR_INDEX = MAJOR_INDEX + MAJOR_SIZE; + static const size_t MINIMUM_SIZE = MAJOR_SIZE + MINOR_SIZE; +}; + +/** + * \brief InputOutput class describes the input or output of a box. + */ +class InputOutput final : public CPacketPart +{ +public: + InputOutput(); + InputOutput(uint64_t id, size_t type, const std::string& name); + std::vector<uint8_t> toBytes() const override; + bool fromBytes(const std::vector<uint8_t>& buffer, size_t& bufferIndex) override; + uint64_t getId() const { return m_id; } + size_t getType() const { return m_type; } + std::string getName() const { return m_name; } + +private: + uint64_t m_id = 0; + size_t m_type = 0; + std::string m_name; + + static const size_t ID_SIZE = sizeof(uint64_t); + static const size_t TYPE_SIZE = sizeof(size_t); + static const size_t NAME_SIZE_SIZE = sizeof(size_t); + static const size_t ID_INDEX = 0; + static const size_t TYPE_INDEX = ID_INDEX + ID_SIZE; + static const size_t NAME_SIZE_INDEX = TYPE_INDEX + TYPE_SIZE; + static const size_t NAME_INDEX = NAME_SIZE_INDEX + NAME_SIZE_SIZE; + static const size_t MINIMUM_SIZE = ID_SIZE + TYPE_SIZE + NAME_SIZE_SIZE; +}; + +class Parameter final : public CPacketPart +{ +public: + Parameter(); + Parameter(uint64_t id, size_t type, const std::string& name, const std::string& value); + std::vector<uint8_t> toBytes() const override; + bool fromBytes(const std::vector<uint8_t>& buffer, size_t& bufferIndex) override; + + uint64_t getId() const { return m_id; } + size_t getType() const { return m_type; } + std::string getName() const { return m_name; } + std::string getValue() const { return m_value; } + +private: + uint64_t m_id = 0; + size_t m_type = 0; + std::string m_name; + std::string m_value; + + static const size_t ID_SIZE = sizeof(uint64_t); + static const size_t TYPE_SIZE = sizeof(size_t); + static const size_t NAME_SIZE_SIZE = sizeof(size_t); + static const size_t VALUE_SIZE_SIZE = sizeof(size_t); + static const size_t ID_INDEX = 0; + static const size_t TYPE_INDEX = ID_INDEX + ID_SIZE; + static const size_t NAME_SIZE_INDEX = TYPE_INDEX + TYPE_SIZE; + static const size_t VALUE_SIZE_INDEX = NAME_SIZE_INDEX + NAME_SIZE_SIZE; + static const size_t NAME_INDEX = VALUE_SIZE_INDEX + VALUE_SIZE_SIZE; + static const size_t MINIMUM_SIZE = ID_SIZE + TYPE_SIZE + NAME_SIZE_SIZE + VALUE_SIZE_SIZE; +}; + +/** + * \brief This message contains information about the box used in the NeuroRT pipeline. + * This message is sent by the server and received by the client. + */ +class BoxDescriptionMessage final : public Message +{ +public: + std::vector<uint8_t> toBytes() const override; + bool fromBytes(const std::vector<uint8_t>& buffer, size_t& bufferIndex) override; + EMessageType getMessageType() const override; + bool addInput(uint64_t id, size_t type, const std::string& name); + bool addOutput(uint64_t id, size_t type, const std::string& name); + bool addParameter(uint64_t id, size_t type, const std::string& name, const std::string& value); + + const std::vector<InputOutput>* getInputs() const { return &m_inputs; } + const std::vector<InputOutput>* getOutputs() const { return &m_outputs; } + const std::vector<Parameter>* getParameters() const { return &m_parameters; } + +private: + std::vector<InputOutput> m_inputs; + std::vector<InputOutput> m_outputs; + std::vector<Parameter> m_parameters; + + static const size_t N_INPUT_SIZE = sizeof(size_t); + static const size_t N_OUTPUT_SIZE = sizeof(size_t); + static const size_t N_PARAMETER_SIZE = sizeof(size_t); + static const size_t N_INPUT_INDEX = 0; + static const size_t N_OUTPUT_INDEX = N_INPUT_INDEX + N_INPUT_SIZE; + static const size_t N_PARAMETER_INDEX = N_OUTPUT_INDEX + N_OUTPUT_SIZE; + static const size_t MINIMUM_SIZE = N_INPUT_SIZE + N_OUTPUT_SIZE + N_PARAMETER_SIZE; +}; + +/** + * \brief Log message is a way to communicate information from the client to the server. + */ +class LogMessage final : public Message +{ +public: + LogMessage(); + LogMessage(ELogLevel type, const std::string& message); + std::vector<uint8_t> toBytes() const override; + bool fromBytes(const std::vector<uint8_t>& buffer, size_t& bufferIndex) override; + + EMessageType getMessageType() const override { return MessageType_Log; } + ELogLevel getType() const { return m_type; } + std::string getMessage() const { return m_message; } + +private: + ELogLevel m_type; + std::string m_message; + + static const size_t TYPE_SIZE = sizeof(ELogLevel); + static const size_t SIZE_SIZE = sizeof(size_t); + static const size_t TYPE_INDEX = 0; + static const size_t SIZE_INDEX = TYPE_INDEX + TYPE_SIZE; + static const size_t NAME_INDEX = SIZE_INDEX + SIZE_SIZE; + static const size_t MINIMUM_SIZE = TYPE_SIZE + SIZE_SIZE; +}; + +/** + * \brief EBML message is used to send EBML data. + */ +class EBMLMessage final : public Message +{ +public: + EBMLMessage(); + + EBMLMessage(size_t index, uint64_t startTime, uint64_t endTime, const std::shared_ptr<const std::vector<uint8_t>>& ebml); + + std::vector<uint8_t> toBytes() const override; + + bool fromBytes(const std::vector<uint8_t>& buffer, size_t& bufferIndex) override; + + EMessageType getMessageType() const override { return MessageType_EBML; } + size_t getIndex() const { return m_ioIdx; } + uint64_t getStartTime() const { return m_startTime; } + uint64_t getEndTime() const { return m_endTime; } + std::shared_ptr<const std::vector<uint8_t>> getEBML() const { return m_EBML; } + +private: + size_t m_ioIdx = 0; + uint64_t m_startTime = 0; + uint64_t m_endTime = 0; + + std::shared_ptr<const std::vector<uint8_t>> m_EBML; + + static const size_t IO_INDEX_SIZE = sizeof(size_t); + static const size_t START_TIME_SIZE = sizeof(uint64_t); + static const size_t END_TIME_SIZE = sizeof(uint64_t); + static const size_t SIZE_SIZE = sizeof(size_t); + static const size_t IO_INDEX_INDEX = 0; + static const size_t START_TIME_INDEX = IO_INDEX_INDEX + IO_INDEX_SIZE; + static const size_t END_TIME_INDEX = START_TIME_INDEX + START_TIME_SIZE; + static const size_t SIZE_INDEX = END_TIME_INDEX + END_TIME_SIZE; + static const size_t EBML_INDEX = SIZE_INDEX + SIZE_SIZE; + static const size_t MINIMUM_SIZE = IO_INDEX_SIZE + START_TIME_SIZE + END_TIME_SIZE + SIZE_SIZE; +}; + +/** + * \brief Error message is used to alert the client that the server raise an error due to a message by the client. + */ +class ErrorMessage final : public Message +{ +public: + ErrorMessage() : m_type(Error_Unknown), m_guiltyId(std::numeric_limits<decltype(m_guiltyId)>::max()) {} + ErrorMessage(const EError error, const uint64_t guiltyId) : m_type(error), m_guiltyId(guiltyId) {} + + std::vector<uint8_t> toBytes() const override; + bool fromBytes(const std::vector<uint8_t>& buffer, size_t& bufferIndex) override; + + EMessageType getMessageType() const override { return MessageType_Error; } + EError getType() const { return m_type; } + uint64_t getGuiltyId() const { return m_guiltyId; } + +private: + EError m_type; + uint64_t m_guiltyId = 0; + + static const size_t TYPE_SIZE = sizeof(EError); + static const size_t GUILTY_ID_SIZE = sizeof(uint64_t); + static const size_t TYPE_INDEX = 0; + static const size_t GUILTY_ID_INDEX = TYPE_INDEX + TYPE_SIZE; + static const size_t MINIMUM_SIZE = GUILTY_ID_SIZE + TYPE_SIZE; +}; + +/** + * \brief End message can be sent by the server or/and by the client to inform that the processing is stopped and the connection will be closed. + */ +class EndMessage final : public Message +{ +public: + EndMessage() {} + std::vector<uint8_t> toBytes() const override { return std::vector<uint8_t>(); } + bool fromBytes(const std::vector<uint8_t>& /*buffer*/, size_t& /*index*/) override { return false; } + EMessageType getMessageType() const override { return MessageType_End; } +}; + +/** + * \brief Time messages are only sent by the server to inform the client about the current time of the pipeline. + */ +class TimeMessage final : public Message +{ +public: + TimeMessage(const uint64_t time = 0) : m_time(time) {} + std::vector<uint8_t> toBytes() const override; + bool fromBytes(const std::vector<uint8_t>& buffer, size_t& bufferIndex) override; + + EMessageType getMessageType() const override { return MessageType_Time; } + uint64_t getTime() const { return m_time; } + +private: + uint64_t m_time = 0; + + static const size_t TIME_SIZE = sizeof(uint64_t); + static const size_t TIME_INDEX = 0; + static const size_t MINIMUM_SIZE = TIME_SIZE; +}; + +/** + * \brief Sync message can be sent by the server or/and by the client to inform that it's waiting the other part. + */ +class SyncMessage final : public Message +{ +public: + SyncMessage() {} + std::vector<uint8_t> toBytes() const override { return std::vector<uint8_t>(); } + bool fromBytes(const std::vector<uint8_t>& /*buffer*/, size_t& /*index*/) override { return false; } + EMessageType getMessageType() const override { return MessageType_Sync; } +}; } // namespace Communication diff --git a/modules/communication/include/communication/ovCMessagingServer.h b/modules/communication/include/communication/ovCMessagingServer.h index e9f1b48510c4eaacc6609acb12dbdc8e3926bf17..768cc0eabcc47f75f3ab3430a23603bdaf0ec0b2 100644 --- a/modules/communication/include/communication/ovCMessagingServer.h +++ b/modules/communication/include/communication/ovCMessagingServer.h @@ -5,182 +5,181 @@ #include "socket/IConnectionServer.h" -namespace Communication +namespace Communication { +class Communication_API MessagingServer : public CMessaging { - class Communication_API MessagingServer : public CMessaging - { - public: - - /** - * \brief Default constructor. - */ - MessagingServer() : CMessaging(), m_Server(Socket::createConnectionServer()) {} - - /** - * \brief Destructor. - */ - ~MessagingServer() override; - - /** - * \brief Start listening on the given port. - * - * \param port The port. - * - * \retval True if listenning - * \retval False if not. - * - * \sa close - */ - bool listen(const size_t port) const { return m_Server->listen(port); } - - /** - * \brief Close the connection - * * - * \retval True if it succeeds - * \retval False if it fails. - */ - bool close(); - - /** - * \brief Accepts one incoming connection. - * - * \retval True if it succeeds. - * \retval False if it fails. - */ - bool accept(); - - /** - * \brief Returns the port on the one the server is listening. - * This is useful if you set the port to '0'. - * \param port [out]: port on the one the server is listening - */ - bool getSocketPort(size_t& port) const { return m_Server->getSocketPort(port); } - - - /** - * \brief Adds a parameter in the Box Information. - * - * \param id The parameter's identifier. - * \param type The parameter's type. Use OpenViBE::CIdentifier. - * \param name The parameter's name. - * \param value The parameter's value. A string. - * - * \retval True if it succeeds. - * \retval False if an output with the given id already exists. - * - * \sa addInput - * \sa addOutput - */ - bool addParameter(uint64_t id, size_t type, const std::string& name, const std::string& value) const; - - /** - * \brief Adds an input in the box Information. - * - * \param id The input's identifier. - * \param type The input's type. Use OpenViBE::CIdentifier. - * \param name The input's name. - * - * \retval True if it succeeds. - * \retval False if an output with the given id already exists. - * - * \sa addParameter - * \sa addOutput - */ - bool addInput(uint64_t id, size_t type, const std::string& name) const; - - /** - * \brief Adds an output in the box information. - * - * \param id The output's identifier. - * \param type The output's type. Use OpenViBE::CIdentifier. - * \param name The output's name. - * - * \retval True if it succeeds. - * \retval False if an output with the given id already exists. - * - * \sa addParameter - * \sa addInput - */ - bool addOutput(uint64_t id, size_t type, const std::string& name) const; - - /** - * \brief Get the log message received from the client. - * - * \param[out] packetId Packet id - * \param[out] type Level of the log - * \param[out] message Log message - * - * \retval True if it succeeds. - * \retval False if the library is in error state. - */ - bool popLog(uint64_t& packetId, ELogLevel& type, std::string& message) override; - - /** - * \brief Get the EBML data received from the client. - * - * \param[out] packetId Packet id - * \param[out] index Output index - * \param[out] startTime Chunk time in OpenViBE 32:32 format - * \param[out] endTime Chunk time in OpenViBE 32:32 format - * \param[out] ebml EBML data - * - * \retval True if it succeeds. - * \retval False if the library is in error state. - */ - bool popEBML(uint64_t& packetId, size_t& index, uint64_t& startTime, uint64_t& endTime, std::shared_ptr<const std::vector<uint8_t>>& ebml) override; - - /** - * \brief Push Error message to the client - * - * \param error Error code - * \param guiltyId Id of the received message that raised the error. - * - * \retval True if it succeeds. - * \retval False if the library is in error state. - */ - bool pushError(EError error, uint64_t guiltyId) const; - - /** - * \brief Push EBML message to the client - * - * \param index Index of the input. - * \param startTime Chunk time in OpenViBE 32:32 format - * \param endTime Chunk time in OpenViBE 32:32 format - * \param ebml EBML data - * - * \retval True if it succeeds. - * \retval False if the library is in error state. - */ - bool pushEBML(size_t index, uint64_t startTime, uint64_t endTime, const std::shared_ptr<const std::vector<uint8_t>>& ebml) const; - - /** - * \brief Push Time message to the client - * - * \param time Time in OpenViBE 32:32 format - * - * \retval True if it succeeds. - * \retval False if the library is in error state. - */ - bool pushTime(uint64_t time) { return this->pushMessage(TimeMessage(time)); } - - /** - * \brief Push Sync message to the client - * - * \retval True if it succeeds. +public: + + /** + * \brief Default constructor. + */ + MessagingServer() : CMessaging(), m_Server(Socket::createConnectionServer()) {} + + /** + * \brief Destructor. + */ + ~MessagingServer() override; + + /** + * \brief Start listening on the given port. + * + * \param port The port. + * + * \retval True if listenning + * \retval False if not. + * + * \sa close + */ + bool listen(const size_t port) const { return m_Server->listen(port); } + + /** + * \brief Close the connection + * * + * \retval True if it succeeds + * \retval False if it fails. + */ + bool close(); + + /** + * \brief Accepts one incoming connection. + * + * \retval True if it succeeds. + * \retval False if it fails. + */ + bool accept(); + + /** + * \brief Returns the port on the one the server is listening. + * This is useful if you set the port to '0'. + * \param port [out]: port on the one the server is listening + */ + bool getSocketPort(size_t& port) const { return m_Server->getSocketPort(port); } + + + /** + * \brief Adds a parameter in the Box Information. + * + * \param id The parameter's identifier. + * \param type The parameter's type. Use OpenViBE::CIdentifier. + * \param name The parameter's name. + * \param value The parameter's value. A string. + * + * \retval True if it succeeds. + * \retval False if an output with the given id already exists. + * + * \sa addInput + * \sa addOutput + */ + bool addParameter(uint64_t id, size_t type, const std::string& name, const std::string& value) const; + + /** + * \brief Adds an input in the box Information. + * + * \param id The input's identifier. + * \param type The input's type. Use OpenViBE::CIdentifier. + * \param name The input's name. + * + * \retval True if it succeeds. + * \retval False if an output with the given id already exists. + * + * \sa addParameter + * \sa addOutput + */ + bool addInput(uint64_t id, size_t type, const std::string& name) const; + + /** + * \brief Adds an output in the box information. + * + * \param id The output's identifier. + * \param type The output's type. Use OpenViBE::CIdentifier. + * \param name The output's name. + * + * \retval True if it succeeds. + * \retval False if an output with the given id already exists. + * + * \sa addParameter + * \sa addInput + */ + bool addOutput(uint64_t id, size_t type, const std::string& name) const; + + /** + * \brief Get the log message received from the client. + * + * \param[out] packetId Packet id + * \param[out] type Level of the log + * \param[out] message Log message + * + * \retval True if it succeeds. * \retval False if the library is in error state. - */ - bool pushSync() { return this->pushMessage(SyncMessage()); } - - /** - * \brief Check if a sync message is received. - * - * \retval True if a sync message is received. - * \retval False if no sync message was received. - */ - bool waitForSyncMessage() override { return CMessaging::waitForSyncMessage(); } - - private: - Socket::IConnectionServer* m_Server = nullptr; //< Server connection - Socket::IConnection* m_Client = nullptr; - }; + */ + bool popLog(uint64_t& packetId, ELogLevel& type, std::string& message) override; + + /** + * \brief Get the EBML data received from the client. + * + * \param[out] packetId Packet id + * \param[out] index Output index + * \param[out] startTime Chunk time in OpenViBE 32:32 format + * \param[out] endTime Chunk time in OpenViBE 32:32 format + * \param[out] ebml EBML data + * + * \retval True if it succeeds. + * \retval False if the library is in error state. + */ + bool popEBML(uint64_t& packetId, size_t& index, uint64_t& startTime, uint64_t& endTime, std::shared_ptr<const std::vector<uint8_t>>& ebml) override; + + /** + * \brief Push Error message to the client + * + * \param error Error code + * \param guiltyId Id of the received message that raised the error. + * + * \retval True if it succeeds. + * \retval False if the library is in error state. + */ + bool pushError(EError error, uint64_t guiltyId) const; + + /** + * \brief Push EBML message to the client + * + * \param index Index of the input. + * \param startTime Chunk time in OpenViBE 32:32 format + * \param endTime Chunk time in OpenViBE 32:32 format + * \param ebml EBML data + * + * \retval True if it succeeds. + * \retval False if the library is in error state. + */ + bool pushEBML(size_t index, uint64_t startTime, uint64_t endTime, const std::shared_ptr<const std::vector<uint8_t>>& ebml) const; + + /** + * \brief Push Time message to the client + * + * \param time Time in OpenViBE 32:32 format + * + * \retval True if it succeeds. + * \retval False if the library is in error state. + */ + bool pushTime(uint64_t time) { return this->pushMessage(TimeMessage(time)); } + + /** + * \brief Push Sync message to the client + * + * \retval True if it succeeds. + * \retval False if the library is in error state. + */ + bool pushSync() { return this->pushMessage(SyncMessage()); } + + /** + * \brief Check if a sync message is received. + * + * \retval True if a sync message is received. + * \retval False if no sync message was received. + */ + bool waitForSyncMessage() override { return CMessaging::waitForSyncMessage(); } + +private: + Socket::IConnectionServer* m_Server = nullptr; //< Server connection + Socket::IConnection* m_Client = nullptr; +}; } // namespace Communication diff --git a/modules/communication/src/ovCMessaging.cpp b/modules/communication/src/ovCMessaging.cpp index 8c588cf5ad6359be29eb587ca3ff914f95479402..27f5ceb126f6887388f9a30d6097962d8b10135d 100644 --- a/modules/communication/src/ovCMessaging.cpp +++ b/modules/communication/src/ovCMessaging.cpp @@ -13,38 +13,37 @@ using namespace Communication; -namespace +namespace { +const std::map<CMessaging::ELibraryError, std::string> ERRORS_STRING = { - const std::map<CMessaging::ELibraryError, std::string> ERRORS_STRING = - { - { CMessaging::NoError, "No error" }, - { CMessaging::Socket_NotConnected, "Not connected" }, - { CMessaging::Socket_FailedToConnect, "Failed to connect" }, - { CMessaging::Socket_ReceiveBufferFail, "Failed to receive the buffer" }, - { CMessaging::Socket_SendBufferFail, "Failed to send the buffer" }, - { CMessaging::Socket_NoIncomingClientConnection, "No incoming client connection before the timeout" }, - { CMessaging::Socket_NotReadyToSend, "Socket not ready to send the buffer" }, - { CMessaging::Socket_NoDataReceived, "No data received by the socket" }, - { CMessaging::Socket_FailedCloseClientConnection, "Failed to close the client connection" }, - { CMessaging::Socket_FailedToCloseConnection, "Failed to close the server connection" }, - { CMessaging::Socket_FailedConnectClient, "Failed to connect the client" }, - { CMessaging::Socket_ClientAlreadyConnected, "A client is already connected" }, - { CMessaging::Deserialize_BufferTooSmall, "Buffer received is too small to be unpacked" }, - { CMessaging::Deserialize_Header, "Fail to unpack the buffer to a Header" }, - { CMessaging::Deserialize_ProtocolVersionMessage, "Fail to unpack Protocol Version message" }, - { CMessaging::Deserialize_BoxDescriptionMessage, "Fail to unpack Box description message" }, - { CMessaging::Deserialize_EBMLMessage, "Fail to unpack EBML message" }, - { CMessaging::Deserialize_EndMessage, "Fail to unpack End message" }, - { CMessaging::Deserialize_ErrorMessage, "Fail to unpack error message" }, - { CMessaging::Deserialize_LogMessage, "Fail to unpack log message" }, - { CMessaging::Deserialize_AuthenticationMessage, "Fail to unpack Authentication message" }, - { CMessaging::Deserialize_MessageTypeNotSupported, "Message type not supported" }, - { CMessaging::BoxDescriptionAlreadyReceived, "Box Description already received" }, - { CMessaging::BoxDescriptionNotReceived, "Box description not received" }, - { CMessaging::BadAuthenticationReceived, "Authentication received is invalid" }, - { CMessaging::NoAuthenticationReceived, "No authentication received before the timeout" }, - { CMessaging::ThreadJoinFailed, "Failed to terminate the thread" } - }; + { CMessaging::NoError, "No error" }, + { CMessaging::Socket_NotConnected, "Not connected" }, + { CMessaging::Socket_FailedToConnect, "Failed to connect" }, + { CMessaging::Socket_ReceiveBufferFail, "Failed to receive the buffer" }, + { CMessaging::Socket_SendBufferFail, "Failed to send the buffer" }, + { CMessaging::Socket_NoIncomingClientConnection, "No incoming client connection before the timeout" }, + { CMessaging::Socket_NotReadyToSend, "Socket not ready to send the buffer" }, + { CMessaging::Socket_NoDataReceived, "No data received by the socket" }, + { CMessaging::Socket_FailedCloseClientConnection, "Failed to close the client connection" }, + { CMessaging::Socket_FailedToCloseConnection, "Failed to close the server connection" }, + { CMessaging::Socket_FailedConnectClient, "Failed to connect the client" }, + { CMessaging::Socket_ClientAlreadyConnected, "A client is already connected" }, + { CMessaging::Deserialize_BufferTooSmall, "Buffer received is too small to be unpacked" }, + { CMessaging::Deserialize_Header, "Fail to unpack the buffer to a Header" }, + { CMessaging::Deserialize_ProtocolVersionMessage, "Fail to unpack Protocol Version message" }, + { CMessaging::Deserialize_BoxDescriptionMessage, "Fail to unpack Box description message" }, + { CMessaging::Deserialize_EBMLMessage, "Fail to unpack EBML message" }, + { CMessaging::Deserialize_EndMessage, "Fail to unpack End message" }, + { CMessaging::Deserialize_ErrorMessage, "Fail to unpack error message" }, + { CMessaging::Deserialize_LogMessage, "Fail to unpack log message" }, + { CMessaging::Deserialize_AuthenticationMessage, "Fail to unpack Authentication message" }, + { CMessaging::Deserialize_MessageTypeNotSupported, "Message type not supported" }, + { CMessaging::BoxDescriptionAlreadyReceived, "Box Description already received" }, + { CMessaging::BoxDescriptionNotReceived, "Box description not received" }, + { CMessaging::BadAuthenticationReceived, "Authentication received is invalid" }, + { CMessaging::NoAuthenticationReceived, "No authentication received before the timeout" }, + { CMessaging::ThreadJoinFailed, "Failed to terminate the thread" } +}; } // namespace CMessaging::CMessaging() @@ -88,7 +87,6 @@ void CMessaging::reset() const } CMessaging::ELibraryError CMessaging::getLastError() const { return impl->m_LastLibraryError; } - void CMessaging::setLastError(const ELibraryError libraryError) const { impl->m_LastLibraryError = libraryError; } bool CMessaging::push() const diff --git a/modules/communication/src/ovCMessagingClient.cpp b/modules/communication/src/ovCMessagingClient.cpp index efa8a655f0e396569722a87213971ba10ff26377..a588d7890977f582c74ba6155559ac55d306de1e 100644 --- a/modules/communication/src/ovCMessagingClient.cpp +++ b/modules/communication/src/ovCMessagingClient.cpp @@ -85,21 +85,18 @@ bool MessagingClient::close() const size_t MessagingClient::getParameterCount() const { if (!m_BoxDescriptionReceived) { return 0; } - return impl->m_BoxDesc.getParameters()->size(); } size_t MessagingClient::getInputCount() const { if (!m_BoxDescriptionReceived) { return 0; } - return impl->m_BoxDesc.getInputs()->size(); } size_t MessagingClient::getOutputCount() const { if (!m_BoxDescriptionReceived) { return 0; } - return impl->m_BoxDesc.getOutputs()->size(); } @@ -161,7 +158,6 @@ bool MessagingClient::popEBML(uint64_t& packetId, size_t& index, uint64_t& start } bool MessagingClient::pushAuthentication(const std::string& connectionID) const { return this->pushMessage(AuthenticationMessage(connectionID)); } - bool MessagingClient::pushLog(const ELogLevel logLevel, const std::string& log) const { return this->pushMessage(LogMessage(logLevel, log)); } bool MessagingClient::pushEBML(const size_t index, const uint64_t startTime, const uint64_t endTime, @@ -171,5 +167,4 @@ bool MessagingClient::pushEBML(const size_t index, const uint64_t startTime, con } bool MessagingClient::pushSync() const { return this->pushMessage(SyncMessage()); } - bool MessagingClient::waitForSyncMessage() { return CMessaging::waitForSyncMessage(); } diff --git a/modules/communication/src/ovCMessagingImpl.hpp b/modules/communication/src/ovCMessagingImpl.hpp index 04397cadf050eccb4b222ba6bd88896615f9c61a..2d73d334a71984cd4087aef4e7a4265376fbda1b 100644 --- a/modules/communication/src/ovCMessagingImpl.hpp +++ b/modules/communication/src/ovCMessagingImpl.hpp @@ -12,55 +12,54 @@ #include <queue> #include <atomic> -namespace Communication +namespace Communication { +struct CMessaging::SMessagingImpl { - struct CMessaging::SMessagingImpl - { - std::string m_ConnectionID; - BoxDescriptionMessage m_BoxDesc; - std::atomic<uint64_t> m_Time; + std::string m_ConnectionID; + BoxDescriptionMessage m_BoxDesc; + std::atomic<uint64_t> m_Time; - uint64_t m_nMessage = 0; + uint64_t m_nMessage = 0; - std::mutex m_IncAuthMutex; - std::queue<std::pair<uint64_t, AuthenticationMessage>> m_IncomingAuthentications; + std::mutex m_IncAuthMutex; + std::queue<std::pair<uint64_t, AuthenticationMessage>> m_IncomingAuthentications; - std::mutex m_IncCommProVerMutex; - std::queue<std::pair<uint64_t, CommunicationProtocolVersionMessage>> m_IncomingCommunicationProtocolVersions; + std::mutex m_IncCommProVerMutex; + std::queue<std::pair<uint64_t, CommunicationProtocolVersionMessage>> m_IncomingCommunicationProtocolVersions; - std::mutex m_IncBoxDescriptionMutex; - std::queue<std::pair<uint64_t, BoxDescriptionMessage>> m_IncomingBoxDescriptions; + std::mutex m_IncBoxDescriptionMutex; + std::queue<std::pair<uint64_t, BoxDescriptionMessage>> m_IncomingBoxDescriptions; - std::mutex m_IncEBMLMutex; - std::queue<std::pair<uint64_t, EBMLMessage>> m_IncomingEBMLs; + std::mutex m_IncEBMLMutex; + std::queue<std::pair<uint64_t, EBMLMessage>> m_IncomingEBMLs; - std::mutex m_IncLogMutex; - std::queue<std::pair<uint64_t, LogMessage>> m_IncomingLogs; + std::mutex m_IncLogMutex; + std::queue<std::pair<uint64_t, LogMessage>> m_IncomingLogs; - std::mutex m_IncErrorsMutex; - std::queue<std::pair<uint64_t, ErrorMessage>> m_IncomingErrors; + std::mutex m_IncErrorsMutex; + std::queue<std::pair<uint64_t, ErrorMessage>> m_IncomingErrors; - std::mutex m_IncEndMutex; - std::queue<std::pair<uint64_t, EndMessage>> m_IncomingEnds; + std::mutex m_IncEndMutex; + std::queue<std::pair<uint64_t, EndMessage>> m_IncomingEnds; - static const size_t s_BufferSize = 1024 * 64; //< Empirical value + static const size_t s_BufferSize = 1024 * 64; //< Empirical value - std::vector<uint8_t> m_RcvBuffer; - std::array<uint8_t, s_BufferSize> m_TempRcvBuffer; + std::vector<uint8_t> m_RcvBuffer; + std::array<uint8_t, s_BufferSize> m_TempRcvBuffer; - std::mutex m_SendBufferMutex; - std::vector<uint8_t> m_SendBuffer; + std::mutex m_SendBufferMutex; + std::vector<uint8_t> m_SendBuffer; - Socket::IConnection* m_Connection = nullptr; + Socket::IConnection* m_Connection = nullptr; - mutable std::atomic<ELibraryError> m_LastLibraryError; + mutable std::atomic<ELibraryError> m_LastLibraryError; - std::thread m_SyncThread; + std::thread m_SyncThread; - std::atomic<bool> m_IsStopRequested; - std::atomic<bool> m_IsInErrorState; - std::atomic<bool> m_IsEndMessageReceived; + std::atomic<bool> m_IsStopRequested; + std::atomic<bool> m_IsInErrorState; + std::atomic<bool> m_IsEndMessageReceived; - std::atomic<bool> m_WasSyncMessageReceived; - }; + std::atomic<bool> m_WasSyncMessageReceived; +}; } // namespace Communication diff --git a/modules/communication/src/ovCMessagingProtocol.cpp b/modules/communication/src/ovCMessagingProtocol.cpp index 36349d4bf2a7c837f4d92550fb2e6d1a0045788e..ace86d00113d386779a57e48e0ca943018bee95a 100644 --- a/modules/communication/src/ovCMessagingProtocol.cpp +++ b/modules/communication/src/ovCMessagingProtocol.cpp @@ -7,82 +7,73 @@ using namespace Communication; -namespace +namespace { +/** + * \brief Copy a string to buffer + * + * \param [out] dest The buffer destination + * \param [out] bufferIndex The index of the buffer where the beginning of the string must be copied. + * \param value The string to copy. + * + * \retval True if it succeeds + * \retval False if it fails. + */ +bool copyTobuffer(std::vector<uint8_t>& dest, size_t& bufferIndex, const std::string& value) { - /** - * \brief Copy a string to buffer - * - * \param [out] dest The buffer destination - * \param [out] bufferIndex The index of the buffer where the beginning of the string must be copied. - * \param value The string to copy. - * - * \retval True if it succeeds - * \retval False if it fails. - */ - bool copyTobuffer(std::vector<uint8_t>& dest, size_t& bufferIndex, const std::string& value) - { - if (dest.size() < bufferIndex + value.size()) { return false; } - - memcpy(dest.data() + bufferIndex, value.data(), value.size()); - - bufferIndex += value.size(); - - return true; - } - - /** - * \brief Copy a value to a buffer. - * - * \param [out] dest Destination for the. - * \param [out] bufferIndex Zero-based index of the buffer. - * \param value The value. - * - * \return True if it succeeds, false if it fails. - */ - template <class T> - bool copyTobuffer(std::vector<uint8_t>& dest, size_t& bufferIndex, const T& value) - { - if (dest.size() < bufferIndex + sizeof(value)) { return false; } - - memcpy(dest.data() + bufferIndex, &value, sizeof(value)); - - bufferIndex += sizeof(value); - - return true; - } - - template <class T> - bool copyToVariable(const std::vector<uint8_t>& src, const size_t bufferIndex, T& destVariable) - { - if (src.size() < bufferIndex + sizeof(destVariable)) { return false; } + if (dest.size() < bufferIndex + value.size()) { return false; } + memcpy(dest.data() + bufferIndex, value.data(), value.size()); + bufferIndex += value.size(); + return true; +} - memcpy(&destVariable, src.data() + bufferIndex, sizeof(destVariable)); +/** + * \brief Copy a value to a buffer. + * + * \param [out] dest Destination for the. + * \param [out] bufferIndex Zero-based index of the buffer. + * \param value The value. + * + * \return True if it succeeds, false if it fails. + */ +template <class T> +bool copyTobuffer(std::vector<uint8_t>& dest, size_t& bufferIndex, const T& value) +{ + if (dest.size() < bufferIndex + sizeof(value)) { return false; } + memcpy(dest.data() + bufferIndex, &value, sizeof(value)); + bufferIndex += sizeof(value); + return true; +} - return true; - } +template <class T> +bool copyToVariable(const std::vector<uint8_t>& src, const size_t bufferIndex, T& destVariable) +{ + if (src.size() < bufferIndex + sizeof(destVariable)) { return false; } + memcpy(&destVariable, src.data() + bufferIndex, sizeof(destVariable)); + return true; +} - /** - * \brief Convert a buffer to a string - * - * \param src The buffer - * \param bufferIndex The index where to start the convertion. - * \param size The size of the string. - * \param [out] string The string. - * - * \retval True if it succeeds - * \retval False if it fails. - * - * \sa copyToVariable - */ - bool copyToString(const std::vector<uint8_t>& src, const size_t bufferIndex, const size_t size, std::string& string) - { - if (src.size() < bufferIndex + size) { return false; } +/** + * \brief Convert a buffer to a string + * + * \param src The buffer + * \param bufferIndex The index where to start the convertion. + * \param size The size of the string. + * \param [out] string The string. + * + * \retval True if it succeeds + * \retval False if it fails. + * + * \sa copyToVariable + */ +bool copyToString(const std::vector<uint8_t>& src, const size_t bufferIndex, const size_t size, std::string& string) +{ + if (src.size() < bufferIndex + size) { return false; } - string = std::string(src.begin() + static_cast<const long>(bufferIndex), - src.begin() + static_cast<const long>(bufferIndex) + static_cast<const long>(size)); + string = std::string(src.begin() + static_cast<const long>(bufferIndex), + src.begin() + static_cast<const long>(bufferIndex) + static_cast<const long>(size)); - return true; - } + return true; +} } // namespace /****************************************************************************** @@ -92,7 +83,6 @@ namespace ******************************************************************************/ Header::Header() : m_type(MessageType_Unknown), m_id(std::numeric_limits<decltype(m_id)>::max()) { m_isValid = false; } - Header::Header(const EMessageType type, const uint64_t id, const size_t size) : m_type(type), m_id(id), m_size(size) { m_isValid = true; } std::vector<uint8_t> Header::toBytes() const @@ -382,7 +372,6 @@ bool BoxDescriptionMessage::addInput(const uint64_t id, const size_t type, const { const auto it = std::find_if(m_inputs.begin(), m_inputs.end(), [&id](const InputOutput& obj) { return obj.getId() == id; }); if (it != m_inputs.end()) { return false; } - m_inputs.emplace_back(id, type, name); return true; } @@ -390,9 +379,7 @@ bool BoxDescriptionMessage::addInput(const uint64_t id, const size_t type, const bool BoxDescriptionMessage::addOutput(const uint64_t id, const size_t type, const std::string& name) { const auto it = std::find_if(m_outputs.begin(), m_outputs.end(), [&id](const InputOutput& obj) { return obj.getId() == id; }); - if (it != m_outputs.end()) { return false; } - m_outputs.emplace_back(id, type, name); return true; } @@ -400,9 +387,7 @@ bool BoxDescriptionMessage::addOutput(const uint64_t id, const size_t type, cons bool BoxDescriptionMessage::addParameter(const uint64_t id, const size_t type, const std::string& name, const std::string& value) { const auto it = std::find_if(m_parameters.begin(), m_parameters.end(), [&id](const Parameter& obj) { return obj.getId() == id; }); - if (it != m_parameters.end()) { return false; } - m_parameters.emplace_back(id, type, name, value); return true; } @@ -420,7 +405,6 @@ bool BoxDescriptionMessage::addParameter(const uint64_t id, const size_t type, c ******************************************************************************/ LogMessage::LogMessage() : m_type(LogLevel_Unknown) { m_isValid = false; } - LogMessage::LogMessage(const ELogLevel type, const std::string& message) : m_type(type), m_message(message) { m_isValid = true; } std::vector<uint8_t> LogMessage::toBytes() const @@ -571,7 +555,6 @@ bool TimeMessage::fromBytes(const std::vector<uint8_t>& buffer, size_t& bufferIn m_isValid = false; if (buffer.size() < bufferIndex + MINIMUM_SIZE) { return false; } - if (!copyToVariable(buffer, bufferIndex + TIME_INDEX, m_time)) { return false; } bufferIndex += MINIMUM_SIZE; diff --git a/modules/communication/src/ovCMessagingServer.cpp b/modules/communication/src/ovCMessagingServer.cpp index 1f5f1322de9a1d79007e1238b9b121947b203adb..d004471bce4d34df0bf798a0b24e332b9e3d5af4 100644 --- a/modules/communication/src/ovCMessagingServer.cpp +++ b/modules/communication/src/ovCMessagingServer.cpp @@ -131,12 +131,7 @@ bool MessagingServer::addParameter(const uint64_t id, const size_t type, const s } bool MessagingServer::addInput(const uint64_t id, const size_t type, const std::string& name) const { return impl->m_BoxDesc.addInput(id, type, name); } - -bool MessagingServer::addOutput(const uint64_t id, const size_t type, const std::string& name) const -{ - return impl->m_BoxDesc.addOutput(id, type, name); -} - +bool MessagingServer::addOutput(const uint64_t id, const size_t type, const std::string& name) const { return impl->m_BoxDesc.addOutput(id, type, name); } bool MessagingServer::popLog(uint64_t& packetId, ELogLevel& type, std::string& message) { return CMessaging::popLog(packetId, type, message); } bool MessagingServer::popEBML(uint64_t& packetId, size_t& index, uint64_t& startTime, uint64_t& endTime, std::shared_ptr<const std::vector<uint8_t>>& ebml) @@ -146,7 +141,7 @@ bool MessagingServer::popEBML(uint64_t& packetId, size_t& index, uint64_t& start bool MessagingServer::pushError(const EError error, const uint64_t guiltyId) const { return this->pushMessage(ErrorMessage(error, guiltyId)); } -bool MessagingServer::pushEBML(const size_t index, const uint64_t startTime, const uint64_t endTime, +bool MessagingServer::pushEBML(const size_t index, const uint64_t startTime, const uint64_t endTime, const std::shared_ptr<const std::vector<uint8_t>>& ebml) const { return this->pushMessage(EBMLMessage(index, startTime, endTime, ebml)); diff --git a/modules/csv/CMakeLists.txt b/modules/csv/CMakeLists.txt index 060301bf0ea9844a7c82e36e05bca042de275f27..cafb37367c1aceb6ff1357218332e2cd7200d0bc 100644 --- a/modules/csv/CMakeLists.txt +++ b/modules/csv/CMakeLists.txt @@ -13,12 +13,14 @@ ADD_LIBRARY(${PROJECT_NAME} SHARED ${SRC_FILES}) SET_TARGET_PROPERTIES(${PROJECT_NAME} PROPERTIES VERSION ${PROJECT_VERSION} SOVERSION ${PROJECT_VERSION_MAJOR} + FOLDER ${MODULES_FOLDER} COMPILE_FLAGS "-DCSV_Shared -DCSV_Exports") ADD_LIBRARY(${PROJECT_NAME}-static STATIC ${SRC_FILES}) SET_TARGET_PROPERTIES(${PROJECT_NAME}-static PROPERTIES VERSION ${PROJECT_VERSION} SOVERSION ${PROJECT_VERSION_MAJOR} + FOLDER ${MODULES_FOLDER} COMPILE_FLAGS "-DCSV_Static -DCSV_Exports") IF(UNIX) @@ -33,9 +35,7 @@ INCLUDE("FindThirdPartyBoost_FileSystem") # --------------------------------- # Target macros -# Defines target operating system -# Defines target architecture -# Defines target compiler +# Defines target operating system, architecture and compiler # --------------------------------- SET_BUILD_PLATFORM() diff --git a/modules/csv/include/csv/defines.h b/modules/csv/include/csv/defines.h index b9bf8b8ea3e27965cf04a451a27bf70d21012c3e..f379a11f379c6b2b80b2be35693c829b32320951 100644 --- a/modules/csv/include/csv/defines.h +++ b/modules/csv/include/csv/defines.h @@ -1,23 +1,23 @@ #pragma once #if defined CSV_Shared -#if defined TARGET_OS_Windows -#define CSV_API_Export __declspec(dllexport) -#define CSV_API_Import __declspec(dllimport) -#elif defined TARGET_OS_Linux || defined TARGET_OS_MacOS - #define CSV_API_Export __attribute__((visibility("default"))) - #define CSV_API_Import __attribute__((visibility("default"))) +# if defined TARGET_OS_Windows +# define CSV_API_Export __declspec(dllexport) +# define CSV_API_Import __declspec(dllimport) +# elif defined TARGET_OS_Linux || defined TARGET_OS_MacOS +# define CSV_API_Export __attribute__((visibility("default"))) +# define CSV_API_Import __attribute__((visibility("default"))) +# else +# define CSV_API_Export +# define CSV_API_Import +# endif #else - #define CSV_API_Export - #define CSV_API_Import -#endif -#else -#define CSV_API_Export -#define CSV_API_Import +# define CSV_API_Export +# define CSV_API_Import #endif #if defined CSV_Exports -#define CSV_API CSV_API_Export +# define CSV_API CSV_API_Export #else - #define CSV_API CSV_API_Import +# define CSV_API CSV_API_Import #endif diff --git a/modules/csv/src/ovCCSV.cpp b/modules/csv/src/ovCCSV.cpp index 588e3c59cde08beb7dd54b25aec401e8c1ffde66..3d3d66920c4e1619c35531825f8e4247e6bf50e3 100755 --- a/modules/csv/src/ovCCSV.cpp +++ b/modules/csv/src/ovCCSV.cpp @@ -49,28 +49,27 @@ using namespace OpenViBE; using namespace CSV; using namespace boost::spirit; -namespace -{ - const size_t SIGNAL_EPOCH_COL_IDX = 1; - const size_t TIME_COL_IDX = 0; - const size_t END_TIME_COL_IDX = 1; - const size_t N_PRE_DATA_COL = 2; // Number of columns before data (Time/Epoch) - const size_t N_POST_DATA_COL = 3; // Number of columns after data (Events) - - //Separators - const char SEPARATOR(','); - const char DATA_SEPARATOR(':'); - const char DIMENSION_SEPARATOR('x'); - - // Columns Names - const std::string EVENT_ID_COL = "Event Id"; - const std::string EVENT_DATE_COL = "Event Date"; - const std::string EVENT_DURATION_COL = "Event Duration"; - - const size_t CHAR_TO_READ = 1000; - //const size_t MAXIMUM_FLOAT_DECIMAL = 32; - - const char END_OF_LINE_CHAR('\n'); +namespace { +const size_t SIGNAL_EPOCH_COL_IDX = 1; +const size_t TIME_COL_IDX = 0; +const size_t END_TIME_COL_IDX = 1; +const size_t N_PRE_DATA_COL = 2; // Number of columns before data (Time/Epoch) +const size_t N_POST_DATA_COL = 3; // Number of columns after data (Events) + +//Separators +const char SEPARATOR(','); +const char DATA_SEPARATOR(':'); +const char DIMENSION_SEPARATOR('x'); + +// Columns Names +const std::string EVENT_ID_COL = "Event Id"; +const std::string EVENT_DATE_COL = "Event Date"; +const std::string EVENT_DURATION_COL = "Event Duration"; + +const size_t CHAR_TO_READ = 1000; +//const size_t MAXIMUM_FLOAT_DECIMAL = 32; + +const char END_OF_LINE_CHAR('\n'); } // namespace bool CCSVHandler::streamReader(std::istream& in, std::string& out, const char delimiter, std::string& bufferHistory) const @@ -1022,7 +1021,7 @@ std::string CCSVHandler::createHeaderString() } } while (this->increasePositionIndexes(position)); } - break; + break; case EStreamType::Spectrum: for (const std::string& label : m_dimLabels) @@ -1754,4 +1753,4 @@ bool CCSVHandler::calculateSampleCountPerBuffer() CSV_API ICSVHandler* CSV::createCSVHandler() { return new CCSVHandler(); } -CSV_API void CSV::releaseCSVHandler(ICSVHandler* object) { delete dynamic_cast<CCSVHandler *>(object); } +CSV_API void CSV::releaseCSVHandler(ICSVHandler* object) { delete dynamic_cast<CCSVHandler*>(object); } diff --git a/modules/csv/src/ovCCSV.hpp b/modules/csv/src/ovCCSV.hpp index a6d148b1460a41c760edf8985fa070d7004196b4..c09e29b1ec7bbfbf26d9752776db9448d8df702f 100755 --- a/modules/csv/src/ovCCSV.hpp +++ b/modules/csv/src/ovCCSV.hpp @@ -27,331 +27,329 @@ #include <string> #include <vector> -namespace OpenViBE +namespace OpenViBE { +namespace CSV { +class CCSVHandler final : public ICSVHandler { - namespace CSV - { - class CCSVHandler final : public ICSVHandler - { - public: - /** - * \brief Set lib value to default - */ - CCSVHandler() : m_inputTypeID(EStreamType::StreamedMatrix), m_dimSizes({}) {} - - /** - * \brief Close the file if it is open. - */ - ~CCSVHandler() override { this->closeFile(); } - - /** - * \brief Get the floating point precision used to write float values. - * - * \return the Floating point precision. - */ - size_t getOutputFloatPrecision() override { return m_oPrecision; } - - /** - * \brief Set the floating point precision used to write float values. - * - * \param precision the floating point precision. - */ - void setOutputFloatPrecision(const size_t precision) override { m_oPrecision = precision; } - - void setFormatType(const EStreamType typeID) override; - EStreamType getFormatType() override { return m_inputTypeID; } - - void setLastMatrixOnlyMode(const bool isActivated) override { m_lastMatrixOnly = isActivated; } - bool getLastMatrixOnlyMode() override { return m_lastMatrixOnly; } - - bool setSignalInformation(const std::vector<std::string>& channelNames, size_t sampling, size_t nSamplePerBuffer) override; - bool getSignalInformation(std::vector<std::string>& channelNames, size_t& sampling, size_t& nSamplePerBuffer) override; - - bool setSpectrumInformation(const std::vector<std::string>& channelNames, const std::vector<double>& frequencyAbscissa, size_t sampling) override; - bool getSpectrumInformation(std::vector<std::string>& channelNames, std::vector<double>& frequencyAbscissa, size_t& sampling) override; - - bool setFeatureVectorInformation(const std::vector<std::string>& channelNames) override; - bool getFeatureVectorInformation(std::vector<std::string>& channelNames) override; - - bool setStreamedMatrixInformation(const std::vector<size_t>& dimSizes, const std::vector<std::string>& labels) override; - bool getStreamedMatrixInformation(std::vector<size_t>& dimSizes, std::vector<std::string>& labels) override; - - /** - * \brief Write the header to the file - * - * \retval True in case of success. - * \retval False in case of error. - */ - bool writeHeaderToFile() override; - - /** - * \brief Write current available data to the file until the last stimulation or if you set that it will not have new event before a date. - * - * \retval True in case of success. - * \retval False in case of error. - * - * \sa noEventsUntilDate - */ - bool writeDataToFile() override; - - /** - * \brief Write current available data to the file. - * - * \retval True in case of success. - * \retval False in case of error. - */ - bool writeAllDataToFile() override; - - /** - * \brief Read samples and stimulations. - * - * \param lineNb Maximum number of lines to read. If there is no more data in the file, the number of lines read can be lower. - * \param chunks[out] Valid chunks read. - * \param stimulations[out] Valid stimulations read. - * - * \retval True in case of success, even if the number of lines is different than the lineNb parameter. - * \retval False in case of error. - */ - bool readSamplesAndEventsFromFile(size_t lineNb, std::vector<SMatrixChunk>& chunks, std::vector<SStimulationChunk>& stimulations) override; - - /** - * \brief Open a OV CSV file. - * - * \retval True in case of success. - * \retval False in case of error. - */ - bool openFile(const std::string& fileName, EFileAccessMode mode) override; - - /** - * \brief Close the opened file. - * - * \retval True in case of success. - * \retval False in case of error. - */ - bool closeFile() override; - - /** - * \brief Add a single sample. - * - * \retval True in case of success. - * \retval False in case of error. - */ - bool addSample(const SMatrixChunk& sample) override; - - /** - * \brief Add several samples. - * - * \retval True in case of success. - * \retval False in case of error. - */ - bool addBuffer(const std::vector<SMatrixChunk>& samples) override; - - /** - * \brief Add a single stimulation. - * - * \retval True in case of success. - * \retval False in case of error. - */ - bool addEvent(uint64_t code, double date, double duration) override; - - /** - * \brief Add several stimulations. - * - * \retval True in case of success. - * \retval False in case of error. - */ - bool addEvent(const SStimulationChunk& event) override; - - /** - * \brief Guarantee that will not have new event before a date. - * This information is used to allow the library to write all the chunks available, before this date, to a file. - * - * \retval True in case of success. - * \retval False in case of error. - * - * \sa writeDataToFile - */ - bool noEventsUntilDate(double date) override; - - ELogErrorCodes getLastLogError() override { return m_logError; } - - std::string getLastErrorString() override { return m_lastStringError; } - - /** - * \brief Check if there is still data to read in the file. - * - * \retval True if there is still data to read in the file. - * \retval False if there is no more data to read in the file. - */ - bool hasDataToRead() const override { return m_hasDataToRead; } - - private: - /** - * \brief Split a string into a vector of strings. - * - * \param in String to split. - * \param delimiter Delimitor. - * \param out[out] Vector of string. - */ - void split(const std::string& in, char delimiter, std::vector<std::string>& out) const; - - /** - * \brief Create a string with stimulations to add in the buffer. - * - * \param stimulationsToPrint stimulations to put into the buffer - * - * \return string with stimulations to write - */ - std::string stimulationsToString(const std::vector<SStimulationChunk>& stimulationsToPrint) const; - - /** - * \brief Create a string representation of the header data. - * - * \retval true Header data as it should be written in the file - * \retval "" in case of error - */ - std::string createHeaderString(); - - /** - * \brief Set the buffer in function of data saved. - * - * \param canWriteAll true if it must write all lines, false if it write only the next buffer - * \param csv The CSV string. - * - * \retval true in case of success - * \retval false in case of wrong data sent - */ - bool createCSVStringFromData(bool canWriteAll, std::string& csv); - - /** - * \brief Parsing header to read data. - * - * \retval true in case of correct header - * \retval false in case of incorrect header - */ - bool parseHeader(); - - /** - * \brief Parsing header to read signal data. - * - * \param header[out] - * - * \retval true in case of correct header - * \retval false in case of incorrect header - */ - bool parseSignalHeader(const std::vector<std::string>& header); - - /** - * \brief Parsing header to read Spectrum data. - * - * \param header[out] - * - * \retval true in case of correct header - * \retval false in case of incorrect header - */ - bool parseSpectrumHeader(const std::vector<std::string>& header); - - /** - * \brief Parsing header to read matrix data (Streamed Matrix, Covariance matrix and Feature Vector). - * - * \param header[out] - * - * \retval true in case of correct header - * \retval false in case of incorrect header - */ - bool parseMatrixHeader(const std::vector<std::string>& header); - - /** - * \brief Read line data concerning time, epoch and matrix. - * - * \param line line to read - * \param sample[out] reference to stock data in - * \param lineNb index of the read line - * - * \retval true in case of success - * \retval false in case of error (as letters instead of numbers) - */ - bool readSampleChunk(const std::string& line, SMatrixChunk& sample, size_t lineNb); - - /** - * \brief Read line data conerning stimulations. - * - * \param line the line to read - * \param stimulations[out] vector to stock stimulations in (identifier, date and duration) - * \param lineNb the line actually reading - * - * \retval true in case of success - * \retval false in case of error (as letters instead of numbers) - */ - bool readStimulationChunk(const std::string& line, std::vector<SStimulationChunk>& stimulations, size_t lineNb); - - /** - * \brief Update position into the matrix while reading or writing. - * - * \param position[out] is the position into the matrix - * - * \retval true in case of success - * \retval false in case of browse matrix - */ - bool increasePositionIndexes(std::vector<size_t>& position); - - /** - * \brief Read lines of the first epoch to found sample count per buffer. - * - * \retval true in case of success - * \retval false in case of error - */ - bool calculateSampleCountPerBuffer(); - - /** - * \brief Read a stream until a delimiter and provide the string before the delimiter. - * - * \param in The stream to read. - * \param out The string before the next delimitor. - * \param delimiter The delimiter . - * \param bufferHistory - */ - bool streamReader(std::istream& in, std::string& out, char delimiter, std::string& bufferHistory) const; - - std::fstream m_fs; - std::string m_filename; - std::deque<SMatrixChunk> m_chunks; - std::deque<SStimulationChunk> m_stimulations; - ELogErrorCodes m_logError = LogErrorCodes_NoError; - std::string m_lastStringError = ""; - - EStreamType m_inputTypeID; - - typedef std::istream& GetLine(std::istream& in, std::string& out, char delimiter); - size_t m_nDim = 0; - std::vector<size_t> m_dimSizes; - std::vector<std::string> m_dimLabels; - size_t m_nSamplePerBuffer = 0; - double m_noEventSince = 0; - - std::vector<double> m_frequencyAbscissa; - - size_t m_sampling = 0; - size_t m_nCol = 0; - - bool m_hasInputType = false; - bool m_isFirstLineWritten = false; - bool m_isHeaderRead = false; - bool m_isSetInfoCalled = false; - bool m_hasEpoch = false; - - size_t m_nSampleOriginal = 0; - size_t m_oPrecision = 10; - - bool m_lastMatrixOnly = false; - - std::string m_bufferReadFileLine; // Buffer used to store unused read chars. - - bool m_hasDataToRead = true; +public: + /** + * \brief Set lib value to default + */ + CCSVHandler() : m_inputTypeID(EStreamType::StreamedMatrix), m_dimSizes({}) {} + + /** + * \brief Close the file if it is open. + */ + ~CCSVHandler() override { this->closeFile(); } + + /** + * \brief Get the floating point precision used to write float values. + * + * \return the Floating point precision. + */ + size_t getOutputFloatPrecision() override { return m_oPrecision; } + + /** + * \brief Set the floating point precision used to write float values. + * + * \param precision the floating point precision. + */ + void setOutputFloatPrecision(const size_t precision) override { m_oPrecision = precision; } + + void setFormatType(const EStreamType typeID) override; + EStreamType getFormatType() override { return m_inputTypeID; } + + void setLastMatrixOnlyMode(const bool isActivated) override { m_lastMatrixOnly = isActivated; } + bool getLastMatrixOnlyMode() override { return m_lastMatrixOnly; } + + bool setSignalInformation(const std::vector<std::string>& channelNames, size_t sampling, size_t nSamplePerBuffer) override; + bool getSignalInformation(std::vector<std::string>& channelNames, size_t& sampling, size_t& nSamplePerBuffer) override; + + bool setSpectrumInformation(const std::vector<std::string>& channelNames, const std::vector<double>& frequencyAbscissa, size_t sampling) override; + bool getSpectrumInformation(std::vector<std::string>& channelNames, std::vector<double>& frequencyAbscissa, size_t& sampling) override; + + bool setFeatureVectorInformation(const std::vector<std::string>& channelNames) override; + bool getFeatureVectorInformation(std::vector<std::string>& channelNames) override; + + bool setStreamedMatrixInformation(const std::vector<size_t>& dimSizes, const std::vector<std::string>& labels) override; + bool getStreamedMatrixInformation(std::vector<size_t>& dimSizes, std::vector<std::string>& labels) override; + + /** + * \brief Write the header to the file + * + * \retval True in case of success. + * \retval False in case of error. + */ + bool writeHeaderToFile() override; + + /** + * \brief Write current available data to the file until the last stimulation or if you set that it will not have new event before a date. + * + * \retval True in case of success. + * \retval False in case of error. + * + * \sa noEventsUntilDate + */ + bool writeDataToFile() override; + + /** + * \brief Write current available data to the file. + * + * \retval True in case of success. + * \retval False in case of error. + */ + bool writeAllDataToFile() override; + + /** + * \brief Read samples and stimulations. + * + * \param lineNb Maximum number of lines to read. If there is no more data in the file, the number of lines read can be lower. + * \param chunks[out] Valid chunks read. + * \param stimulations[out] Valid stimulations read. + * + * \retval True in case of success, even if the number of lines is different than the lineNb parameter. + * \retval False in case of error. + */ + bool readSamplesAndEventsFromFile(size_t lineNb, std::vector<SMatrixChunk>& chunks, std::vector<SStimulationChunk>& stimulations) override; + + /** + * \brief Open a OV CSV file. + * + * \retval True in case of success. + * \retval False in case of error. + */ + bool openFile(const std::string& fileName, EFileAccessMode mode) override; + + /** + * \brief Close the opened file. + * + * \retval True in case of success. + * \retval False in case of error. + */ + bool closeFile() override; + + /** + * \brief Add a single sample. + * + * \retval True in case of success. + * \retval False in case of error. + */ + bool addSample(const SMatrixChunk& sample) override; + + /** + * \brief Add several samples. + * + * \retval True in case of success. + * \retval False in case of error. + */ + bool addBuffer(const std::vector<SMatrixChunk>& samples) override; + + /** + * \brief Add a single stimulation. + * + * \retval True in case of success. + * \retval False in case of error. + */ + bool addEvent(uint64_t code, double date, double duration) override; + + /** + * \brief Add several stimulations. + * + * \retval True in case of success. + * \retval False in case of error. + */ + bool addEvent(const SStimulationChunk& event) override; + + /** + * \brief Guarantee that will not have new event before a date. + * This information is used to allow the library to write all the chunks available, before this date, to a file. + * + * \retval True in case of success. + * \retval False in case of error. + * + * \sa writeDataToFile + */ + bool noEventsUntilDate(double date) override; + + ELogErrorCodes getLastLogError() override { return m_logError; } + + std::string getLastErrorString() override { return m_lastStringError; } + + /** + * \brief Check if there is still data to read in the file. + * + * \retval True if there is still data to read in the file. + * \retval False if there is no more data to read in the file. + */ + bool hasDataToRead() const override { return m_hasDataToRead; } + +private: + /** + * \brief Split a string into a vector of strings. + * + * \param in String to split. + * \param delimiter Delimitor. + * \param out[out] Vector of string. + */ + void split(const std::string& in, char delimiter, std::vector<std::string>& out) const; + + /** + * \brief Create a string with stimulations to add in the buffer. + * + * \param stimulationsToPrint stimulations to put into the buffer + * + * \return string with stimulations to write + */ + std::string stimulationsToString(const std::vector<SStimulationChunk>& stimulationsToPrint) const; + + /** + * \brief Create a string representation of the header data. + * + * \retval true Header data as it should be written in the file + * \retval "" in case of error + */ + std::string createHeaderString(); + + /** + * \brief Set the buffer in function of data saved. + * + * \param canWriteAll true if it must write all lines, false if it write only the next buffer + * \param csv The CSV string. + * + * \retval true in case of success + * \retval false in case of wrong data sent + */ + bool createCSVStringFromData(bool canWriteAll, std::string& csv); + + /** + * \brief Parsing header to read data. + * + * \retval true in case of correct header + * \retval false in case of incorrect header + */ + bool parseHeader(); + + /** + * \brief Parsing header to read signal data. + * + * \param header[out] + * + * \retval true in case of correct header + * \retval false in case of incorrect header + */ + bool parseSignalHeader(const std::vector<std::string>& header); + + /** + * \brief Parsing header to read Spectrum data. + * + * \param header[out] + * + * \retval true in case of correct header + * \retval false in case of incorrect header + */ + bool parseSpectrumHeader(const std::vector<std::string>& header); + + /** + * \brief Parsing header to read matrix data (Streamed Matrix, Covariance matrix and Feature Vector). + * + * \param header[out] + * + * \retval true in case of correct header + * \retval false in case of incorrect header + */ + bool parseMatrixHeader(const std::vector<std::string>& header); + + /** + * \brief Read line data concerning time, epoch and matrix. + * + * \param line line to read + * \param sample[out] reference to stock data in + * \param lineNb index of the read line + * + * \retval true in case of success + * \retval false in case of error (as letters instead of numbers) + */ + bool readSampleChunk(const std::string& line, SMatrixChunk& sample, size_t lineNb); + + /** + * \brief Read line data conerning stimulations. + * + * \param line the line to read + * \param stimulations[out] vector to stock stimulations in (identifier, date and duration) + * \param lineNb the line actually reading + * + * \retval true in case of success + * \retval false in case of error (as letters instead of numbers) + */ + bool readStimulationChunk(const std::string& line, std::vector<SStimulationChunk>& stimulations, size_t lineNb); + + /** + * \brief Update position into the matrix while reading or writing. + * + * \param position[out] is the position into the matrix + * + * \retval true in case of success + * \retval false in case of browse matrix + */ + bool increasePositionIndexes(std::vector<size_t>& position); + + /** + * \brief Read lines of the first epoch to found sample count per buffer. + * + * \retval true in case of success + * \retval false in case of error + */ + bool calculateSampleCountPerBuffer(); + + /** + * \brief Read a stream until a delimiter and provide the string before the delimiter. + * + * \param in The stream to read. + * \param out The string before the next delimitor. + * \param delimiter The delimiter . + * \param bufferHistory + */ + bool streamReader(std::istream& in, std::string& out, char delimiter, std::string& bufferHistory) const; + + std::fstream m_fs; + std::string m_filename; + std::deque<SMatrixChunk> m_chunks; + std::deque<SStimulationChunk> m_stimulations; + ELogErrorCodes m_logError = LogErrorCodes_NoError; + std::string m_lastStringError = ""; + + EStreamType m_inputTypeID; + + typedef std::istream& GetLine(std::istream& in, std::string& out, char delimiter); + size_t m_nDim = 0; + std::vector<size_t> m_dimSizes; + std::vector<std::string> m_dimLabels; + size_t m_nSamplePerBuffer = 0; + double m_noEventSince = 0; + + std::vector<double> m_frequencyAbscissa; + + size_t m_sampling = 0; + size_t m_nCol = 0; + + bool m_hasInputType = false; + bool m_isFirstLineWritten = false; + bool m_isHeaderRead = false; + bool m_isSetInfoCalled = false; + bool m_hasEpoch = false; + + size_t m_nSampleOriginal = 0; + size_t m_oPrecision = 10; + + bool m_lastMatrixOnly = false; + + std::string m_bufferReadFileLine; // Buffer used to store unused read chars. + + bool m_hasDataToRead = true; #if defined TARGET_OS_Linux || defined TARGET_OS_MacOS bool m_isCRLFEOL = false; // Is a CRLF end of line #endif - }; - } // namespace CSV -} // namespace OpenViBE +}; +} // namespace CSV +} // namespace OpenViBE diff --git a/modules/csv/src/ovICSV.cpp b/modules/csv/src/ovICSV.cpp index 8d4fc648350bce5921dad9c2f7ef99879f13318d..9786fd99e5fccce7f630656f65cb57d1dda85cd8 100644 --- a/modules/csv/src/ovICSV.cpp +++ b/modules/csv/src/ovICSV.cpp @@ -3,42 +3,41 @@ #include <ovICSV.h> using namespace OpenViBE::CSV; -namespace +namespace { +const std::map<ELogErrorCodes, std::string> ERROR_MAP = { - const std::map<ELogErrorCodes, std::string> ERROR_MAP = - { - { LogErrorCodes_ErrorWhileClosing, "Error while closing the file" }, - { LogErrorCodes_NoFileDefined, "No file defined yet" }, - { LogErrorCodes_CantOpenFile, "Could not open the file" }, - { LogErrorCodes_DurationError, "The duration can't be negative" }, - { LogErrorCodes_DateError, "The date can't be negative" }, - { LogErrorCodes_NoSample, "Their is no sample to add" }, - { LogErrorCodes_NoMatrixLabels, "No matrix labels" }, - { LogErrorCodes_WrongMatrixSize, "Matrix size is different from the initial size" }, - { LogErrorCodes_MatrixEmpty, "A matrix of the buffer is empty" }, - { LogErrorCodes_DimensionSizeZero, "Dimensions can not have size equal to 0" }, - { LogErrorCodes_DimensionSizeEmpty, "Dimension sizes vector is empty" }, - { LogErrorCodes_NoChannelsName, "No channel names in the vector" }, - { LogErrorCodes_SetInfoOnce, "The setTypeInformation function should be called only once" }, - { LogErrorCodes_WrongInputType, "Wrong input type" }, - { LogErrorCodes_WrongHeader, "Error in the header of the file" }, - { LogErrorCodes_WrongLineSize, "There is a difference between the current line size and the size that it should have" }, - { LogErrorCodes_SampleNotEmpty, "Matrix must be empty to store in results of reading" }, - { LogErrorCodes_NotEnoughLines, "Can't reach the line in parameter, not enough lines in the file" }, - { LogErrorCodes_NegativeStimulation, "Stimulations cannot have negatives values" }, - { LogErrorCodes_WrongSampleDate, "Sample dates must be correct (greater than or equal to zero, and start date less than end date)" }, - { LogErrorCodes_InvalidStimulationArgument, "Wrong stimulation entry" }, - { LogErrorCodes_StimulationSize, "Some stimulation(s) has/have incomplete parameter(s)" }, - { LogErrorCodes_EmptyColumn, "A column of the file is empty" }, - { LogErrorCodes_WrongDimensionSize, "Size of dimension sizes vector must be equal to the number of dimensions" }, - { LogErrorCodes_DimensionCountZero, "Number of dimension must be at least 1" }, - { LogErrorCodes_OutOfRangeException, "Convertion from string to number is impossible : string is out of range" }, - { LogErrorCodes_InvalidArgumentException, "An invalid argument exeption have been thrown" }, - { LogErrorCodes_CantWriteHeader, "Can not write header, data already began to be written or header already written" }, - { LogErrorCodes_ErrorWhileWriting, "Error occured while trying to write" }, - { LogErrorCodes_WrongParameters, "Error with (one of )the parameter(s)" }, - { LogErrorCodes_MissingData, "Missing data in file, file may be corrupted" } - }; + { LogErrorCodes_ErrorWhileClosing, "Error while closing the file" }, + { LogErrorCodes_NoFileDefined, "No file defined yet" }, + { LogErrorCodes_CantOpenFile, "Could not open the file" }, + { LogErrorCodes_DurationError, "The duration can't be negative" }, + { LogErrorCodes_DateError, "The date can't be negative" }, + { LogErrorCodes_NoSample, "Their is no sample to add" }, + { LogErrorCodes_NoMatrixLabels, "No matrix labels" }, + { LogErrorCodes_WrongMatrixSize, "Matrix size is different from the initial size" }, + { LogErrorCodes_MatrixEmpty, "A matrix of the buffer is empty" }, + { LogErrorCodes_DimensionSizeZero, "Dimensions can not have size equal to 0" }, + { LogErrorCodes_DimensionSizeEmpty, "Dimension sizes vector is empty" }, + { LogErrorCodes_NoChannelsName, "No channel names in the vector" }, + { LogErrorCodes_SetInfoOnce, "The setTypeInformation function should be called only once" }, + { LogErrorCodes_WrongInputType, "Wrong input type" }, + { LogErrorCodes_WrongHeader, "Error in the header of the file" }, + { LogErrorCodes_WrongLineSize, "There is a difference between the current line size and the size that it should have" }, + { LogErrorCodes_SampleNotEmpty, "Matrix must be empty to store in results of reading" }, + { LogErrorCodes_NotEnoughLines, "Can't reach the line in parameter, not enough lines in the file" }, + { LogErrorCodes_NegativeStimulation, "Stimulations cannot have negatives values" }, + { LogErrorCodes_WrongSampleDate, "Sample dates must be correct (greater than or equal to zero, and start date less than end date)" }, + { LogErrorCodes_InvalidStimulationArgument, "Wrong stimulation entry" }, + { LogErrorCodes_StimulationSize, "Some stimulation(s) has/have incomplete parameter(s)" }, + { LogErrorCodes_EmptyColumn, "A column of the file is empty" }, + { LogErrorCodes_WrongDimensionSize, "Size of dimension sizes vector must be equal to the number of dimensions" }, + { LogErrorCodes_DimensionCountZero, "Number of dimension must be at least 1" }, + { LogErrorCodes_OutOfRangeException, "Convertion from string to number is impossible : string is out of range" }, + { LogErrorCodes_InvalidArgumentException, "An invalid argument exeption have been thrown" }, + { LogErrorCodes_CantWriteHeader, "Can not write header, data already began to be written or header already written" }, + { LogErrorCodes_ErrorWhileWriting, "Error occured while trying to write" }, + { LogErrorCodes_WrongParameters, "Error with (one of )the parameter(s)" }, + { LogErrorCodes_MissingData, "Missing data in file, file may be corrupted" } +}; } // namespace std::string ICSVHandler::getLogError(const ELogErrorCodes code) diff --git a/modules/date/CMakeLists.txt b/modules/date/CMakeLists.txt index b027ccd94c50e1696b90b12f6a66f7b38946b20b..fd402d0d3d0c77cdf80bdbe3b83568118ff0e77f 100644 --- a/modules/date/CMakeLists.txt +++ b/modules/date/CMakeLists.txt @@ -25,12 +25,14 @@ ADD_LIBRARY(${PROJECT_NAME} SHARED ${SRC_FILES}) SET_TARGET_PROPERTIES(${PROJECT_NAME} PROPERTIES VERSION ${PROJECT_VERSION} SOVERSION ${PROJECT_VERSION_MAJOR} + FOLDER ${MODULES_FOLDER} COMPILE_FLAGS "-DDate_Shared -DDate_Exports") ADD_LIBRARY(${PROJECT_NAME}-static STATIC ${SRC_FILES}) SET_TARGET_PROPERTIES(${PROJECT_NAME}-static PROPERTIES VERSION ${PROJECT_VERSION} SOVERSION ${PROJECT_VERSION_MAJOR} + FOLDER ${MODULES_FOLDER} COMPILE_FLAGS "-DDate_Static -DDate_Exports") IF(UNIX) @@ -43,9 +45,7 @@ INCLUDE("FindThirdPartyExpat") # --------------------------------- # Target macros -# Defines target operating system -# Defines target architecture -# Defines target compiler +# Defines target operating system, architecture and compiler # --------------------------------- SET_BUILD_PLATFORM() diff --git a/modules/date/include/date/DateParser.h b/modules/date/include/date/DateParser.h index 034da2bba1a6e647318e053b073a5e532f822922..4fcaec04642e4527f824d8c3a5941bcf95519d3f 100644 --- a/modules/date/include/date/DateParser.h +++ b/modules/date/include/date/DateParser.h @@ -6,20 +6,19 @@ #include <ctime> #endif -namespace DateParser +namespace DateParser { +class Date_API CDateParser { - class Date_API CDateParser - { - public: - /** - * \brief parse a string representing a date along a format given by a char*, and store it in a tm struct - * \param sStringToParse: the string to parse - * \param sDateFormat: the string that gives the format of the date to parse, example "%Y-%m-%d %H:%M" - * \param tmParsed: time parsed - */ - static char* strpTime(const char* sStringToParse, const char* sDateFormat, struct tm* tmParsed); +public: + /** + * \brief parse a string representing a date along a format given by a char*, and store it in a tm struct + * \param sStringToParse: the string to parse + * \param sDateFormat: the string that gives the format of the date to parse, example "%Y-%m-%d %H:%M" + * \param tmParsed: time parsed + */ + static char* strpTime(const char* sStringToParse, const char* sDateFormat, struct tm* tmParsed); - private: - CDateParser() = default; - }; +private: + CDateParser() = default; +}; } // namespace DateParser diff --git a/modules/date/include/date/WindowsDateParser.h b/modules/date/include/date/WindowsDateParser.h index c8e81fcf18435a0515e23db4ca2e44f816245796..c0f0cf1881e5275707465f7775e5d28a84b3bb03 100644 --- a/modules/date/include/date/WindowsDateParser.h +++ b/modules/date/include/date/WindowsDateParser.h @@ -2,7 +2,6 @@ #include "defines.h" #include <ctime> -namespace DateParser -{ - extern Date_API char* windowsStrptime(const char* buf, const char* fmt, struct tm* tmParsed); +namespace DateParser { +extern Date_API char* windowsStrptime(const char* buf, const char* fmt, struct tm* tmParsed); } diff --git a/modules/date/include/date/defines.h b/modules/date/include/date/defines.h index 213d84cf9ba642fd84724dbbcca869cf0ce228a4..6e73fe7bd90ba5a5b44aa77d2ba63cfe2c2a976c 100644 --- a/modules/date/include/date/defines.h +++ b/modules/date/include/date/defines.h @@ -3,23 +3,23 @@ #include <ov_common_defines.h> #if defined Date_Shared -#if defined TARGET_OS_Windows -#define Date_API_Export __declspec(dllexport) -#define Date_API_Import __declspec(dllimport) -#elif defined TARGET_OS_Linux -#define Date_API_Export __attribute__((visibility("default"))) -#define Date_API_Import __attribute__((visibility("default"))) +# if defined TARGET_OS_Windows +# define Date_API_Export __declspec(dllexport) +# define Date_API_Import __declspec(dllimport) +# elif defined TARGET_OS_Linux +# define Date_API_Export __attribute__((visibility("default"))) +# define Date_API_Import __attribute__((visibility("default"))) +# else +# define Date_API_Export +# define Date_API_Import +# endif #else -#define Date_API_Export -#define Date_API_Import -#endif -#else -#define Date_API_Export -#define Date_API_Import +# define Date_API_Export +# define Date_API_Import #endif #if defined Date_Exports -#define Date_API Date_API_Export +# define Date_API Date_API_Export #else -#define Date_API Date_API_Import +# define Date_API Date_API_Import #endif diff --git a/modules/date/src/WindowsDateParser.cpp b/modules/date/src/WindowsDateParser.cpp index 4520f611a32fa125ff0671167e66a12806721448..bf5c1cd2f3f078a09a104be47efddd9873986038 100644 --- a/modules/date/src/WindowsDateParser.cpp +++ b/modules/date/src/WindowsDateParser.cpp @@ -57,11 +57,13 @@ using namespace DateParser; static int ConvNum(const char** buf, int* dest, const int llim, const int ulim); -static const std::array<const std::string, 7> DAY = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; +static const std::array<const std::string, 7> DAY = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; static const std::array<const std::string, 7> AB_DAY = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; -static const std::array<const std::string, 12> MON = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; +static const std::array<const std::string, 12> MON = { + "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" +}; static const std::array<const std::string, 12> AB_MON = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; -static const std::array<const std::string, 2> AM_PM = { "AM", "PM" }; +static const std::array<const std::string, 2> AM_PM = { "AM", "PM" }; Date_API char* DateParser::windowsStrptime(const char* buf, const char* fmt, struct tm* tmParsed) @@ -325,7 +327,7 @@ Date_API char* DateParser::windowsStrptime(const char* buf, const char* fmt, str } /* LINTED functional specification */ - return const_cast<char *>(bp); + return const_cast<char*>(bp); } diff --git a/modules/ebml/CMakeLists.txt b/modules/ebml/CMakeLists.txt index b57be539c2095934c4c266ac4ed5c3ac5e000197..2b73e984d021d9bc46f6ca7bfc8000ad1e9604d2 100644 --- a/modules/ebml/CMakeLists.txt +++ b/modules/ebml/CMakeLists.txt @@ -14,12 +14,14 @@ ADD_LIBRARY(${PROJECT_NAME} SHARED ${SRC_FILES}) SET_TARGET_PROPERTIES(${PROJECT_NAME} PROPERTIES VERSION ${PROJECT_VERSION} SOVERSION ${PROJECT_VERSION_MAJOR} + FOLDER ${MODULES_FOLDER} COMPILE_FLAGS "-DEBML_Shared -DEBML_Exports") ADD_LIBRARY(${PROJECT_NAME}-static STATIC ${SRC_FILES}) SET_TARGET_PROPERTIES(${PROJECT_NAME}-static PROPERTIES VERSION ${PROJECT_VERSION} SOVERSION ${PROJECT_VERSION_MAJOR} + FOLDER ${MODULES_FOLDER} COMPILE_FLAGS "-DEBML_Static -DEBML_Exports") IF(UNIX) @@ -30,9 +32,7 @@ INCLUDE("FindOpenViBECommon") # --------------------------------- # Target macros -# Defines target operating system -# Defines target architecture -# Defines target compiler +# Defines target operating system, architecture and compiler # --------------------------------- SET_BUILD_PLATFORM() diff --git a/modules/ebml/include/ebml/CIdentifier.h b/modules/ebml/include/ebml/CIdentifier.h index 7efccd3d8f0517c9eca56e4b8b1ce313b89966cb..bf87c1a40bd6ba4ac22f9314770809ae69e8169e 100644 --- a/modules/ebml/include/ebml/CIdentifier.h +++ b/modules/ebml/include/ebml/CIdentifier.h @@ -3,150 +3,149 @@ #include "defines.h" #include <climits> -namespace EBML +namespace EBML { +/** + * \class CIdentifier + * \author Yann Renard (INRIA/IRISA) + * \date 2006-08-07 + * \brief Base class to work with EBML identifiers + * + * This class is used in order to work on EBML identifier. + * It handles 64 bits values for now, but could easily be + * changed to handle bigger values if needed. + * + * Be sure to look at http://ebml.sourceforge.net/specs/ in + * order to understand what an identifier is and how it works + */ +class EBML_API CIdentifier { +public: + + /** \name Constructors */ + //@{ + + /** + * \brief Basic constructor + * + * Initializes the identifier to 0. + */ + CIdentifier() : m_id(ULLONG_MAX) {} /** - * \class CIdentifier - * \author Yann Renard (INRIA/IRISA) - * \date 2006-08-07 - * \brief Base class to work with EBML identifiers + * \brief Integer based constructor + * \param id [in] : The value to use * - * This class is used in order to work on EBML identifier. - * It handles 64 bits values for now, but could easily be - * changed to handle bigger values if needed. + * Initializes the identifier to the given 64 bits value. + */ + CIdentifier(const uint64_t id) : m_id(id) {} + /** + * \brief 32 bits integer based constructor + * \param id1 [in] : the first part of the identifier + * \param id2 [in] : the second part of the identifier + * + * Builds up the 64 bits identifier given its two 32 bits + * components. + */ + CIdentifier(const size_t id1, const size_t id2) : m_id((uint64_t(id1) << 32) + id2) {} + /** + * \brief Copy constructor + * \param id [in] : The source identifier to use * - * Be sure to look at http://ebml.sourceforge.net/specs/ in - * order to understand what an identifier is and how it works + * Initializes this identifier to the same value as + * the given source identifier. */ - class EBML_API CIdentifier - { - public: + CIdentifier(const CIdentifier& id) : m_id(id.m_id) {} - /** \name Constructors */ - //@{ + //@} + /** \name Operators */ + //@{ - /** - * \brief Basic constructor - * - * Initializes the identifier to 0. - */ - CIdentifier() : m_id(ULLONG_MAX) {} - /** - * \brief Integer based constructor - * \param id [in] : The value to use - * - * Initializes the identifier to the given 64 bits value. - */ - CIdentifier(const uint64_t id) : m_id(id) {} - /** - * \brief 32 bits integer based constructor - * \param id1 [in] : the first part of the identifier - * \param id2 [in] : the second part of the identifier - * - * Builds up the 64 bits identifier given its two 32 bits - * components. - */ - CIdentifier(const size_t id1, const size_t id2) : m_id((uint64_t(id1) << 32) + id2) {} - /** - * \brief Copy constructor - * \param id [in] : The source identifier to use - * - * Initializes this identifier to the same value as - * the given source identifier. - */ - CIdentifier(const CIdentifier& id) : m_id(id.m_id) {} + /** + * \brief Copy operator + * \param id [in] : The source identifier to copy from + * \return a const reference on this identifier + * + * Initializes this identifier to the same value as + * the given source identifier. + */ + const CIdentifier& operator=(const CIdentifier& id); - //@} - /** \name Operators */ - //@{ + /** + * \brief Equality comparison operator + * \param id1 [in] : The first identifier to compare + * \param id2 [in] : The second identifier to compare + * \return \e true when the identifiers are equal, \e false + * when they are different. + * + * This function compares the two 64 bits values. + */ + friend EBML_API bool operator==(const CIdentifier& id1, const CIdentifier& id2); + /** + * \brief Difference comparison operator + * \param id1 [in] : The first identifier to compare + * \param id2 [in] : The second identifier to compare + * \return \e true when the identifiers are different, \e false + * when they are equal. + * + * This function compares the two 64 bits values. + */ + friend EBML_API bool operator!=(const CIdentifier& id1, const CIdentifier& id2); + /** + * \brief Ordering comparison operator + * \param id1 [in] : The first identifier to compare + * \param id2 [in] : The second identifier to compare + * \return \e true when the first identifier is lesser or equal + * to the second identifier, \e false in other cases. + * + * This function compares the two 64 bits values. + */ + friend EBML_API bool operator<=(const CIdentifier& id1, const CIdentifier& id2); + /** + * \brief Ordering comparison operator + * \param id1 [in] : The first identifier to compare + * \param id2 [in] : The second identifier to compare + * \return \e true when the first identifier is greater or equal + * to the second identifier, \e false in other cases. + * + * This function compares the two 64 bits values. + */ + friend EBML_API bool operator>=(const CIdentifier& id1, const CIdentifier& id2); + /** + * \brief Ordering comparison operator + * \param id1 [in] : The first identifier to compare + * \param id2 [in] : The second identifier to compare + * \return \e true when the first identifier is lesser and not equal + * to the second identifier, \e false in other cases. + * + * This function compares the two 64 bits values. + */ + friend EBML_API bool operator<(const CIdentifier& id1, const CIdentifier& id2); + /** + * \brief Ordering comparison operator + * \param id1 [in] : The first identifier to compare + * \param id2 [in] : The second identifier to compare + * \return \e true when the first identifier is greater and not equal + * to the second identifier, \e false in other cases. + * + * This function compares the two 64 bits values. + */ + friend EBML_API bool operator>(const CIdentifier& id1, const CIdentifier& id2); - /** - * \brief Copy operator - * \param id [in] : The source identifier to copy from - * \return a const reference on this identifier - * - * Initializes this identifier to the same value as - * the given source identifier. - */ - const CIdentifier& operator=(const CIdentifier& id); + /** + * \brief Cast operator + * \return \e the 64 bits value contained by this identifier. + */ + operator uint64_t() const { return this->toUInteger(); } - /** - * \brief Equality comparison operator - * \param id1 [in] : The first identifier to compare - * \param id2 [in] : The second identifier to compare - * \return \e true when the identifiers are equal, \e false - * when they are different. - * - * This function compares the two 64 bits values. - */ - friend EBML_API bool operator==(const CIdentifier& id1, const CIdentifier& id2); - /** - * \brief Difference comparison operator - * \param id1 [in] : The first identifier to compare - * \param id2 [in] : The second identifier to compare - * \return \e true when the identifiers are different, \e false - * when they are equal. - * - * This function compares the two 64 bits values. - */ - friend EBML_API bool operator!=(const CIdentifier& id1, const CIdentifier& id2); - /** - * \brief Ordering comparison operator - * \param id1 [in] : The first identifier to compare - * \param id2 [in] : The second identifier to compare - * \return \e true when the first identifier is lesser or equal - * to the second identifier, \e false in other cases. - * - * This function compares the two 64 bits values. - */ - friend EBML_API bool operator<=(const CIdentifier& id1, const CIdentifier& id2); - /** - * \brief Ordering comparison operator - * \param id1 [in] : The first identifier to compare - * \param id2 [in] : The second identifier to compare - * \return \e true when the first identifier is greater or equal - * to the second identifier, \e false in other cases. - * - * This function compares the two 64 bits values. - */ - friend EBML_API bool operator>=(const CIdentifier& id1, const CIdentifier& id2); - /** - * \brief Ordering comparison operator - * \param id1 [in] : The first identifier to compare - * \param id2 [in] : The second identifier to compare - * \return \e true when the first identifier is lesser and not equal - * to the second identifier, \e false in other cases. - * - * This function compares the two 64 bits values. - */ - friend EBML_API bool operator<(const CIdentifier& id1, const CIdentifier& id2); - /** - * \brief Ordering comparison operator - * \param id1 [in] : The first identifier to compare - * \param id2 [in] : The second identifier to compare - * \return \e true when the first identifier is greater and not equal - * to the second identifier, \e false in other cases. - * - * This function compares the two 64 bits values. - */ - friend EBML_API bool operator>(const CIdentifier& id1, const CIdentifier& id2); - - /** - * \brief Cast operator - * \return \e the 64 bits value contained by this identifier. - */ - operator uint64_t() const { return this->toUInteger(); } - - /** - * \brief Conversion to 64 bits uint32_t (should be used instead of the cast) - * \return \e the 64 bits value contained by this identifier. - */ - uint64_t toUInteger() const { return m_id; } + /** + * \brief Conversion to 64 bits uint32_t (should be used instead of the cast) + * \return \e the 64 bits value contained by this identifier. + */ + uint64_t toUInteger() const { return m_id; } - //@} + //@} - protected: +protected: - uint64_t m_id = 0; ///< The 64 bits value of this identifier - }; -} // namespace EBML + uint64_t m_id = 0; ///< The 64 bits value of this identifier +}; +} // namespace EBML diff --git a/modules/ebml/include/ebml/CReader.h b/modules/ebml/include/ebml/CReader.h index ba8ade59fe0469f5e5da673b8392745a73db8d7e..87ce802fe279f5a94c8af99ba5f698e458f4f750 100644 --- a/modules/ebml/include/ebml/CReader.h +++ b/modules/ebml/include/ebml/CReader.h @@ -2,25 +2,24 @@ #include "IReader.h" -namespace EBML +namespace EBML { +class EBML_API CReader final : public IReader { - class EBML_API CReader final : public IReader - { - public: +public: - explicit CReader(IReaderCallback& callback); - ~CReader() override; - bool processData(const void* buffer, const size_t size) override; - CIdentifier getCurrentNodeID() const override; - size_t getCurrentNodeSize() const override; - void release() override; + explicit CReader(IReaderCallback& callback); + ~CReader() override; + bool processData(const void* buffer, const size_t size) override; + CIdentifier getCurrentNodeID() const override; + size_t getCurrentNodeSize() const override; + void release() override; - protected: +protected: - IReader* m_impl = nullptr; + IReader* m_impl = nullptr; - private: +private: - CReader() = delete; - }; -} // namespace EBML + CReader() = delete; +}; +} // namespace EBML diff --git a/modules/ebml/include/ebml/CReaderHelper.h b/modules/ebml/include/ebml/CReaderHelper.h index 270c1526136c432e70c5eb351ac805ae4512532a..d1fd0c4874173f1f5014f950d2af5be5bd3775e7 100644 --- a/modules/ebml/include/ebml/CReaderHelper.h +++ b/modules/ebml/include/ebml/CReaderHelper.h @@ -2,22 +2,21 @@ #include "IReaderHelper.h" -namespace EBML +namespace EBML { +class EBML_API CReaderHelper final : public IReaderHelper { - class EBML_API CReaderHelper final : public IReaderHelper - { - public: +public: - CReaderHelper(); - ~CReaderHelper() override; - uint64_t getUInt(const void* buffer, const size_t size) override; - int64_t getInt(const void* buffer, const size_t size) override; - double getDouble(const void* buffer, const size_t size) override; - const char* getStr(const void* buffer, const size_t size) override; - void release() override; + CReaderHelper(); + ~CReaderHelper() override; + uint64_t getUInt(const void* buffer, const size_t size) override; + int64_t getInt(const void* buffer, const size_t size) override; + double getDouble(const void* buffer, const size_t size) override; + const char* getStr(const void* buffer, const size_t size) override; + void release() override; - protected: +protected: - IReaderHelper* m_impl = nullptr; - }; -} // namespace EBML + IReaderHelper* m_impl = nullptr; +}; +} // namespace EBML diff --git a/modules/ebml/include/ebml/CWriter.h b/modules/ebml/include/ebml/CWriter.h index 2e051e958a7ffdd5a764a4db82897754661c352c..7a6fb8814879e5b66e65675887b253e262703c3e 100644 --- a/modules/ebml/include/ebml/CWriter.h +++ b/modules/ebml/include/ebml/CWriter.h @@ -2,25 +2,24 @@ #include "IWriter.h" -namespace EBML +namespace EBML { +class EBML_API CWriter final : public IWriter { - class EBML_API CWriter final : public IWriter - { - public: +public: - explicit CWriter(IWriterCallback& callback); - ~CWriter() override; - bool openChild(const CIdentifier& identifier) override; - bool setChildData(const void* buffer, const size_t size) override; - bool closeChild() override; - void release() override; + explicit CWriter(IWriterCallback& callback); + ~CWriter() override; + bool openChild(const CIdentifier& identifier) override; + bool setChildData(const void* buffer, const size_t size) override; + bool closeChild() override; + void release() override; - protected: +protected: - IWriter* m_impl = nullptr; + IWriter* m_impl = nullptr; - private: +private: - CWriter() = delete; - }; -} // namespace EBML + CWriter() = delete; +}; +} // namespace EBML diff --git a/modules/ebml/include/ebml/CWriterHelper.h b/modules/ebml/include/ebml/CWriterHelper.h index fd649bbdfc2ef561980a94771ae97667ec0d07ae..2974efa40ebaf4725a03292d939e1889e34b3f62 100644 --- a/modules/ebml/include/ebml/CWriterHelper.h +++ b/modules/ebml/include/ebml/CWriterHelper.h @@ -2,28 +2,27 @@ #include "IWriterHelper.h" -namespace EBML +namespace EBML { +class EBML_API CWriterHelper final : public IWriterHelper { - class EBML_API CWriterHelper final : public IWriterHelper - { - public: +public: - CWriterHelper(); - ~CWriterHelper() override; - bool connect(IWriter* writer) override; - bool disconnect() override; - bool openChild(const CIdentifier& identifier) override; - bool closeChild() override; - bool setInt(const int64_t value) override; - bool setUInt(const uint64_t value) override; - bool setFloat(const float value) override; - bool setDouble(const double value) override; - bool setBinary(const void* buffer, const size_t size) override; - bool setStr(const char* value) override; - void release() override { } + CWriterHelper(); + ~CWriterHelper() override; + bool connect(IWriter* writer) override; + bool disconnect() override; + bool openChild(const CIdentifier& identifier) override; + bool closeChild() override; + bool setInt(const int64_t value) override; + bool setUInt(const uint64_t value) override; + bool setFloat(const float value) override; + bool setDouble(const double value) override; + bool setBinary(const void* buffer, const size_t size) override; + bool setStr(const char* value) override; + void release() override { } - protected: +protected: - IWriterHelper* m_impl = nullptr; - }; -} // namespace EBML + IWriterHelper* m_impl = nullptr; +}; +} // namespace EBML diff --git a/modules/ebml/include/ebml/IReader.h b/modules/ebml/include/ebml/IReader.h index 67f04f48fe033a682066ee35f2061f3d42c7bbdf..fa48d32a51ae4c7df56a3daea71ca2ad9652854e 100644 --- a/modules/ebml/include/ebml/IReader.h +++ b/modules/ebml/include/ebml/IReader.h @@ -3,134 +3,133 @@ #include "CIdentifier.h" #include <cstdlib> // fix Unix compatibility -namespace EBML +namespace EBML { +/** + * \class IReaderCallback + * \author Yann Renard (INRIA/IRISA) + * \date 2006-08-07 + * \brief Callback class to use when parsing the EBML stream + * + * This class is to be overloaded by the user in order to get rid of the parsing events. It will be notified + * by the EBML::IReader object of what is found in the stream. + * + * \sa EBML::IReader + */ +class EBML_API IReaderCallback { +public: + + /** + * \brief Virtual destructor + */ + virtual ~IReaderCallback() { } + /** + * \brief Kind of child querry + * \param id [in] : The id which type has to be known + * \return \e true when the node is a master node + * \return \e false when it is a simple child node. + * + * When called by the reader, this function should tell it whether the node identified by \c id is a master + * node (has child) or not (has data). For that, it has to return \e true when the node should have children, and \e false in other cases. + */ + virtual bool isMasterChild(const CIdentifier& id) = 0; /** - * \class IReaderCallback - * \author Yann Renard (INRIA/IRISA) - * \date 2006-08-07 - * \brief Callback class to use when parsing the EBML stream + * \brief Informs the callback object a new node parsing is starting + * \param id [in] : The idenfier of the newly parsing node * - * This class is to be overloaded by the user in order to get rid of the parsing events. It will be notified - * by the EBML::IReader object of what is found in the stream. + * This is called to notify the callback object that the parser has started a new EBML node parsing. This EBML + * node is identified by \c id. After this call will follow whether a new \c openChild if this node is + * a master one, whher a processData if this node is a simple child one. + */ + virtual void openChild(const CIdentifier& id) = 0; + /** + * \brief Gives the callback object the data associated with the currently opened child node + * \param buffer [in] : The buffer corresponding to the current simple child node + * \param size [in] : The buffer size in bytes + * + * This function is called when the data reading is terminated for a simple child node and so the callback + * object can process it. Whether the callback object knows how to process the data, whether it requests + * a reader helper object to do the work... See EBML::IReaderHelper for more details on that subject. + */ + virtual void processChildData(const void* buffer, const size_t size) = 0; + /** + * \brief Informs the callback object the current node parsing is terminated * - * \sa EBML::IReader + * This function tells the callback object the current node parsing is terminated. Thus the parsing continues for the + * top level node, whether opening a new child or closing itself and so on... */ - class EBML_API IReaderCallback - { - public: + virtual void closeChild() = 0; +}; - /** - * \brief Virtual destructor - */ - virtual ~IReaderCallback() { } - /** - * \brief Kind of child querry - * \param id [in] : The id which type has to be known - * \return \e true when the node is a master node - * \return \e false when it is a simple child node. - * - * When called by the reader, this function should tell it whether the node identified by \c id is a master - * node (has child) or not (has data). For that, it has to return \e true when the node should have children, and \e false in other cases. - */ - virtual bool isMasterChild(const CIdentifier& id) = 0; - /** - * \brief Informs the callback object a new node parsing is starting - * \param id [in] : The idenfier of the newly parsing node - * - * This is called to notify the callback object that the parser has started a new EBML node parsing. This EBML - * node is identified by \c id. After this call will follow whether a new \c openChild if this node is - * a master one, whher a processData if this node is a simple child one. - */ - virtual void openChild(const CIdentifier& id) = 0; - /** - * \brief Gives the callback object the data associated with the currently opened child node - * \param buffer [in] : The buffer corresponding to the current simple child node - * \param size [in] : The buffer size in bytes - * - * This function is called when the data reading is terminated for a simple child node and so the callback - * object can process it. Whether the callback object knows how to process the data, whether it requests - * a reader helper object to do the work... See EBML::IReaderHelper for more details on that subject. - */ - virtual void processChildData(const void* buffer, const size_t size) = 0; - /** - * \brief Informs the callback object the current node parsing is terminated - * - * This function tells the callback object the current node parsing is terminated. Thus the parsing continues for the - * top level node, whether opening a new child or closing itself and so on... - */ - virtual void closeChild() = 0; - }; +class EBML_API IReaderCallBack : public IReaderCallback { }; - class EBML_API IReaderCallBack : public IReaderCallback { }; +/** + * \class IReader + * \author Yann Renard (INRIA/IRISA) + * \date 2006-08-07 + * \brief EBML processing class + * + * This class should be used in order to parse an EBML stream. It should be given a callback object that can handle the + * content of the stream. The parser itself as no understanding of what is included in the EBML structure. + * + * The parsing interface looks like the eXpat XML parser, allowing on-the-fly parsing. See http://expat.sourceforge.net for more details. + * + * To create instances of this class, the user has to call EBML::createReader. To delete instances of this class, the user has to call EBML::IReader::release. + * + * Be sure to look at http://ebml.sourceforge.net/specs/ in order to understand what EBML is and how it should be used. + */ +class EBML_API IReader +{ +public: /** - * \class IReader - * \author Yann Renard (INRIA/IRISA) - * \date 2006-08-07 - * \brief EBML processing class - * - * This class should be used in order to parse an EBML stream. It should be given a callback object that can handle the - * content of the stream. The parser itself as no understanding of what is included in the EBML structure. + * \brief Processes a chunk of data + * \param buffer [in] : The buffer of data to process + * \param size [in] : The buffer size in bytes + * \return \e true when data processing was ok + * \return \e false in other cases. * - * The parsing interface looks like the eXpat XML parser, allowing on-the-fly parsing. See http://expat.sourceforge.net for more details. + * This function has to be called as soon as the stream reader (file, socket, whatever) has data. Those data + * are sent to the parser and parsing for this chunk is started immediatly. The callback object is called + * according to the EBML structure contained in the chunk and the previously parsed chunks. See + * EBML::IReaderCallback for more details on the callback object. + */ + virtual bool processData(const void* buffer, const size_t size) = 0; + /** + * \brief Gets the identifier of the current node + * \return the identifier of the current node + */ + virtual CIdentifier getCurrentNodeID() const = 0; + /** + * \brief Gets the size of the current node + * \return the size of the current node + */ + virtual size_t getCurrentNodeSize() const = 0; + /** + * \brief Tells this object it won't be used anymore * - * To create instances of this class, the user has to call EBML::createReader. To delete instances of this class, the user has to call EBML::IReader::release. + * Instances of this class can not be instanciated another way than calling \c createReader. They can + * not be deleted either because the destructor is. protected. The library knows how to create and + * delete an instance of this class... Calling \c release will simply delete this instance and + * handle necessary cleanings when needed. * - * Be sure to look at http://ebml.sourceforge.net/specs/ in order to understand what EBML is and how it should be used. + * The current object is invalid after calling this function. It can not be used anymore. */ - class EBML_API IReader - { - public: - - /** - * \brief Processes a chunk of data - * \param buffer [in] : The buffer of data to process - * \param size [in] : The buffer size in bytes - * \return \e true when data processing was ok - * \return \e false in other cases. - * - * This function has to be called as soon as the stream reader (file, socket, whatever) has data. Those data - * are sent to the parser and parsing for this chunk is started immediatly. The callback object is called - * according to the EBML structure contained in the chunk and the previously parsed chunks. See - * EBML::IReaderCallback for more details on the callback object. - */ - virtual bool processData(const void* buffer, const size_t size) = 0; - /** - * \brief Gets the identifier of the current node - * \return the identifier of the current node - */ - virtual CIdentifier getCurrentNodeID() const = 0; - /** - * \brief Gets the size of the current node - * \return the size of the current node - */ - virtual size_t getCurrentNodeSize() const = 0; - /** - * \brief Tells this object it won't be used anymore - * - * Instances of this class can not be instanciated another way than calling \c createReader. They can - * not be deleted either because the destructor is. protected. The library knows how to create and - * delete an instance of this class... Calling \c release will simply delete this instance and - * handle necessary cleanings when needed. - * - * The current object is invalid after calling this function. It can not be used anymore. - */ - virtual void release() = 0; + virtual void release() = 0; - protected: - - /** - * \brief Virtual destructor - should be overloaded - */ - virtual ~IReader() { } - }; +protected: /** - * \brief Instanciation function for EBML reader objects - * \param callback [in] : The callback object the reader should use - * \return a pointer to the created instance on success. - * \return \c NULL when something went wrong. + * \brief Virtual destructor - should be overloaded */ - extern EBML_API IReader* createReader(IReaderCallback& callback); -} // namespace EBML + virtual ~IReader() { } +}; + +/** + * \brief Instanciation function for EBML reader objects + * \param callback [in] : The callback object the reader should use + * \return a pointer to the created instance on success. + * \return \c NULL when something went wrong. + */ +extern EBML_API IReader* createReader(IReaderCallback& callback); +} // namespace EBML diff --git a/modules/ebml/include/ebml/IReaderHelper.h b/modules/ebml/include/ebml/IReaderHelper.h index 98ca21b4d856e39fe3dbaac3eda5600249f3b77c..b97d2138a45c4ae859cc02f615b0cc73e20e9e47 100644 --- a/modules/ebml/include/ebml/IReaderHelper.h +++ b/modules/ebml/include/ebml/IReaderHelper.h @@ -2,93 +2,92 @@ #include "IReader.h" -namespace EBML +namespace EBML { +/** + * \class IReaderHelper + * \author Yann Renard (INRIA/IRISA) + * \date 2006-08-07 + * \brief Helper to read basic EBML types + * + * This class may be used by a IReaderCallback instance + * in order to correctly parse simple types defined in the + * EBML description such as integers, floats, strings etc... + * + * A similar class exists to help formating process... + * See EBML::IWriterHelper for more details. + * + * Be sure to look at http://ebml.sourceforge.net/specs/ in + * order to understand what EBML is and how it should be used. + * + * \todo long double reading implementation + * \todo date reading implementation + * \todo utf8 string reading implementation + */ +class EBML_API IReaderHelper { +public: + /** - * \class IReaderHelper - * \author Yann Renard (INRIA/IRISA) - * \date 2006-08-07 - * \brief Helper to read basic EBML types - * - * This class may be used by a IReaderCallback instance - * in order to correctly parse simple types defined in the - * EBML description such as integers, floats, strings etc... - * - * A similar class exists to help formating process... - * See EBML::IWriterHelper for more details. + * \name Standard EBML value reading + * \param buffer [in] : The buffer containing data + * \param size [in] : The buffer size in bytes + * \return The value contained in the buffer * * Be sure to look at http://ebml.sourceforge.net/specs/ in - * order to understand what EBML is and how it should be used. - * - * \todo long double reading implementation - * \todo date reading implementation - * \todo utf8 string reading implementation + * order to understand standard EBML types. */ - class EBML_API IReaderHelper - { - public: - - /** - * \name Standard EBML value reading - * \param buffer [in] : The buffer containing data - * \param size [in] : The buffer size in bytes - * \return The value contained in the buffer - * - * Be sure to look at http://ebml.sourceforge.net/specs/ in - * order to understand standard EBML types. - */ - //@{ - /** - * \brief Gets an unsigned integer from the given buffer - */ - virtual uint64_t getUInt(const void* buffer, const size_t size) = 0; - /** - * \brief Gets a signed integer from the given buffer - */ - virtual int64_t getInt(const void* buffer, const size_t size) = 0; - /** - * \brief Gets a float from the given buffer - */ - virtual double getDouble(const void* buffer, const size_t size) = 0; - // virtual ??? getFloat80FromChildData(const void* buffer, const size_t size)=0; - // virtual ??? getDateFromChildData(const void* buffer, const size_t size)=0; - /** - * \brief Gets an ASCII string from the given buffer - * \warning The returned value is not permanent. It should be - * copied immediatly somewhere else by the caller. - */ - virtual const char* getStr(const void* buffer, const size_t size) = 0; - // virtual ??? getUTF8StringFromChildData(const void* buffer, const size_t size)=0; - //@} - - /** - * \brief Tells this object it won't be used anymore - * - * Instances of this class can not be instanciated - * another way than calling \c createReaderHelper. They - * can not be deleted either because the destructor is. - * protected. The library knows how to create and - * delete an instance of this class... Calling - * \c release will simply delete this instance and - * handle necessary cleanings when needed. - * - * The current object is invalid after calling this - * function. It can not be used anymore. - */ - virtual void release() = 0; + //@{ + /** + * \brief Gets an unsigned integer from the given buffer + */ + virtual uint64_t getUInt(const void* buffer, const size_t size) = 0; + /** + * \brief Gets a signed integer from the given buffer + */ + virtual int64_t getInt(const void* buffer, const size_t size) = 0; + /** + * \brief Gets a float from the given buffer + */ + virtual double getDouble(const void* buffer, const size_t size) = 0; + // virtual ??? getFloat80FromChildData(const void* buffer, const size_t size)=0; + // virtual ??? getDateFromChildData(const void* buffer, const size_t size)=0; + /** + * \brief Gets an ASCII string from the given buffer + * \warning The returned value is not permanent. It should be + * copied immediatly somewhere else by the caller. + */ + virtual const char* getStr(const void* buffer, const size_t size) = 0; + // virtual ??? getUTF8StringFromChildData(const void* buffer, const size_t size)=0; + //@} - protected: + /** + * \brief Tells this object it won't be used anymore + * + * Instances of this class can not be instanciated + * another way than calling \c createReaderHelper. They + * can not be deleted either because the destructor is. + * protected. The library knows how to create and + * delete an instance of this class... Calling + * \c release will simply delete this instance and + * handle necessary cleanings when needed. + * + * The current object is invalid after calling this + * function. It can not be used anymore. + */ + virtual void release() = 0; - /** - * \brief Virtual destructor - should be overloaded - */ - virtual ~IReaderHelper() { } - }; +protected: /** - * \brief Instanciation function for EBML reader helper objects - * \return a pointer to the created instance on success. - * \return \c NULL when something went wrong. + * \brief Virtual destructor - should be overloaded */ - extern EBML_API IReaderHelper* createReaderHelper(); -} // namespace EBML + virtual ~IReaderHelper() { } +}; + +/** + * \brief Instanciation function for EBML reader helper objects + * \return a pointer to the created instance on success. + * \return \c NULL when something went wrong. + */ +extern EBML_API IReaderHelper* createReaderHelper(); +} // namespace EBML diff --git a/modules/ebml/include/ebml/IWriter.h b/modules/ebml/include/ebml/IWriter.h index de9a61866a158de62c18d26a23292e30ec69268c..2dc557780c4bb5689f1d28439c3f3f168a42a4ea 100644 --- a/modules/ebml/include/ebml/IWriter.h +++ b/modules/ebml/include/ebml/IWriter.h @@ -3,126 +3,125 @@ #include "CIdentifier.h" #include <cstdlib> // fix Unix compatibility -namespace EBML +namespace EBML { +/** + * \class IWriterCallback + * \author Yann Renard (INRIA/IRISA) + * \date 2006-08-07 + * \brief Callback class to use when creating the EBML stream + * + * This class is to be overloaded by the user in order to get rid of the stream writing events. It will be + * notified by the EBML::IWriter object of what is to be written in the stream while the user sends information to the writer. + * + * \sa EBML::IWriter + */ +class EBML_API IWriterCallback { +public: + /** - * \class IWriterCallback - * \author Yann Renard (INRIA/IRISA) - * \date 2006-08-07 - * \brief Callback class to use when creating the EBML stream - * - * This class is to be overloaded by the user in order to get rid of the stream writing events. It will be - * notified by the EBML::IWriter object of what is to be written in the stream while the user sends information to the writer. + * \brief Virtual destructor + */ + virtual ~IWriterCallback() { } + /** + * \brief Gives the callback object a new stream chunk + * \param buffer [in] : The buffer to write in the stream + * \param size [in] : The buffer size in bytes * - * \sa EBML::IWriter + * This function tells the callback object new data are ready to send in the EBML stream. This function + * may be called while the user sends data to the writer. */ - class EBML_API IWriterCallback - { - public: + virtual void write(const void* buffer, const size_t size) = 0; +}; - /** - * \brief Virtual destructor - */ - virtual ~IWriterCallback() { } - /** - * \brief Gives the callback object a new stream chunk - * \param buffer [in] : The buffer to write in the stream - * \param size [in] : The buffer size in bytes - * - * This function tells the callback object new data are ready to send in the EBML stream. This function - * may be called while the user sends data to the writer. - */ - virtual void write(const void* buffer, const size_t size) = 0; - }; +class EBML_API IWriterCallBack : public IWriterCallback { }; - class EBML_API IWriterCallBack : public IWriterCallback { }; +/** + * \class IWriter + * \author Yann Renard (INRIA/IRISA) + * \date 2006-08-07 + * \brief EBML formating class + * + * This class is used in order to format datas using EBML specifications. It gives a minimalistic interface to + * allow creating new EBML nodes, and to insert data in simple child nodes. + * + * Basic usage of this class consists in : + * + * - Create child node + * - Gives information about the node : + * - Whether created node is master node (Goto 1) + * - Whether created node is simple child node (set data for this child node) + * - Close opened node + * + * The EBML::IWriterHelper class could be used in order to send EBML standard data such as integers, floats, strings, etc... + * + * To create instances of this class, the user has to call EBML::createWriter. To delete instances of this class, the user has to call EBML::IWriter::release. + * + * Be sure to look at http://ebml.sourceforge.net/specs/ in order to understand what EBML is and how it should be used. + */ +class EBML_API IWriter +{ +public: /** - * \class IWriter - * \author Yann Renard (INRIA/IRISA) - * \date 2006-08-07 - * \brief EBML formating class + * \brief Starts a new child node + * \param identifier [in] : The identifier of the new child node + * \return \e true on success. + * \return \e false on error. * - * This class is used in order to format datas using EBML specifications. It gives a minimalistic interface to - * allow creating new EBML nodes, and to insert data in simple child nodes. + * This function is called when the user wants to add a child node to the currently opened master node. + * A node containing data can not have child so if \c setChildData has been called before, this function returns \e false. * - * Basic usage of this class consists in : + * Once the node has been opened, it should be closed calling \c closeChild. + */ + virtual bool openChild(const CIdentifier& identifier) = 0; + /** + * \brief Sets data for simple child node + * \param buffer [in] : The buffer to set as child data + * \param size [in] : The buffer size in bytes + * \return \e true on success. + * \return \e false on error. * - * - Create child node - * - Gives information about the node : - * - Whether created node is master node (Goto 1) - * - Whether created node is simple child node (set data for this child node) - * - Close opened node + * This function is called by the user for setting data in the currently opened simple child node. + * If the currently opened node has children, it is a master node so it can't receive data. In such case, the function returns \e false. However, + * it the currently opened node already has data, it returns \e false too. + */ + virtual bool setChildData(const void* buffer, const size_t size) = 0; + /** + * \brief Closes currently opened child node + * \return \e true on success. + * \return \e false on error. * - * The EBML::IWriterHelper class could be used in order to send EBML standard data such as integers, floats, strings, etc... + * This function is called when the user wants to close a child node. The node should have received + * either child nodes or data depending if it is a master node or a simple child node. + */ + virtual bool closeChild() = 0; + /** + * \brief Tells this object it won't be used anymore * - * To create instances of this class, the user has to call EBML::createWriter. To delete instances of this class, the user has to call EBML::IWriter::release. + * Instances of this class can not be instanciated another way than calling \c createWriter. They can + * not be deleted either because the destructor is. protected. The library knows how to create and + * delete an instance of this class... Calling \c release will simply delete this instance and + * handle necessary cleanings when needed. * - * Be sure to look at http://ebml.sourceforge.net/specs/ in order to understand what EBML is and how it should be used. + * The current object is invalid after calling this + * function. It can not be used anymore. */ - class EBML_API IWriter - { - public: + virtual void release() = 0; - /** - * \brief Starts a new child node - * \param identifier [in] : The identifier of the new child node - * \return \e true on success. - * \return \e false on error. - * - * This function is called when the user wants to add a child node to the currently opened master node. - * A node containing data can not have child so if \c setChildData has been called before, this function returns \e false. - * - * Once the node has been opened, it should be closed calling \c closeChild. - */ - virtual bool openChild(const CIdentifier& identifier) = 0; - /** - * \brief Sets data for simple child node - * \param buffer [in] : The buffer to set as child data - * \param size [in] : The buffer size in bytes - * \return \e true on success. - * \return \e false on error. - * - * This function is called by the user for setting data in the currently opened simple child node. - * If the currently opened node has children, it is a master node so it can't receive data. In such case, the function returns \e false. However, - * it the currently opened node already has data, it returns \e false too. - */ - virtual bool setChildData(const void* buffer, const size_t size) = 0; - /** - * \brief Closes currently opened child node - * \return \e true on success. - * \return \e false on error. - * - * This function is called when the user wants to close a child node. The node should have received - * either child nodes or data depending if it is a master node or a simple child node. - */ - virtual bool closeChild() = 0; - /** - * \brief Tells this object it won't be used anymore - * - * Instances of this class can not be instanciated another way than calling \c createWriter. They can - * not be deleted either because the destructor is. protected. The library knows how to create and - * delete an instance of this class... Calling \c release will simply delete this instance and - * handle necessary cleanings when needed. - * - * The current object is invalid after calling this - * function. It can not be used anymore. - */ - virtual void release() = 0; - - protected: - - /** - * \brief Virtual destructor - should be overloaded - */ - virtual ~IWriter() { } - }; +protected: /** - * \brief Instanciation function for EBML writer objects - * \param callback [in] : The callback object the writer should use - * \return a pointer to the created instance on success. - * \return \c NULL when something went wrong. + * \brief Virtual destructor - should be overloaded */ - extern EBML_API IWriter* createWriter(IWriterCallback& callback); -} // namespace EBML + virtual ~IWriter() { } +}; + +/** + * \brief Instanciation function for EBML writer objects + * \param callback [in] : The callback object the writer should use + * \return a pointer to the created instance on success. + * \return \c NULL when something went wrong. + */ +extern EBML_API IWriter* createWriter(IWriterCallback& callback); +} // namespace EBML diff --git a/modules/ebml/include/ebml/IWriterHelper.h b/modules/ebml/include/ebml/IWriterHelper.h index 94ba7b5707af0c4c2a7686f936fcaa2e663e5468..66110cb55cf74f65f9dfc7748cf7ec06641c3af6 100644 --- a/modules/ebml/include/ebml/IWriterHelper.h +++ b/modules/ebml/include/ebml/IWriterHelper.h @@ -2,176 +2,175 @@ #include "IWriter.h" -namespace EBML +namespace EBML { +/** + * \class IWriterHelper + * \author Yann Renard (INRIA/IRISA) + * \date 2006-08-07 + * \brief Helper to write basic EBML types + * + * This class may be used by the user in order to correctly + * format simple types defined in the EBML description such + * as integers, floats, strings etc... It directly uses the + * EBML::IWriter connected instance so one could simply + * use the helper in order to write his EBML stream. + * + * A similar class exists to help parsing process... + * See EBML::IReaderHelper for more details. + * + * Be sure to look at http://ebml.sourceforge.net/specs/ in + * order to understand what EBML is and how it should be used. + * + * \todo long double formating implementation + * \todo date formating implementation + * \todo utf8 string formating implementation + */ +class EBML_API IWriterHelper { +public: + + /** \name Writer connection */ + //@{ /** - * \class IWriterHelper - * \author Yann Renard (INRIA/IRISA) - * \date 2006-08-07 - * \brief Helper to write basic EBML types - * - * This class may be used by the user in order to correctly - * format simple types defined in the EBML description such - * as integers, floats, strings etc... It directly uses the - * EBML::IWriter connected instance so one could simply - * use the helper in order to write his EBML stream. + * \brief Connects an EBML writer to this helper + * \param writer [in] : The writer to connect + * \return \e true on success. + * \return \e false on error. * - * A similar class exists to help parsing process... - * See EBML::IReaderHelper for more details. + * This function gives the helper a handle to the writer + * to use in order to forward requests. Thus, when the + * user calls a helper function, the call is forwarded + * to the correct writer that effictively does the work. + * The aim of this helper is simply to transform standard + * EBML types into bytes buffers. * - * Be sure to look at http://ebml.sourceforge.net/specs/ in - * order to understand what EBML is and how it should be used. + * Once a writer is connected, it could be disconnected + * thanks to the \c disconnect function. It must be done + * before calling \c connect again. + */ + virtual bool connect(IWriter* writer) = 0; + /** + * \brief Disconnects the currently connected EBML writer + * \return \e true on success. + * \return \e false on error. * - * \todo long double formating implementation - * \todo date formating implementation - * \todo utf8 string formating implementation + * This function should be called to release the EBML + * writer handle. The helper instance may then be used + * with another EBML writer instance calling \c connect + * again. */ - class EBML_API IWriterHelper - { - public: - - /** \name Writer connection */ - //@{ - /** - * \brief Connects an EBML writer to this helper - * \param writer [in] : The writer to connect - * \return \e true on success. - * \return \e false on error. - * - * This function gives the helper a handle to the writer - * to use in order to forward requests. Thus, when the - * user calls a helper function, the call is forwarded - * to the correct writer that effictively does the work. - * The aim of this helper is simply to transform standard - * EBML types into bytes buffers. - * - * Once a writer is connected, it could be disconnected - * thanks to the \c disconnect function. It must be done - * before calling \c connect again. - */ - virtual bool connect(IWriter* writer) = 0; - /** - * \brief Disconnects the currently connected EBML writer - * \return \e true on success. - * \return \e false on error. - * - * This function should be called to release the EBML - * writer handle. The helper instance may then be used - * with another EBML writer instance calling \c connect - * again. - */ - virtual bool disconnect() = 0; - //@} + virtual bool disconnect() = 0; + //@} - /** \name Writer binding functions */ - //@{ - /** - * \brief Child opening binding - * \param identifier [in] : The identifier of the new child node - * \return \e true on success. - * \return \e false on error. - * - * This function simply forwards the call to the - * corresponding EBML::IWriter function. See - * EBML::IWriter::openChild for more details. - */ - virtual bool openChild(const CIdentifier& identifier) = 0; - /** - * \brief Child closing binding - * \return \e true on success. - * \return \e false on error. - * - * This function simply forwards the call to the - * corresponding EBML::IWriter function. See - * EBML::IWriter::closeChild for more details. - */ - virtual bool closeChild() = 0; - //@} - - /** - * \name Standard EBML formating - * \brief EBML::IWriter::setChildData replacement - * \return \e true on success. - * \return \e false on error. - * - * Those functions should be used in place of the - * basic EBML::IWriter::setChildData function. They - * format standard EBML types into corresponding - * buffers and then send those built buffers to - * the writer using the EBML::IWriter::setChildData - * function. - */ - //@{ - /** - * \brief Sets a signed integer as child data - * \param value [in] : The integer value to set - */ - virtual bool setInt(const int64_t value) = 0; - /** - * \brief Sets an unsigned integer as child data - * \param value [in] : The integer value to set - */ - virtual bool setUInt(const uint64_t value) = 0; - /** - * \brief Sets a 32 bits float value as child data - * \param value [in] : The 32 bits float value to set - */ - virtual bool setFloat(const float value) = 0; - /** - * \brief Sets a 64 bits float value as child data - * \param value [in] : The 64 bits float value to set - */ - virtual bool setDouble(const double value) = 0; - // virtual bool setFloat80AsChildData( ??? value)=0; - // virtual bool setDateAsChildData( ??? value)=0; - /** - * \brief Sets a buffer as child data - * \param buffer [in] : The buffer to send to the writer - * \param size [in] : The buffer size in bytes - * \note This function simply calls the basic - * EBML::IWriter::setChildData function with the - * same two parameters. - */ - virtual bool setBinary(const void* buffer, const size_t size) = 0; - /** - * \brief Sets an ASCII string as child data - * \param value [in] : The ASCII string value to set - */ - virtual bool setStr(const char* value) = 0; - // virtual bool setUTF8StringAsChildData( ??? value)=0; - //@} + /** \name Writer binding functions */ + //@{ + /** + * \brief Child opening binding + * \param identifier [in] : The identifier of the new child node + * \return \e true on success. + * \return \e false on error. + * + * This function simply forwards the call to the + * corresponding EBML::IWriter function. See + * EBML::IWriter::openChild for more details. + */ + virtual bool openChild(const CIdentifier& identifier) = 0; + /** + * \brief Child closing binding + * \return \e true on success. + * \return \e false on error. + * + * This function simply forwards the call to the + * corresponding EBML::IWriter function. See + * EBML::IWriter::closeChild for more details. + */ + virtual bool closeChild() = 0; + //@} - /** - * \brief Tells this object it won't be used anymore - * - * Instances of this class can not be instanciated - * another way than calling \c createWriterHelper. They - * can not be deleted either because the destructor is. - * protected. The library knows how to create and - * delete an instance of this class... Calling - * \c release will simply delete this instance and - * handle necessary cleanings when needed. - * - * The current object is invalid after calling this - * function. It can not be used anymore. - * - * \warning Releasing this obbject does not release the - * connected writer instance ! - */ - virtual void release() = 0; + /** + * \name Standard EBML formating + * \brief EBML::IWriter::setChildData replacement + * \return \e true on success. + * \return \e false on error. + * + * Those functions should be used in place of the + * basic EBML::IWriter::setChildData function. They + * format standard EBML types into corresponding + * buffers and then send those built buffers to + * the writer using the EBML::IWriter::setChildData + * function. + */ + //@{ + /** + * \brief Sets a signed integer as child data + * \param value [in] : The integer value to set + */ + virtual bool setInt(const int64_t value) = 0; + /** + * \brief Sets an unsigned integer as child data + * \param value [in] : The integer value to set + */ + virtual bool setUInt(const uint64_t value) = 0; + /** + * \brief Sets a 32 bits float value as child data + * \param value [in] : The 32 bits float value to set + */ + virtual bool setFloat(const float value) = 0; + /** + * \brief Sets a 64 bits float value as child data + * \param value [in] : The 64 bits float value to set + */ + virtual bool setDouble(const double value) = 0; + // virtual bool setFloat80AsChildData( ??? value)=0; + // virtual bool setDateAsChildData( ??? value)=0; + /** + * \brief Sets a buffer as child data + * \param buffer [in] : The buffer to send to the writer + * \param size [in] : The buffer size in bytes + * \note This function simply calls the basic + * EBML::IWriter::setChildData function with the + * same two parameters. + */ + virtual bool setBinary(const void* buffer, const size_t size) = 0; + /** + * \brief Sets an ASCII string as child data + * \param value [in] : The ASCII string value to set + */ + virtual bool setStr(const char* value) = 0; + // virtual bool setUTF8StringAsChildData( ??? value)=0; + //@} - protected: + /** + * \brief Tells this object it won't be used anymore + * + * Instances of this class can not be instanciated + * another way than calling \c createWriterHelper. They + * can not be deleted either because the destructor is. + * protected. The library knows how to create and + * delete an instance of this class... Calling + * \c release will simply delete this instance and + * handle necessary cleanings when needed. + * + * The current object is invalid after calling this + * function. It can not be used anymore. + * + * \warning Releasing this obbject does not release the + * connected writer instance ! + */ + virtual void release() = 0; - /** - * \brief Virtual destructor - should be overloaded - */ - virtual ~IWriterHelper() { } - }; +protected: /** - * \brief Instanciation function for EBML writer helper objects - * \return a pointer to the created instance on success. - * \return \c NULL when something went wrong. + * \brief Virtual destructor - should be overloaded */ - extern EBML_API IWriterHelper* createWriterHelper(); -} // namespace EBML + virtual ~IWriterHelper() { } +}; + +/** + * \brief Instanciation function for EBML writer helper objects + * \return a pointer to the created instance on success. + * \return \c NULL when something went wrong. + */ +extern EBML_API IWriterHelper* createWriterHelper(); +} // namespace EBML diff --git a/modules/ebml/include/ebml/TReaderCallbackProxy.h b/modules/ebml/include/ebml/TReaderCallbackProxy.h index 6656108a51e6a29a62f47ceeb569b359dd32b8ad..835e3b2196f35b943b8afdb720a938e2e436e315 100644 --- a/modules/ebml/include/ebml/TReaderCallbackProxy.h +++ b/modules/ebml/include/ebml/TReaderCallbackProxy.h @@ -2,81 +2,80 @@ #include "IReader.h" -namespace EBML +namespace EBML { + +// ________________________________________________________________________________________________________________ +// + +template <class TOwnerClass> +class TReaderCallbackProxy1 final : public IReaderCallback { +public: + TReaderCallbackProxy1(TOwnerClass& ownerObject, bool (TOwnerClass::*mfpIsMasterChild)(const CIdentifier& identifier), + void (TOwnerClass::*mfpOpenChild)(const CIdentifier& identifier), + void (TOwnerClass::*mfpProcessChildData)(const void* buffer, const size_t size), void (TOwnerClass::*mfpCloseChild)()) + : m_ownerObject(ownerObject), m_mfpIsMasterChild(mfpIsMasterChild), m_mfpOpenChild(mfpOpenChild), m_mfpProcessChildData(mfpProcessChildData), + m_mfpCloseChild(mfpCloseChild) { } + + bool isMasterChild(const CIdentifier& identifier) override + { + if (m_mfpIsMasterChild) { return (m_ownerObject.*m_mfpIsMasterChild)(identifier); } + return false; + } + + void openChild(const CIdentifier& identifier) override { if (m_mfpOpenChild) { (m_ownerObject.*m_mfpOpenChild)(identifier); } } - // ________________________________________________________________________________________________________________ - // + void processChildData(const void* buffer, const size_t size) override + { + if (m_mfpProcessChildData) { (m_ownerObject.*m_mfpProcessChildData)(buffer, size); } + } + + void closeChild() override { if (m_mfpCloseChild) { (m_ownerObject.*m_mfpCloseChild)(); } } + +protected: + TOwnerClass& m_ownerObject; + bool (TOwnerClass::*m_mfpIsMasterChild)(const CIdentifier& identifier); + void (TOwnerClass::*m_mfpOpenChild)(const CIdentifier& identifier); + void (TOwnerClass::*m_mfpProcessChildData)(const void* buffer, size_t size); + void (TOwnerClass::*m_mfpCloseChild)(); +}; + +// ________________________________________________________________________________________________________________ +// + +template <class TOwnerClass, bool (TOwnerClass::*TMfpIsMasterChild)(const CIdentifier& identifier), + void (TOwnerClass::*TMfpOpenChild)(const CIdentifier& identifier), + void (TOwnerClass::*TMfpProcessChildData)(const void* buffer, size_t size), void (TOwnerClass::*TMfpCloseChild)()> +class TReaderCallbackProxy2 final : public IReaderCallback +{ +public: + TReaderCallbackProxy2(TOwnerClass& ownerObject) + : m_ownerObject(ownerObject), m_mfpIsMasterChild(TMfpIsMasterChild), m_mfpOpenChild(TMfpOpenChild), m_mfpProcessChildData(TMfpProcessChildData), + m_mfpCloseChild(TMfpCloseChild) { } - template <class TOwnerClass> - class TReaderCallbackProxy1 final : public IReaderCallback + bool isMasterChild(const CIdentifier& identifier) override { - public: - TReaderCallbackProxy1(TOwnerClass& ownerObject, bool (TOwnerClass::*mfpIsMasterChild)(const CIdentifier& identifier), - void (TOwnerClass::*mfpOpenChild)(const CIdentifier& identifier), - void (TOwnerClass::*mfpProcessChildData)(const void* buffer, const size_t size), void (TOwnerClass::*mfpCloseChild)()) - : m_ownerObject(ownerObject), m_mfpIsMasterChild(mfpIsMasterChild), m_mfpOpenChild(mfpOpenChild), m_mfpProcessChildData(mfpProcessChildData), - m_mfpCloseChild(mfpCloseChild) { } - - bool isMasterChild(const CIdentifier& identifier) override - { - if (m_mfpIsMasterChild) { return (m_ownerObject.*m_mfpIsMasterChild)(identifier); } - return false; - } - - void openChild(const CIdentifier& identifier) override { if (m_mfpOpenChild) { (m_ownerObject.*m_mfpOpenChild)(identifier); } } - - void processChildData(const void* buffer, const size_t size) override - { - if (m_mfpProcessChildData) { (m_ownerObject.*m_mfpProcessChildData)(buffer, size); } - } - - void closeChild() override { if (m_mfpCloseChild) { (m_ownerObject.*m_mfpCloseChild)(); } } - - protected: - TOwnerClass& m_ownerObject; - bool (TOwnerClass::*m_mfpIsMasterChild)(const CIdentifier& identifier); - void (TOwnerClass::*m_mfpOpenChild)(const CIdentifier& identifier); - void (TOwnerClass::*m_mfpProcessChildData)(const void* buffer, size_t size); - void (TOwnerClass::*m_mfpCloseChild)(); - }; - - // ________________________________________________________________________________________________________________ - // - - template <class TOwnerClass, bool (TOwnerClass::*TMfpIsMasterChild)(const CIdentifier& identifier), - void (TOwnerClass::*TMfpOpenChild)(const CIdentifier& identifier), - void (TOwnerClass::*TMfpProcessChildData)(const void* buffer, size_t size), void (TOwnerClass::*TMfpCloseChild)()> - class TReaderCallbackProxy2 final : public IReaderCallback + if (m_mfpIsMasterChild) { return (m_ownerObject.*m_mfpIsMasterChild)(identifier); } + return false; + } + + void openChild(const CIdentifier& identifier) override { if (m_mfpOpenChild) { (m_ownerObject.*m_mfpOpenChild)(identifier); } } + + void processChildData(const void* buffer, const size_t size) override { - public: - TReaderCallbackProxy2(TOwnerClass& ownerObject) - : m_ownerObject(ownerObject), m_mfpIsMasterChild(TMfpIsMasterChild), m_mfpOpenChild(TMfpOpenChild), m_mfpProcessChildData(TMfpProcessChildData), - m_mfpCloseChild(TMfpCloseChild) { } - - bool isMasterChild(const CIdentifier& identifier) override - { - if (m_mfpIsMasterChild) { return (m_ownerObject.*m_mfpIsMasterChild)(identifier); } - return false; - } - - void openChild(const CIdentifier& identifier) override { if (m_mfpOpenChild) { (m_ownerObject.*m_mfpOpenChild)(identifier); } } - - void processChildData(const void* buffer, const size_t size) override - { - if (m_mfpProcessChildData) { (m_ownerObject.*m_mfpProcessChildData)(buffer, size); } - } - - void closeChild() override { if (m_mfpCloseChild) { (m_ownerObject.*m_mfpCloseChild)(); } } - - protected: - TOwnerClass& m_ownerObject; - bool (TOwnerClass::*m_mfpIsMasterChild)(const CIdentifier& identifier); - void (TOwnerClass::*m_mfpOpenChild)(const CIdentifier& identifier); - void (TOwnerClass::*m_mfpProcessChildData)(const void* buffer, size_t size); - void (TOwnerClass::*m_mfpCloseChild)(); - }; - - // ________________________________________________________________________________________________________________ - // -} // namespace EBML + if (m_mfpProcessChildData) { (m_ownerObject.*m_mfpProcessChildData)(buffer, size); } + } + + void closeChild() override { if (m_mfpCloseChild) { (m_ownerObject.*m_mfpCloseChild)(); } } + +protected: + TOwnerClass& m_ownerObject; + bool (TOwnerClass::*m_mfpIsMasterChild)(const CIdentifier& identifier); + void (TOwnerClass::*m_mfpOpenChild)(const CIdentifier& identifier); + void (TOwnerClass::*m_mfpProcessChildData)(const void* buffer, size_t size); + void (TOwnerClass::*m_mfpCloseChild)(); +}; + +// ________________________________________________________________________________________________________________ +// +} // namespace EBML diff --git a/modules/ebml/include/ebml/TWriterCallbackProxy.h b/modules/ebml/include/ebml/TWriterCallbackProxy.h index 84cf0b643fb6f93db63fcde65d0b56e21c8bdcce..38ca9f356401556803934488934ed5e69425ed49 100644 --- a/modules/ebml/include/ebml/TWriterCallbackProxy.h +++ b/modules/ebml/include/ebml/TWriterCallbackProxy.h @@ -2,42 +2,41 @@ #include "IWriter.h" -namespace EBML -{ +namespace EBML { - // ________________________________________________________________________________________________________________ - // +// ________________________________________________________________________________________________________________ +// - template <class TOwnerClass> - class TWriterCallbackProxy1 final : public IWriterCallback - { - public: - TWriterCallbackProxy1(TOwnerClass& ownerObject, void (TOwnerClass::*mfpWrite)(const void* buffer, size_t size)) - : m_ownerObject(ownerObject), m_mfpWrite(mfpWrite) { } +template <class TOwnerClass> +class TWriterCallbackProxy1 final : public IWriterCallback +{ +public: + TWriterCallbackProxy1(TOwnerClass& ownerObject, void (TOwnerClass::*mfpWrite)(const void* buffer, size_t size)) + : m_ownerObject(ownerObject), m_mfpWrite(mfpWrite) { } - void write(const void* buffer, const size_t size) override { if (m_mfpWrite) { (m_ownerObject.*m_mfpWrite)(buffer, size); } } + void write(const void* buffer, const size_t size) override { if (m_mfpWrite) { (m_ownerObject.*m_mfpWrite)(buffer, size); } } - protected: - TOwnerClass& m_ownerObject; - void (TOwnerClass::*m_mfpWrite)(const void* buffer, size_t size); - }; +protected: + TOwnerClass& m_ownerObject; + void (TOwnerClass::*m_mfpWrite)(const void* buffer, size_t size); +}; - // ________________________________________________________________________________________________________________ - // +// ________________________________________________________________________________________________________________ +// - template <class TOwnerClass, void (TOwnerClass::*TMfpWrite)(const void* buffer, size_t size)> - class TWriterCallbackProxy2 final : public IWriterCallback - { - public: - TWriterCallbackProxy2(TOwnerClass& ownerObject) : m_ownerObject(ownerObject), m_mfpWrite(TMfpWrite) { } +template <class TOwnerClass, void (TOwnerClass::*TMfpWrite)(const void* buffer, size_t size)> +class TWriterCallbackProxy2 final : public IWriterCallback +{ +public: + TWriterCallbackProxy2(TOwnerClass& ownerObject) : m_ownerObject(ownerObject), m_mfpWrite(TMfpWrite) { } - void write(const void* buffer, const size_t size) override { if (m_mfpWrite) { (m_ownerObject.*m_mfpWrite)(buffer, size); } } + void write(const void* buffer, const size_t size) override { if (m_mfpWrite) { (m_ownerObject.*m_mfpWrite)(buffer, size); } } - protected: - TOwnerClass& m_ownerObject; - void (TOwnerClass::*m_mfpWrite)(const void* buffer, size_t size); - }; +protected: + TOwnerClass& m_ownerObject; + void (TOwnerClass::*m_mfpWrite)(const void* buffer, size_t size); +}; - // ________________________________________________________________________________________________________________ - // -} // namespace EBML +// ________________________________________________________________________________________________________________ +// +} // namespace EBML diff --git a/modules/ebml/include/ebml/defines.h b/modules/ebml/include/ebml/defines.h index 9012597474c9b7085767c47565a77ce9675d9b17..c296f1bf951ee40fc3e56ea62776c7ed402e8802 100644 --- a/modules/ebml/include/ebml/defines.h +++ b/modules/ebml/include/ebml/defines.h @@ -95,23 +95,23 @@ //@} #if defined EBML_Shared -#if defined TARGET_OS_Windows -#define EBML_API_Export __declspec(dllexport) -#define EBML_API_Import __declspec(dllimport) -#elif defined TARGET_OS_Linux || defined TARGET_OS_MacOS - #define EBML_API_Export __attribute__((visibility("default"))) - #define EBML_API_Import __attribute__((visibility("default"))) +# if defined TARGET_OS_Windows +# define EBML_API_Export __declspec(dllexport) +# define EBML_API_Import __declspec(dllimport) +# elif defined TARGET_OS_Linux || defined TARGET_OS_MacOS +# define EBML_API_Export __attribute__((visibility("default"))) +# define EBML_API_Import __attribute__((visibility("default"))) +# else +# define EBML_API_Export +# define EBML_API_Import +# endif #else - #define EBML_API_Export - #define EBML_API_Import -#endif -#else -#define EBML_API_Export -#define EBML_API_Import +# define EBML_API_Export +# define EBML_API_Import #endif #if defined EBML_Exports -#define EBML_API EBML_API_Export +# define EBML_API EBML_API_Export #else - #define EBML_API EBML_API_Import +# define EBML_API EBML_API_Import #endif diff --git a/modules/ebml/src/CIdentifier.cpp b/modules/ebml/src/CIdentifier.cpp index 3db8658af2aad3d7d564d29555374812e09702b4..a64bbfdf345a8338cafefe1776f72c457f0d3316 100644 --- a/modules/ebml/src/CIdentifier.cpp +++ b/modules/ebml/src/CIdentifier.cpp @@ -8,12 +8,11 @@ const CIdentifier& CIdentifier::operator=(const CIdentifier& id) return *this; } -namespace EBML -{ - bool operator==(const CIdentifier& id1, const CIdentifier& id2) { return id1.m_id == id2.m_id; } - bool operator!=(const CIdentifier& id1, const CIdentifier& id2) { return id1.m_id != id2.m_id; } - bool operator<=(const CIdentifier& id1, const CIdentifier& id2) { return id1.m_id <= id2.m_id; } - bool operator>=(const CIdentifier& id1, const CIdentifier& id2) { return id1.m_id >= id2.m_id; } - bool operator<(const CIdentifier& id1, const CIdentifier& id2) { return id1.m_id < id2.m_id; } - bool operator>(const CIdentifier& id1, const CIdentifier& id2) { return id1.m_id > id2.m_id; } -} // namespace EBML +namespace EBML { +bool operator==(const CIdentifier& id1, const CIdentifier& id2) { return id1.m_id == id2.m_id; } +bool operator!=(const CIdentifier& id1, const CIdentifier& id2) { return id1.m_id != id2.m_id; } +bool operator<=(const CIdentifier& id1, const CIdentifier& id2) { return id1.m_id <= id2.m_id; } +bool operator>=(const CIdentifier& id1, const CIdentifier& id2) { return id1.m_id >= id2.m_id; } +bool operator<(const CIdentifier& id1, const CIdentifier& id2) { return id1.m_id < id2.m_id; } +bool operator>(const CIdentifier& id1, const CIdentifier& id2) { return id1.m_id > id2.m_id; } +} // namespace EBML diff --git a/modules/ebml/src/CReader.cpp b/modules/ebml/src/CReader.cpp index a6dda409be6f365e02eb6ef077ddc66124c85f5b..8b288cc2b510fb644feedd522d2ba99c61aeb4bd 100644 --- a/modules/ebml/src/CReader.cpp +++ b/modules/ebml/src/CReader.cpp @@ -3,13 +3,10 @@ using namespace EBML; CReader::CReader(IReaderCallback& callback) { m_impl = createReader(callback); } - CReader::~CReader() { m_impl->release(); } bool CReader::processData(const void* buffer, const size_t size) { return m_impl->processData(buffer, size); } - CIdentifier CReader::getCurrentNodeID() const { return m_impl->getCurrentNodeID(); } - size_t CReader::getCurrentNodeSize() const { return m_impl->getCurrentNodeSize(); } void CReader::release() {} diff --git a/modules/ebml/src/CWriter.cpp b/modules/ebml/src/CWriter.cpp index 5c41f5f101148d43709b16d84522d890d0d6dfd1..d35632e32324129b44a57f8f0d9bc8b5b590b3f9 100644 --- a/modules/ebml/src/CWriter.cpp +++ b/modules/ebml/src/CWriter.cpp @@ -3,13 +3,10 @@ using namespace EBML; CWriter::CWriter(IWriterCallback& callback) { m_impl = createWriter(callback); } - CWriter::~CWriter() { m_impl->release(); } bool CWriter::openChild(const CIdentifier& identifier) { return m_impl->openChild(identifier); } - bool CWriter::setChildData(const void* buffer, const size_t size) { return m_impl->setChildData(buffer, size); } - bool CWriter::closeChild() { return m_impl->closeChild(); } void CWriter::release() {} diff --git a/modules/ebml/src/IReader.cpp b/modules/ebml/src/IReader.cpp index 2a1af53ee801a4f68f386eb673ca94031813669c..287e334fc1d5bc557c2416ba6e9634631d3fa5fb 100644 --- a/modules/ebml/src/IReader.cpp +++ b/modules/ebml/src/IReader.cpp @@ -62,69 +62,65 @@ inline uint64_t getValue(unsigned char* buffer) // ________________________________________________________________________________________________________________ // -namespace EBML +namespace EBML { +namespace { +class CReaderNode { - namespace - { - class CReaderNode - { - public: - CReaderNode(const CIdentifier& identifier, CReaderNode* parentNode) : m_ParentNode(parentNode), m_Id(identifier) { } +public: + CReaderNode(const CIdentifier& identifier, CReaderNode* parentNode) : m_ParentNode(parentNode), m_Id(identifier) { } - private: - CReaderNode() = delete; +private: + CReaderNode() = delete; - public: +public: - CReaderNode* m_ParentNode = nullptr; - CIdentifier m_Id; - size_t m_ContentSize = 0; - size_t m_ReadContentSize = 0; - unsigned char* m_Buffer = nullptr; - }; - } // namespace -} // namespace EBML + CReaderNode* m_ParentNode = nullptr; + CIdentifier m_Id; + size_t m_ContentSize = 0; + size_t m_ReadContentSize = 0; + unsigned char* m_Buffer = nullptr; +}; +} // namespace +} // namespace EBML // ________________________________________________________________________________________________________________ // -namespace EBML +namespace EBML { +namespace { +class CReader final : public IReader { - namespace - { - class CReader final : public IReader - { - public: +public: - explicit CReader(IReaderCallback& callback) : m_readerCB(callback) { } - ~CReader() override; - bool processData(const void* buffer, const size_t size) override; - CIdentifier getCurrentNodeID() const override; - size_t getCurrentNodeSize() const override; - void release() override; + explicit CReader(IReaderCallback& callback) : m_readerCB(callback) { } + ~CReader() override; + bool processData(const void* buffer, const size_t size) override; + CIdentifier getCurrentNodeID() const override; + size_t getCurrentNodeSize() const override; + void release() override; - protected: +protected: - enum EStatus - { - FillingIdentifier, - FillingContentSize, - FillingContent, - }; - - IReaderCallback& m_readerCB; - CReaderNode* m_currentNode = nullptr; - size_t m_pendingSize = 0; - size_t m_nPending = 0; - unsigned char* m_pending = nullptr; - EStatus m_status = FillingIdentifier; - EStatus m_lastStatus = FillingIdentifier; - CIdentifier m_currentID = 0; - size_t m_currentContentSize = 0; - size_t m_totalBytes = 0; - }; - } // namespace -} // namespace EBML + enum EStatus + { + FillingIdentifier, + FillingContentSize, + FillingContent, + }; + + IReaderCallback& m_readerCB; + CReaderNode* m_currentNode = nullptr; + size_t m_pendingSize = 0; + size_t m_nPending = 0; + unsigned char* m_pending = nullptr; + EStatus m_status = FillingIdentifier; + EStatus m_lastStatus = FillingIdentifier; + CIdentifier m_currentID = 0; + size_t m_currentContentSize = 0; + size_t m_totalBytes = 0; +}; +} // namespace +} // namespace EBML // ________________________________________________________________________________________________________________ // @@ -248,7 +244,7 @@ bool CReader::processData(const void* buffer, const size_t size) } } } - break; + break; case FillingContent: { diff --git a/modules/ebml/src/IReaderHelper.cpp b/modules/ebml/src/IReaderHelper.cpp index 5086a1591e68a2c47943b7b8044e9c672b9ce9e6..da369fe0f94327b6c55c413f4ef8fc68c8fff93b 100644 --- a/modules/ebml/src/IReaderHelper.cpp +++ b/modules/ebml/src/IReaderHelper.cpp @@ -6,24 +6,22 @@ using namespace EBML; using namespace std; -namespace EBML +namespace EBML { +namespace { +class CReaderHelper final : public IReaderHelper { - namespace - { - class CReaderHelper final : public IReaderHelper - { - public: - CReaderHelper() { } - uint64_t getUInt(const void* buffer, const size_t size) override; - int64_t getInt(const void* buffer, const size_t size) override; - double getDouble(const void* buffer, const size_t size) override; - const char* getStr(const void* buffer, const size_t size) override; - void release() override; +public: + CReaderHelper() { } + uint64_t getUInt(const void* buffer, const size_t size) override; + int64_t getInt(const void* buffer, const size_t size) override; + double getDouble(const void* buffer, const size_t size) override; + const char* getStr(const void* buffer, const size_t size) override; + void release() override; - std::string m_Str; - }; - } // namespace -} // namespace EBML + std::string m_Str; +}; +} // namespace +} // namespace EBML uint64_t CReaderHelper::getUInt(const void* buffer, const size_t size) { diff --git a/modules/ebml/src/IWriter.cpp b/modules/ebml/src/IWriter.cpp index 883564a69670e86d9d4bcd5e36f6cccdef4b481b..219b4e060c73b6a22b8ef363a6de11581d499429 100644 --- a/modules/ebml/src/IWriter.cpp +++ b/modules/ebml/src/IWriter.cpp @@ -47,37 +47,35 @@ inline bool getCodedBuffer(const uint64_t value, unsigned char* buffer, size_t* // ________________________________________________________________________________________________________________ // -namespace EBML +namespace EBML { +namespace { +class CWriterNode final { - namespace - { - class CWriterNode final - { - public: +public: - CWriterNode(const CIdentifier& identifier, CWriterNode* parentNode) : m_ID(identifier), m_ParentNode(parentNode) {} - ~CWriterNode(); - void process(IWriterCallback& callback); + CWriterNode(const CIdentifier& identifier, CWriterNode* parentNode) : m_ID(identifier), m_ParentNode(parentNode) {} + ~CWriterNode(); + void process(IWriterCallback& callback); - protected: +protected: - size_t getTotalContentSize(bool identifierAndSize); + size_t getTotalContentSize(bool identifierAndSize); - private: +private: - CWriterNode() = delete; + CWriterNode() = delete; - public: +public: - CIdentifier m_ID; - CWriterNode* m_ParentNode = nullptr; - size_t m_BufferLength = 0; - unsigned char* m_Buffer = nullptr; - bool m_Buffered = false; - vector<CWriterNode*> m_Childrens; - }; - } // namespace -} // namespace EBML + CIdentifier m_ID; + CWriterNode* m_ParentNode = nullptr; + size_t m_BufferLength = 0; + unsigned char* m_Buffer = nullptr; + bool m_Buffered = false; + vector<CWriterNode*> m_Childrens; +}; +} // namespace +} // namespace EBML // ________________________________________________________________________________________________________________ // @@ -130,30 +128,28 @@ size_t CWriterNode::getTotalContentSize(const bool identifierAndSize) // ________________________________________________________________________________________________________________ // -namespace EBML +namespace EBML { +namespace { +class CWriter final : public IWriter { - namespace - { - class CWriter final : public IWriter - { - public: - - explicit CWriter(IWriterCallback& callback) : m_callback(callback) {} - bool openChild(const CIdentifier& identifier) override; - bool setChildData(const void* buffer, const size_t size) override; - bool closeChild() override; - void release() override; - - protected: - - CWriterNode* m_node = nullptr; - IWriterCallback& m_callback; - - private: - CWriter() = delete; - }; - } // namespace -} // namespace EBML +public: + + explicit CWriter(IWriterCallback& callback) : m_callback(callback) {} + bool openChild(const CIdentifier& identifier) override; + bool setChildData(const void* buffer, const size_t size) override; + bool closeChild() override; + void release() override; + +protected: + + CWriterNode* m_node = nullptr; + IWriterCallback& m_callback; + +private: + CWriter() = delete; +}; +} // namespace +} // namespace EBML // ________________________________________________________________________________________________________________ // diff --git a/modules/ebml/src/IWriterHelper.cpp b/modules/ebml/src/IWriterHelper.cpp index a0517e2631ccc32f6e187b16b8c7c507859408ed..a2e0380c30fc799d18bdf29edad65f5c36be0e81 100644 --- a/modules/ebml/src/IWriterHelper.cpp +++ b/modules/ebml/src/IWriterHelper.cpp @@ -9,33 +9,31 @@ using namespace EBML; // ________________________________________________________________________________________________________________ // -namespace EBML +namespace EBML { +namespace { +class CWriterHelper final : public IWriterHelper { - namespace - { - class CWriterHelper final : public IWriterHelper - { - public: - - CWriterHelper() { } - bool connect(IWriter* writer) override; - bool disconnect() override; - bool openChild(const CIdentifier& identifier) override; - bool closeChild() override; - bool setInt(const int64_t value) override; - bool setUInt(const uint64_t value) override; - bool setFloat(const float value) override; - bool setDouble(const double value) override; - bool setBinary(const void* buffer, const size_t size) override; - bool setStr(const char* value) override; - void release() override; - - protected: - - IWriter* m_writer = nullptr; - }; - } // namespace -} // namespace EBML +public: + + CWriterHelper() { } + bool connect(IWriter* writer) override; + bool disconnect() override; + bool openChild(const CIdentifier& identifier) override; + bool closeChild() override; + bool setInt(const int64_t value) override; + bool setUInt(const uint64_t value) override; + bool setFloat(const float value) override; + bool setDouble(const double value) override; + bool setBinary(const void* buffer, const size_t size) override; + bool setStr(const char* value) override; + void release() override; + +protected: + + IWriter* m_writer = nullptr; +}; +} // namespace +} // namespace EBML // ________________________________________________________________________________________________________________ // diff --git a/modules/fs/CMakeLists.txt b/modules/fs/CMakeLists.txt index d65e43d476b4aeb7284cbf34d7f5835c62107fcc..ced47613b7ed075700f70b36dba4eb15fbe884e2 100755 --- a/modules/fs/CMakeLists.txt +++ b/modules/fs/CMakeLists.txt @@ -14,12 +14,14 @@ ADD_LIBRARY(${PROJECT_NAME} SHARED ${SRC_FILES}) SET_TARGET_PROPERTIES(${PROJECT_NAME} PROPERTIES VERSION ${PROJECT_VERSION} SOVERSION ${PROJECT_VERSION_MAJOR} + FOLDER ${MODULES_FOLDER} COMPILE_FLAGS "-DFS_Shared -DFS_Exports") ADD_LIBRARY(${PROJECT_NAME}-static STATIC ${SRC_FILES}) SET_TARGET_PROPERTIES(${PROJECT_NAME}-static PROPERTIES VERSION ${PROJECT_VERSION} SOVERSION ${PROJECT_VERSION_MAJOR} + FOLDER ${MODULES_FOLDER} COMPILE_FLAGS "-DFS_Static -DFS_Exports") IF(UNIX) @@ -32,9 +34,7 @@ INCLUDE("FindThirdPartyBoost_FileSystem") # --------------------------------- # Target macros -# Defines target operating system -# Defines target architecture -# Defines target compiler +# Defines target operating system, architecture and compiler # --------------------------------- SET_BUILD_PLATFORM() diff --git a/modules/fs/include/fs/Files.h b/modules/fs/include/fs/Files.h index d04edbf30b84545989fc50bb664896af434771fc..ac851f86d46cb267b4f03239495b09a6b72d08bf 100644 --- a/modules/fs/include/fs/Files.h +++ b/modules/fs/include/fs/Files.h @@ -4,60 +4,59 @@ #include <cstdio> #include <fstream> -namespace FS +namespace FS { +class FS_API Files { - class FS_API Files - { - public: - static FILE* open(const char* file, const char* mode); - static FILE* popen(const char* file, const char* mode); - static void openOFStream(std::ofstream& stream, const char* file, std::ios_base::openmode mode = std::ios_base::out); - static void openIFStream(std::ifstream& stream, const char* file, std::ios_base::openmode mode = std::ios_base::in); - static void openFStream(std::fstream& stream, const char* file, std::ios_base::openmode mode); - - static bool equals(const char* pFile1, const char* pFile2); - static bool fileExists(const char* pathToCheck); - static bool directoryExists(const char* pathToCheck); - // Creates all components of a path to the filesystem - static bool createPath(const char* path); - // Creates all components of a path to the filesystem except the last part (i.e. for paths including a filename in the end) - static bool createParentPath(const char* path); - // Returns a path omitting the last part of it (essentially boost::filesystem::parent_path). Output sParentPath needs to be pre-allocated. - static bool getParentPath(const char* path, char* parentPath); - static bool getParentPath(const char* path, char* parentPath, size_t size); - - /** - * \brief Fills filename as a component of a path - * \param path [in]: input path - * \param filename [out]: file name, needs to be pre-allocated - * - * (essentially boost::filesystem::filename) - * \return Success status - */ - static bool getFilename(const char* path, char* filename); - static bool getFilename(const char* path, char* filename, size_t size); - - /** - * \brief Fills filename as a component of a path without the extension - * \param path [in]: input path - * \param filename [out]: file name without extension, needs to be pre-allocated - * - * (essentially boost::filesystem::filename) - * \return Success status - */ - static bool getFilenameWithoutExtension(const char* path, char* filename); - static bool getFilenameWithoutExtension(const char* path, char* filename, size_t size); - // Returns the extension component of a path - static bool getFilenameExtension(const char* path, char* fileNameExtension); - static bool getFilenameExtension(const char* path, char* extension, size_t size); - - static bool copyFile(const char* srcFile, const char* dstPath); - static bool copyDirectory(const char* srcDir, const char* dstDir); - - static bool remove(const char* path); - static bool removeAll(const char* path); - private: - - Files() = delete; - }; -} // namespace FS +public: + static FILE* open(const char* file, const char* mode); + static FILE* popen(const char* file, const char* mode); + static void openOFStream(std::ofstream& stream, const char* file, std::ios_base::openmode mode = std::ios_base::out); + static void openIFStream(std::ifstream& stream, const char* file, std::ios_base::openmode mode = std::ios_base::in); + static void openFStream(std::fstream& stream, const char* file, std::ios_base::openmode mode); + + static bool equals(const char* pFile1, const char* pFile2); + static bool fileExists(const char* pathToCheck); + static bool directoryExists(const char* pathToCheck); + // Creates all components of a path to the filesystem + static bool createPath(const char* path); + // Creates all components of a path to the filesystem except the last part (i.e. for paths including a filename in the end) + static bool createParentPath(const char* path); + // Returns a path omitting the last part of it (essentially boost::filesystem::parent_path). Output sParentPath needs to be pre-allocated. + static bool getParentPath(const char* path, char* parentPath); + static bool getParentPath(const char* path, char* parentPath, size_t size); + + /** + * \brief Fills filename as a component of a path + * \param path [in]: input path + * \param filename [out]: file name, needs to be pre-allocated + * + * (essentially boost::filesystem::filename) + * \return Success status + */ + static bool getFilename(const char* path, char* filename); + static bool getFilename(const char* path, char* filename, size_t size); + + /** + * \brief Fills filename as a component of a path without the extension + * \param path [in]: input path + * \param filename [out]: file name without extension, needs to be pre-allocated + * + * (essentially boost::filesystem::filename) + * \return Success status + */ + static bool getFilenameWithoutExtension(const char* path, char* filename); + static bool getFilenameWithoutExtension(const char* path, char* filename, size_t size); + // Returns the extension component of a path + static bool getFilenameExtension(const char* path, char* fileNameExtension); + static bool getFilenameExtension(const char* path, char* extension, size_t size); + + static bool copyFile(const char* srcFile, const char* dstPath); + static bool copyDirectory(const char* srcDir, const char* dstDir); + + static bool remove(const char* path); + static bool removeAll(const char* path); +private: + + Files() = delete; +}; +} // namespace FS diff --git a/modules/fs/include/fs/IEntryEnumerator.h b/modules/fs/include/fs/IEntryEnumerator.h index 900ea8b7dd40de60f7315afb31c71e8f7e3fceca..d9fb25d75f7d591645d57d8b476700aee0ee243f 100644 --- a/modules/fs/include/fs/IEntryEnumerator.h +++ b/modules/fs/include/fs/IEntryEnumerator.h @@ -4,52 +4,51 @@ #include <cinttypes> #include <cstdlib> // size_t for unix -namespace FS +namespace FS { +class IEntryEnumeratorCallBack; + +class FS_API IEntryEnumerator { - class IEntryEnumeratorCallBack; +public: - class FS_API IEntryEnumerator + class FS_API IAttributes { public: + virtual bool isFile() = 0; + virtual bool isDirectory() = 0; + virtual bool isSymbolicLink() = 0; + + virtual bool isArchive() = 0; + virtual bool isReadOnly() = 0; + virtual bool isHidden() = 0; + virtual bool isSystem() = 0; + virtual bool isExecutable() = 0; - class FS_API IAttributes - { - public: - virtual bool isFile() = 0; - virtual bool isDirectory() = 0; - virtual bool isSymbolicLink() = 0; - - virtual bool isArchive() = 0; - virtual bool isReadOnly() = 0; - virtual bool isHidden() = 0; - virtual bool isSystem() = 0; - virtual bool isExecutable() = 0; - - virtual size_t getSize() = 0; - protected: - virtual ~IAttributes() {} - }; - - class FS_API IEntry - { - public: - virtual const char* getName() = 0; - protected: - virtual ~IEntry() {} - }; - - virtual bool enumerate(const char* sWildcard, bool bRecursive = false) = 0; - virtual void release() = 0; + virtual size_t getSize() = 0; protected: - virtual ~IEntryEnumerator() { } + virtual ~IAttributes() {} }; - class FS_API IEntryEnumeratorCallBack + class FS_API IEntry { public: - virtual bool callback(IEntryEnumerator::IEntry& rEntry, IEntryEnumerator::IAttributes& rAttributes) = 0; - virtual ~IEntryEnumeratorCallBack() { } + virtual const char* getName() = 0; + protected: + virtual ~IEntry() {} }; - extern FS_API IEntryEnumerator* createEntryEnumerator(IEntryEnumeratorCallBack& rCallBack); -} // namespace FS + virtual bool enumerate(const char* sWildcard, bool bRecursive = false) = 0; + virtual void release() = 0; +protected: + virtual ~IEntryEnumerator() { } +}; + +class FS_API IEntryEnumeratorCallBack +{ +public: + virtual bool callback(IEntryEnumerator::IEntry& rEntry, IEntryEnumerator::IAttributes& rAttributes) = 0; + virtual ~IEntryEnumeratorCallBack() { } +}; + +extern FS_API IEntryEnumerator* createEntryEnumerator(IEntryEnumeratorCallBack& rCallBack); +} // namespace FS diff --git a/modules/fs/include/fs/defines.h b/modules/fs/include/fs/defines.h index 77767473be822f662a06681f7435f97b6370ae4f..c17653f3535ac56a244c39f3707bc7927c7a996d 100644 --- a/modules/fs/include/fs/defines.h +++ b/modules/fs/include/fs/defines.h @@ -3,23 +3,23 @@ #include <ov_common_defines.h> #if defined FS_Shared -#if defined TARGET_OS_Windows -#define FS_API_Export __declspec(dllexport) -#define FS_API_Import __declspec(dllimport) -#elif defined TARGET_OS_Linux || defined TARGET_OS_MacOS - #define FS_API_Export __attribute__((visibility("default"))) - #define FS_API_Import __attribute__((visibility("default"))) +# if defined TARGET_OS_Windows +# define FS_API_Export __declspec(dllexport) +# define FS_API_Import __declspec(dllimport) +# elif defined TARGET_OS_Linux || defined TARGET_OS_MacOS +# define FS_API_Export __attribute__((visibility("default"))) +# define FS_API_Import __attribute__((visibility("default"))) +# else +# define FS_API_Export +# define FS_API_Import +# endif #else - #define FS_API_Export - #define FS_API_Import -#endif -#else -#define FS_API_Export -#define FS_API_Import +# define FS_API_Export +# define FS_API_Import #endif #if defined FS_Exports -#define FS_API FS_API_Export +# define FS_API FS_API_Export #else - #define FS_API FS_API_Import +# define FS_API FS_API_Import #endif diff --git a/modules/fs/src/Files.cpp b/modules/fs/src/Files.cpp index da2cba04e02c334369746d4c936d351460cd7315..cff2c4a3cb7aee9b4d053ff853cd1696d779f7a2 100644 --- a/modules/fs/src/Files.cpp +++ b/modules/fs/src/Files.cpp @@ -162,8 +162,10 @@ bool Files::equals(const char* pFile1, const char* pFile2) bool res = true; if (pFile1 && pFile2) { - const HANDLE handle1 = ::CreateFile(pFile1, 0, FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, nullptr); - const HANDLE handle2 = ::CreateFile(pFile2, 0, FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, nullptr); + const HANDLE handle1 = ::CreateFile(pFile1, 0, FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, + FILE_FLAG_BACKUP_SEMANTICS, nullptr); + const HANDLE handle2 = ::CreateFile(pFile2, 0, FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, + FILE_FLAG_BACKUP_SEMANTICS, nullptr); if (handle1 && handle2) { BY_HANDLE_FILE_INFORMATION stat1; @@ -173,10 +175,10 @@ bool Files::equals(const char* pFile1, const char* pFile2) if (!bStat1 && !bStat2) { res = true; } else if (bStat1 && bStat2) { - res = (stat1.dwVolumeSerialNumber == stat2.dwVolumeSerialNumber) && (stat1.nFileIndexHigh == stat2.nFileIndexHigh) - && (stat1.nFileIndexLow == stat2.nFileIndexLow) && (stat1.nFileSizeHigh == stat2.nFileSizeHigh) - && (stat1.nFileSizeLow == stat2.nFileSizeLow) && (stat1.ftLastWriteTime.dwHighDateTime == stat2.ftLastWriteTime.dwHighDateTime) - && (stat1.ftLastWriteTime.dwLowDateTime == stat2.ftLastWriteTime.dwLowDateTime); + res = (stat1.dwVolumeSerialNumber == stat2.dwVolumeSerialNumber) && (stat1.nFileIndexHigh == stat2.nFileIndexHigh) + && (stat1.nFileIndexLow == stat2.nFileIndexLow) && (stat1.nFileSizeHigh == stat2.nFileSizeHigh) + && (stat1.nFileSizeLow == stat2.nFileSizeLow) && (stat1.ftLastWriteTime.dwHighDateTime == stat2.ftLastWriteTime.dwHighDateTime) + && (stat1.ftLastWriteTime.dwLowDateTime == stat2.ftLastWriteTime.dwLowDateTime); } else { res = false; } CloseHandle(handle1); @@ -333,7 +335,6 @@ bool Files::removeAll(const char* path) } - // old boost compliance // manage cases here diff --git a/modules/fs/src/IEntryEnumerator.cpp b/modules/fs/src/IEntryEnumerator.cpp index 3daa0e7926b2ea89376a773acf3a0d15b3a91a68..b7e4c2dbe8d4df33455049e95963f9a7c5abb8e2 100755 --- a/modules/fs/src/IEntryEnumerator.cpp +++ b/modules/fs/src/IEntryEnumerator.cpp @@ -25,65 +25,62 @@ using namespace FS; // ________________________________________________________________________________________________________________ // -namespace FS +namespace FS { +class CEntry final : public IEntryEnumerator::IEntry { - class CEntry final : public IEntryEnumerator::IEntry - { - public: +public: - explicit CEntry(const string& name) : m_Name(name) {} - const char* getName() override { return m_Name.c_str(); } + explicit CEntry(const string& name) : m_Name(name) {} + const char* getName() override { return m_Name.c_str(); } - string m_Name; - }; -} // namespace FS + string m_Name; +}; +} // namespace FS // ________________________________________________________________________________________________________________ // -namespace FS +namespace FS { +class CAttributes final : public IEntryEnumerator::IAttributes { - class CAttributes final : public IEntryEnumerator::IAttributes - { - public: - - CAttributes() {} - ~CAttributes() override {} - bool isFile() override { return m_IsFile; } - bool isDirectory() override { return m_IsDirectory; } - bool isSymbolicLink() override { return m_IsSymbolicLink; } - bool isArchive() override { return m_IsArchive; } - bool isReadOnly() override { return m_IsReadOnly; } - bool isHidden() override { return m_IsHidden; } - bool isSystem() override { return m_IsSystem; } - bool isExecutable() override { return m_IsExecutable; } - size_t getSize() override { return m_Size; } - - bool m_IsFile = false; - bool m_IsDirectory = false; - bool m_IsSymbolicLink = false; - bool m_IsArchive = false; - bool m_IsReadOnly = false; - bool m_IsHidden = false; - bool m_IsSystem = false; - bool m_IsExecutable = false; - size_t m_Size = 0; - }; +public: + + CAttributes() {} + ~CAttributes() override {} + bool isFile() override { return m_IsFile; } + bool isDirectory() override { return m_IsDirectory; } + bool isSymbolicLink() override { return m_IsSymbolicLink; } + bool isArchive() override { return m_IsArchive; } + bool isReadOnly() override { return m_IsReadOnly; } + bool isHidden() override { return m_IsHidden; } + bool isSystem() override { return m_IsSystem; } + bool isExecutable() override { return m_IsExecutable; } + size_t getSize() override { return m_Size; } + + bool m_IsFile = false; + bool m_IsDirectory = false; + bool m_IsSymbolicLink = false; + bool m_IsArchive = false; + bool m_IsReadOnly = false; + bool m_IsHidden = false; + bool m_IsSystem = false; + bool m_IsExecutable = false; + size_t m_Size = 0; +}; } // namespace FS // ________________________________________________________________________________________________________________ // -namespace FS +namespace FS { +class CEntryEnumerator : public IEntryEnumerator { - class CEntryEnumerator : public IEntryEnumerator - { - public: - explicit CEntryEnumerator(IEntryEnumeratorCallBack& rEntryEnumeratorCallBack) : m_entryEnumeratorCB(rEntryEnumeratorCallBack) {} - void release() override { delete this; } - protected: - IEntryEnumeratorCallBack& m_entryEnumeratorCB; - }; +public: + explicit CEntryEnumerator(IEntryEnumeratorCallBack& rEntryEnumeratorCallBack) : m_entryEnumeratorCB(rEntryEnumeratorCallBack) {} + void release() override { delete this; } +protected: + IEntryEnumeratorCallBack& m_entryEnumeratorCB; +}; // ________________________________________________________________________________________________________________ // @@ -96,12 +93,12 @@ namespace FS }; #elif defined TARGET_OS_Windows - class CEntryEnumeratorWindows final : public CEntryEnumerator - { - public: - explicit CEntryEnumeratorWindows(IEntryEnumeratorCallBack& rEntryEnumeratorCallBack) : CEntryEnumerator(rEntryEnumeratorCallBack) {} - bool enumerate(const char* sWildCard, bool bRecursive = false) override; - }; +class CEntryEnumeratorWindows final : public CEntryEnumerator +{ +public: + explicit CEntryEnumeratorWindows(IEntryEnumeratorCallBack& rEntryEnumeratorCallBack) : CEntryEnumerator(rEntryEnumeratorCallBack) {} + bool enumerate(const char* sWildCard, bool bRecursive = false) override; +}; #else class CEntryEnumeratorDummy : public CEntryEnumerator @@ -112,7 +109,7 @@ namespace FS }; #endif -} // namespace FS +} // namespace FS // ________________________________________________________________________________________________________________ // diff --git a/modules/socket/CMakeLists.txt b/modules/socket/CMakeLists.txt index 32060a78f519e5fb4a11d0fc4b2735f8205ae60e..a59f530c368da417a38ec850ad9c40018bff94f9 100644 --- a/modules/socket/CMakeLists.txt +++ b/modules/socket/CMakeLists.txt @@ -14,12 +14,14 @@ ADD_LIBRARY(${PROJECT_NAME} SHARED ${SRC_FILES}) SET_TARGET_PROPERTIES(${PROJECT_NAME} PROPERTIES VERSION ${PROJECT_VERSION} SOVERSION ${PROJECT_VERSION_MAJOR} + FOLDER ${MODULES_FOLDER} COMPILE_FLAGS "-DSocket_Shared -DSocket_Exports") ADD_LIBRARY(${PROJECT_NAME}-static STATIC ${SRC_FILES}) SET_TARGET_PROPERTIES(${PROJECT_NAME}-static PROPERTIES VERSION ${PROJECT_VERSION} SOVERSION ${PROJECT_VERSION_MAJOR} + FOLDER ${MODULES_FOLDER} COMPILE_FLAGS "-DSocket_Static -DSocket_Exports") IF(UNIX) @@ -52,9 +54,7 @@ ENDIF(WIN32) # --------------------------------- # Target macros -# Defines target operating system -# Defines target architecture -# Defines target compiler +# Defines target operating system, architecture and compiler # --------------------------------- SET_BUILD_PLATFORM() diff --git a/modules/socket/include/socket/IConnection.h b/modules/socket/include/socket/IConnection.h index f58bcc8410b1ac0891753443742f72874a035866..bb85e38398707f587a96174ac9bb1dc9a744d408 100644 --- a/modules/socket/include/socket/IConnection.h +++ b/modules/socket/include/socket/IConnection.h @@ -3,33 +3,32 @@ #include "defines.h" #include <cstdlib> // For Unix Compatibility -namespace Socket +namespace Socket { +class Socket_API IConnection { - class Socket_API IConnection - { - protected: +protected: - virtual bool open() = 0; + virtual bool open() = 0; - public: +public: - virtual bool close() = 0; + virtual bool close() = 0; - virtual bool isReadyToSend(const size_t timeOut = 0) const = 0; - virtual bool isReadyToReceive(const size_t timeOut = 0) const = 0; + virtual bool isReadyToSend(const size_t timeOut = 0) const = 0; + virtual bool isReadyToReceive(const size_t timeOut = 0) const = 0; - virtual size_t sendBuffer(const void* buffer, const size_t size) = 0; - virtual size_t receiveBuffer(void* buffer, const size_t size) = 0; + virtual size_t sendBuffer(const void* buffer, const size_t size) = 0; + virtual size_t receiveBuffer(void* buffer, const size_t size) = 0; - virtual bool sendBufferBlocking(const void* buffer, const size_t size) = 0; - virtual bool receiveBufferBlocking(void* buffer, const size_t size) = 0; + virtual bool sendBufferBlocking(const void* buffer, const size_t size) = 0; + virtual bool receiveBufferBlocking(void* buffer, const size_t size) = 0; - virtual bool isConnected() const = 0; + virtual bool isConnected() const = 0; - virtual void release() = 0; + virtual void release() = 0; - protected: +protected: - virtual ~IConnection() = default; - }; -} // namespace Socket + virtual ~IConnection() = default; +}; +} // namespace Socket diff --git a/modules/socket/include/socket/IConnectionBluetooth.h b/modules/socket/include/socket/IConnectionBluetooth.h index 67060f481e20e032dced0d29e9f12ca2de3ff2f4..c162e8b67de7a69e54c475d42e93fdd3658b787b 100644 --- a/modules/socket/include/socket/IConnectionBluetooth.h +++ b/modules/socket/include/socket/IConnectionBluetooth.h @@ -3,88 +3,88 @@ #include "IConnection.h" #include <array> +#include <cstdio> -namespace Socket +namespace Socket { +class Socket_API IConnectionBluetooth : public IConnection { - class Socket_API IConnectionBluetooth : public IConnection +public: + + /** + * \brief Connect to the bluetooth device. + * \param[in] address the MAC address of the Bluetooth device. + * \return If the function succeeds, the return value is true, else false. + */ + virtual bool connect(const uint64_t address) = 0; + + /** + * \brief Return the input serial pending byte count. + * \return The number of pending byte. + */ + virtual size_t getPendingByteCount() = 0; + + /** + * \brief Flush the input serial buffer. + * \return If the function succeeds, the return value is true, else false. + */ + virtual const char* getLastError() const = 0; + + /** + * \brief Clear the last error registered. + */ + virtual void clearError() = 0; + + /** + * \brief List the paired bluetooth devices: Name and Bluetooth MAC address. + * + * \param[out] nPairedDevices the Bluetooth devices count. + * \param[out] names an array of Bluetooth names. + * \param[out] addresses an array of Bluetooth addresses. + * + * \return If the function succeeds, the return value is true, else false. + */ + virtual bool listPairedBluetoothDevices(size_t* nPairedDevices, char** names, uint64_t** addresses) = 0; + + /** + * \brief Convert string MAC Bluetooth address to hexadecimal. + * \param[out] straddr string MAC Bluetooth address. + * \param[out] btaddr hexadecimal MAC Bluetooth address. + * \retval true in case of success. + * \retval false in case of failure: if the address does not match: %02x:%02x:%02x:%02x:%02x:%02x + */ + static bool string2BluetoothAddress(const char* straddr, uint64_t* btaddr) { - public: - - /** - * \brief Connect to the bluetooth device. - * \param[in] address the MAC address of the Bluetooth device. - * \return If the function succeeds, the return value is true, else false. - */ - virtual bool connect(const uint64_t address) = 0; - - /** - * \brief Return the input serial pending byte count. - * \return The number of pending byte. - */ - virtual size_t getPendingByteCount() = 0; - - /** - * \brief Flush the input serial buffer. - * \return If the function succeeds, the return value is true, else false. - */ - virtual const char* getLastError() const = 0; - - /** - * \brief Clear the last error registered. - */ - virtual void clearError() = 0; - - /** - * \brief List the paired bluetooth devices: Name and Bluetooth MAC address. - * - * \param[out] nPairedDevices the Bluetooth devices count. - * \param[out] names an array of Bluetooth names. - * \param[out] addresses an array of Bluetooth addresses. - * - * \return If the function succeeds, the return value is true, else false. - */ - virtual bool listPairedBluetoothDevices(size_t* nPairedDevices, char** names, uint64_t** addresses) = 0; - - /** - * \brief Convert string MAC Bluetooth address to hexadecimal. - * \param[out] straddr string MAC Bluetooth address. - * \param[out] btaddr hexadecimal MAC Bluetooth address. - * \retval true in case of success. - * \retval false in case of failure: if the address does not match: %02x:%02x:%02x:%02x:%02x:%02x - */ - static bool string2BluetoothAddress(const char* straddr, uint64_t* btaddr) - { - std::array<uint32_t, 6> aaddr = { 0, 0, 0, 0, 0, 0 }; - - const int value = sscanf(straddr, "%02x:%02x:%02x:%02x:%02x:%02x", &aaddr[0], &aaddr[1], &aaddr[2], &aaddr[3], &aaddr[4], &aaddr[5]); + std::array<uint32_t, 6> aaddr = { 0, 0, 0, 0, 0, 0 }; - if (value != 6) { return false; } + const int value = sscanf(straddr, "%02x:%02x:%02x:%02x:%02x:%02x", &aaddr[0], &aaddr[1], &aaddr[2], &aaddr[3], &aaddr[4], &aaddr[5]); - *btaddr = 0; + if (value != 6) { return false; } - for (size_t i = 0; i < 6; ++i) - { - const uint64_t tmpaddr = static_cast<uint64_t>(aaddr[i] & 0xff); - *btaddr = (*btaddr << 8) + tmpaddr; - } + *btaddr = 0; - return true; + for (size_t i = 0; i < 6; ++i) + { + const uint64_t tmpaddr = static_cast<uint64_t>(aaddr[i] & 0xff); + *btaddr = (*btaddr << 8) + tmpaddr; } + return true; + } + - protected: +protected: #if defined TARGET_OS_Windows - static const unsigned char WIN_SOCKET_MAJOR_VERSION = 2; // Winsock major version to use - static const unsigned char WIN_SOCKET_MINOR_VERSION = 2; // Winsock minor version to use + static const unsigned char WIN_SOCKET_MAJOR_VERSION = 2; // Winsock major version to use + static const unsigned char WIN_SOCKET_MINOR_VERSION = 2; // Winsock minor version to use - static bool m_isWinsockInitialized; + static bool m_isWinsockInitialized; #elif defined TARGET_OS_Linux || defined TARGET_OS_MacOS #endif - }; +}; - extern Socket_API IConnectionBluetooth* createConnectionBluetooth(); -} // namespace Socket +extern Socket_API IConnectionBluetooth* createConnectionBluetooth(); +} // namespace Socket diff --git a/modules/socket/include/socket/IConnectionClient.h b/modules/socket/include/socket/IConnectionClient.h index 0e7a6ea1bc90a0cf3cd093dc47996e55671f9e7c..061557179dcff93dbe8cb3a549df3a30ab0e5f5d 100644 --- a/modules/socket/include/socket/IConnectionClient.h +++ b/modules/socket/include/socket/IConnectionClient.h @@ -2,14 +2,13 @@ #include "IConnection.h" -namespace Socket +namespace Socket { +class Socket_API IConnectionClient : public IConnection { - class Socket_API IConnectionClient : public IConnection - { - public: +public: - virtual bool connect(const char* serverName, const size_t serverPort, const size_t timeOut = 0xffffffff) = 0; - }; + virtual bool connect(const char* serverName, const size_t serverPort, const size_t timeOut = 0xffffffff) = 0; +}; - extern Socket_API IConnectionClient* createConnectionClient(); -} // namespace Socket +extern Socket_API IConnectionClient* createConnectionClient(); +} // namespace Socket diff --git a/modules/socket/include/socket/IConnectionParallel.h b/modules/socket/include/socket/IConnectionParallel.h index a426b2f53856dc42f53ecd6a795f9a4bc823ba2a..5566a7ed9fb82d0dcc88d948a9cd07bb836b067c 100644 --- a/modules/socket/include/socket/IConnectionParallel.h +++ b/modules/socket/include/socket/IConnectionParallel.h @@ -7,36 +7,35 @@ #include <windows.h> #endif -namespace Socket +namespace Socket { +/** + * \brief The IConnectionParallel class provides the possibility to communicate with a parallel port. + * On Windows, you must have TVicPort library installed (available for free: http://entechtaiwan.com/dev/port/index.shtm). + */ +class Socket_API IConnectionParallel : public IConnection { - /** - * \brief The IConnectionParallel class provides the possibility to communicate with a parallel port. - * On Windows, you must have TVicPort library installed (available for free: http://entechtaiwan.com/dev/port/index.shtm). - */ - class Socket_API IConnectionParallel : public IConnection - { - public: +public: - virtual bool connect(const unsigned short port) = 0; + virtual bool connect(const unsigned short port) = 0; - virtual std::string getLastError() = 0; + virtual std::string getLastError() = 0; - protected: +protected: #if defined TARGET_OS_Windows - typedef bool (CALLBACK * port_open_t)(); - typedef void (CALLBACK * port_close_t)(); - typedef bool (CALLBACK * port_is_driver_opened_t)(); - typedef bool (CALLBACK * port_write_t)(unsigned short, unsigned char); + typedef bool (CALLBACK * port_open_t)(); + typedef void (CALLBACK * port_close_t)(); + typedef bool (CALLBACK * port_is_driver_opened_t)(); + typedef bool (CALLBACK * port_write_t)(unsigned short, unsigned char); - HMODULE m_port = nullptr; + HMODULE m_port = nullptr; - port_open_t m_portOpen = nullptr; - port_close_t m_portClose = nullptr; - port_is_driver_opened_t m_isDriverOpened = nullptr; - port_write_t m_portWrite = nullptr; + port_open_t m_portOpen = nullptr; + port_close_t m_portClose = nullptr; + port_is_driver_opened_t m_isDriverOpened = nullptr; + port_write_t m_portWrite = nullptr; #endif - }; +}; - extern Socket_API IConnectionParallel* createConnectionParallel(); -} // namespace Socket +extern Socket_API IConnectionParallel* createConnectionParallel(); +} // namespace Socket diff --git a/modules/socket/include/socket/IConnectionSerial.h b/modules/socket/include/socket/IConnectionSerial.h index 90607225c11174945b9920e74dc6cb9d5635b3f4..26dc1bdb80d2dbaf09e44b628341281bb9336871 100644 --- a/modules/socket/include/socket/IConnectionSerial.h +++ b/modules/socket/include/socket/IConnectionSerial.h @@ -3,53 +3,52 @@ #include "IConnection.h" #include <string> -namespace Socket +namespace Socket { +class Socket_API IConnectionSerial : public IConnection { - class Socket_API IConnectionSerial : public IConnection - { - public: - - virtual bool connect(const char* url, const size_t baudRate) = 0; - - /** - * \brief Return the input serial pending byte count. - * \return The number of pending byte. - */ - virtual size_t getPendingByteCount() = 0; - - /** - * \brief Flush the input serial buffer. - * \return If the function succeeds, the return value is true, else false. - */ - virtual bool flush() = 0; - - /** - * \brief Flush the input serial buffer. - * \return If the function succeeds, the return value is true, else false. - */ - virtual const char* getLastError() = 0; - - /** - * \brief Checks if an error raised. - * \return True if the m_LastError is not empty, else false. - */ - virtual bool isErrorRaised() = 0; - - /** - * \brief Clear the last error registered. - */ - virtual void clearError() = 0; - - /** - * \brief Set tiemouts for read and write function. - * \param timeout [in] Timeout in deciseconds. - * \return True if succeed, else false. - */ - virtual bool setTimeouts(const size_t timeout) = 0; - - protected: - void saveLastError(); - }; - - extern Socket_API IConnectionSerial* createConnectionSerial(); -} // namespace Socket +public: + + virtual bool connect(const char* url, const size_t baudRate) = 0; + + /** + * \brief Return the input serial pending byte count. + * \return The number of pending byte. + */ + virtual size_t getPendingByteCount() = 0; + + /** + * \brief Flush the input serial buffer. + * \return If the function succeeds, the return value is true, else false. + */ + virtual bool flush() = 0; + + /** + * \brief Flush the input serial buffer. + * \return If the function succeeds, the return value is true, else false. + */ + virtual const char* getLastError() = 0; + + /** + * \brief Checks if an error raised. + * \return True if the m_LastError is not empty, else false. + */ + virtual bool isErrorRaised() = 0; + + /** + * \brief Clear the last error registered. + */ + virtual void clearError() = 0; + + /** + * \brief Set tiemouts for read and write function. + * \param timeout [in] Timeout in deciseconds. + * \return True if succeed, else false. + */ + virtual bool setTimeouts(const size_t timeout) = 0; + +protected: + void saveLastError(); +}; + +extern Socket_API IConnectionSerial* createConnectionSerial(); +} // namespace Socket diff --git a/modules/socket/include/socket/IConnectionSerialDelegate.h b/modules/socket/include/socket/IConnectionSerialDelegate.h index e0a7501806e6a63e208ab886802431f9dc93cd6e..df41f5300169b6b0ea87a739758a184eae97d380 100644 --- a/modules/socket/include/socket/IConnectionSerialDelegate.h +++ b/modules/socket/include/socket/IConnectionSerialDelegate.h @@ -3,33 +3,32 @@ #include "TConnectionDelegate.h" #include "IConnectionSerial.h" -namespace Socket +namespace Socket { +struct Socket_API SConnectionSerialDelegate { - struct Socket_API SConnectionSerialDelegate - { - SConnectionDelegate connectionDelegate; - bool (*fpConnect)(void*, const char*, const size_t); - size_t (*fpGetPendingByteCount)(void*); - bool (*fpFlush)(void*); - const char* (*fpGetLastError)(void*); - void (*fpSaveLastError)(void*); - // TODO for Android compatibility - //bool(*fpIsErrorRaised)(void*); - //void(*fpClearError)(void*); - //bool(*fSetTimeouts)(void*, const size_t decisecondsTimeout); - }; + SConnectionDelegate connectionDelegate; + bool (*fpConnect)(void*, const char*, const size_t); + size_t (*fpGetPendingByteCount)(void*); + bool (*fpFlush)(void*); + const char* (*fpGetLastError)(void*); + void (*fpSaveLastError)(void*); + // TODO for Android compatibility + //bool(*fpIsErrorRaised)(void*); + //void(*fpClearError)(void*); + //bool(*fSetTimeouts)(void*, const size_t decisecondsTimeout); +}; - class Socket_API IConnectionSerialDelegate : public TConnectionDelegate<IConnectionSerial> - { - public: - IConnectionSerialDelegate(const SConnectionSerialDelegate connectionSerialDelegate) - : TConnectionDelegate<IConnectionSerial>(connectionSerialDelegate.connectionDelegate) { } +class Socket_API IConnectionSerialDelegate : public TConnectionDelegate<IConnectionSerial> +{ +public: + IConnectionSerialDelegate(const SConnectionSerialDelegate connectionSerialDelegate) + : TConnectionDelegate<IConnectionSerial>(connectionSerialDelegate.connectionDelegate) { } - ~IConnectionSerialDelegate() override { } + ~IConnectionSerialDelegate() override { } - protected: - SConnectionSerialDelegate m_connectionSerialDelegate; - }; +protected: + SConnectionSerialDelegate m_connectionSerialDelegate; +}; - extern Socket_API IConnectionSerialDelegate* createConnectionSerialDelegate(SConnectionSerialDelegate connectionSerialDelegate); -} // namespace Socket +extern Socket_API IConnectionSerialDelegate* createConnectionSerialDelegate(SConnectionSerialDelegate connectionSerialDelegate); +} // namespace Socket diff --git a/modules/socket/include/socket/IConnectionServer.h b/modules/socket/include/socket/IConnectionServer.h index a207c63e75e5cfc432fc8d1a041bbea23bb01ca3..0a74299eeab84b16a2c61f85e83cf9f1644a00ac 100644 --- a/modules/socket/include/socket/IConnectionServer.h +++ b/modules/socket/include/socket/IConnectionServer.h @@ -2,29 +2,28 @@ #include "IConnection.h" -namespace Socket +namespace Socket { +class Socket_API IConnectionServer : public IConnection { - class Socket_API IConnectionServer : public IConnection - { - public: +public: - /* - * \brief Places a socket in a listening state on the specified port. - * \param port [in]: port on the one the socket should listen. - * when set to '0', the socket wil start on - * an available port. - */ - virtual bool listen(const size_t port) = 0; + /* + * \brief Places a socket in a listening state on the specified port. + * \param port [in]: port on the one the socket should listen. + * when set to '0', the socket wil start on + * an available port. + */ + virtual bool listen(const size_t port) = 0; - virtual IConnection* accept() = 0; + virtual IConnection* accept() = 0; - /* - * \brief Returns the port on the one the server is listening. - * This is useful if you set the port to '0'. - * \param port [out]: port on the one the server is listening - */ - virtual bool getSocketPort(size_t& port) = 0; - }; + /* + * \brief Returns the port on the one the server is listening. + * This is useful if you set the port to '0'. + * \param port [out]: port on the one the server is listening + */ + virtual bool getSocketPort(size_t& port) = 0; +}; - extern Socket_API IConnectionServer* createConnectionServer(); -} // namespace Socket +extern Socket_API IConnectionServer* createConnectionServer(); +} // namespace Socket diff --git a/modules/socket/include/socket/TConnectionDelegate.h b/modules/socket/include/socket/TConnectionDelegate.h index 4c3b06d43556600d8a0b0e0b047916ce2650d463..588494732a75612e3f4ea381efa547f9af388cbd 100644 --- a/modules/socket/include/socket/TConnectionDelegate.h +++ b/modules/socket/include/socket/TConnectionDelegate.h @@ -2,48 +2,53 @@ #include "IConnection.h" -namespace Socket +namespace Socket { +struct SConnectionDelegate { - struct SConnectionDelegate - { - void* data; - bool (*fpOpen)(void*); - bool (*fpClose)(void*); - bool (*fpIsReadyToSend)(void*, size_t); - bool (*fpIsReadyToReceive)(void*, size_t); - size_t (*fpSendBuffer)(void*, const void*, size_t); - size_t (*fpReceiveBuffer)(void*, void*, size_t); - bool (*fpSendBufferBlocking)(void*, const void*, size_t); - bool (*fpReceiveBufferBlocking)(void*, void*, size_t); - bool (*fpIsConnected)(void*); - bool (*fpRelease)(void*); - }; - - template <class T> - class Socket_API TConnectionDelegate : public T - { - public: - TConnectionDelegate(const SConnectionDelegate connectionDelegate) : m_connectionDelegate(connectionDelegate) { } + void* data; + bool (*fpOpen)(void*); + bool (*fpClose)(void*); + bool (*fpIsReadyToSend)(void*, size_t); + bool (*fpIsReadyToReceive)(void*, size_t); + size_t (*fpSendBuffer)(void*, const void*, size_t); + size_t (*fpReceiveBuffer)(void*, void*, size_t); + bool (*fpSendBufferBlocking)(void*, const void*, size_t); + bool (*fpReceiveBufferBlocking)(void*, void*, size_t); + bool (*fpIsConnected)(void*); + bool (*fpRelease)(void*); +}; + +template <class T> +class Socket_API TConnectionDelegate : public T +{ +public: + TConnectionDelegate(const SConnectionDelegate connectionDelegate) : m_connectionDelegate(connectionDelegate) { } - virtual bool close() { return m_connectionDelegate.fpClose(m_connectionDelegate.data); } + virtual bool close() { return m_connectionDelegate.fpClose(m_connectionDelegate.data); } - virtual bool isReadyToSend(const size_t timeOut) const { return m_connectionDelegate.fpIsReadyToSend(m_connectionDelegate.data, timeOut); } - virtual bool isReadyToReceive(const size_t timeOut) const { return m_connectionDelegate.fpIsReadyToReceive(m_connectionDelegate.data, timeOut); } + virtual bool isReadyToSend(const size_t timeOut) const { return m_connectionDelegate.fpIsReadyToSend(m_connectionDelegate.data, timeOut); } + virtual bool isReadyToReceive(const size_t timeOut) const { return m_connectionDelegate.fpIsReadyToReceive(m_connectionDelegate.data, timeOut); } - virtual size_t sendBuffer(const void* buffer, const size_t size) { return m_connectionDelegate.fpSendBuffer(m_connectionDelegate.data, buffer, size); } - virtual size_t receiveBuffer(void* buffer, const size_t size) { return m_connectionDelegate.fpReceiveBuffer(m_connectionDelegate.data, buffer, size); } + virtual size_t sendBuffer(const void* buffer, const size_t size) { return m_connectionDelegate.fpSendBuffer(m_connectionDelegate.data, buffer, size); } + virtual size_t receiveBuffer(void* buffer, const size_t size) { return m_connectionDelegate.fpReceiveBuffer(m_connectionDelegate.data, buffer, size); } - virtual bool sendBufferBlocking(const void* buffer, const size_t size) { return m_connectionDelegate.fpSendBufferBlocking(m_connectionDelegate.data, buffer, size); } - virtual bool receiveBufferBlocking(void* buffer, const size_t bufferSize) { return m_connectionDelegate.fpReceiveBufferBlocking(m_connectionDelegate.data, buffer, bufferSize); } + virtual bool sendBufferBlocking(const void* buffer, const size_t size) + { + return m_connectionDelegate.fpSendBufferBlocking(m_connectionDelegate.data, buffer, size); + } + virtual bool receiveBufferBlocking(void* buffer, const size_t bufferSize) + { + return m_connectionDelegate.fpReceiveBufferBlocking(m_connectionDelegate.data, buffer, bufferSize); + } - virtual bool isConnected() const { return m_connectionDelegate.fpIsConnected(m_connectionDelegate.data); } + virtual bool isConnected() const { return m_connectionDelegate.fpIsConnected(m_connectionDelegate.data); } - virtual void release() { m_connectionDelegate.fpRelease(m_connectionDelegate.data); } + virtual void release() { m_connectionDelegate.fpRelease(m_connectionDelegate.data); } - virtual ~TConnectionDelegate() { } - protected: - virtual bool open() { return m_connectionDelegate.fpOpen(m_connectionDelegate.data); } + virtual ~TConnectionDelegate() { } +protected: + virtual bool open() { return m_connectionDelegate.fpOpen(m_connectionDelegate.data); } - SConnectionDelegate m_connectionDelegate; - }; -} // namespace Socket + SConnectionDelegate m_connectionDelegate; +}; +} // namespace Socket diff --git a/modules/socket/include/socket/defines.h b/modules/socket/include/socket/defines.h index 5ccc130604a7d208491149106ac0bf2345582130..3c89902f95b73b611b89d9a2d841f2b522d8092a 100644 --- a/modules/socket/include/socket/defines.h +++ b/modules/socket/include/socket/defines.h @@ -6,23 +6,23 @@ // - http://people.redhat.com/drepper/dsohowto.pdf // - http://www.nedprod.com/programs/gccvisibility.html #if defined Socket_Shared -#if defined TARGET_OS_Windows -#define Socket_API_Export __declspec(dllexport) -#define Socket_API_Import __declspec(dllimport) -#elif defined TARGET_OS_Linux || defined TARGET_OS_MacOS - #define Socket_API_Export __attribute__((visibility("default"))) - #define Socket_API_Import __attribute__((visibility("default"))) +# if defined TARGET_OS_Windows +# define Socket_API_Export __declspec(dllexport) +# define Socket_API_Import __declspec(dllimport) +# elif defined TARGET_OS_Linux || defined TARGET_OS_MacOS +# define Socket_API_Export __attribute__((visibility("default"))) +# define Socket_API_Import __attribute__((visibility("default"))) +# else +# define Socket_API_Export +# define Socket_API_Import +# endif #else - #define Socket_API_Export - #define Socket_API_Import -#endif -#else -#define Socket_API_Export -#define Socket_API_Import +# define Socket_API_Export +# define Socket_API_Import #endif #if defined Socket_Exports -#define Socket_API Socket_API_Export +# define Socket_API Socket_API_Export #else - #define Socket_API Socket_API_Import +# define Socket_API Socket_API_Import #endif diff --git a/modules/socket/src/IConnection.inl b/modules/socket/src/IConnection.inl index c4e6c8121064237dc47ef68e65b5d5a9857a69cf..7e50b7aae2e4893aba45501d47e17d4d3425a66d 100644 --- a/modules/socket/src/IConnection.inl +++ b/modules/socket/src/IConnection.inl @@ -31,165 +31,164 @@ #endif -namespace Socket +namespace Socket { +static bool FD_ISSET_PROXY(const int fd, fd_set* set) { return FD_ISSET(fd, set) ? true : false; } + +template <class T> +class TConnection : public T { - static bool FD_ISSET_PROXY(const int fd, fd_set* set) { return FD_ISSET(fd, set) ? true : false; } +public: - template <class T> - class TConnection : public T + TConnection() : m_socket(-1) { - public: - - TConnection() : m_socket(-1) - { #if defined TARGET_OS_Linux || defined TARGET_OS_MacOS #elif defined TARGET_OS_Windows - const int versionHigh = 2; - const int versionLow = 0; - const WORD winsockVersion = MAKEWORD(versionHigh, versionLow); - WSADATA wsaData; - WSAStartup(winsockVersion, &wsaData); + const int versionHigh = 2; + const int versionLow = 0; + const WORD winsockVersion = MAKEWORD(versionHigh, versionLow); + WSADATA wsaData; + WSAStartup(winsockVersion, &wsaData); #else #endif - } + } - explicit TConnection(const int socket) : m_socket(socket) - { + explicit TConnection(const int socket) : m_socket(socket) + { #if defined TARGET_OS_Windows - const int versionHigh = 2; - const int versionLow = 0; - const WORD winsockVersion = MAKEWORD(versionHigh, versionLow); - WSADATA wsaData; - WSAStartup(winsockVersion, &wsaData); + const int versionHigh = 2; + const int versionLow = 0; + const WORD winsockVersion = MAKEWORD(versionHigh, versionLow); + WSADATA wsaData; + WSAStartup(winsockVersion, &wsaData); #elif defined TARGET_OS_Linux || defined TARGET_OS_MacOS #else #endif - } + } - virtual ~TConnection() - { + virtual ~TConnection() + { #if defined TARGET_OS_Linux || defined TARGET_OS_MacOS #elif defined TARGET_OS_Windows - WSACleanup(); + WSACleanup(); #else #endif - } + } - protected: +protected: - virtual bool open() - { - if (isConnected()) { return false; } + virtual bool open() + { + if (isConnected()) { return false; } - m_socket = int(socket(AF_INET, SOCK_STREAM, 0)); - if (m_socket == size_t(-1)) { return false; } + m_socket = int(socket(AF_INET, SOCK_STREAM, 0)); + if (m_socket == size_t(-1)) { return false; } - return true; - } + return true; + } - public: +public: - virtual bool close() - { - if (!isConnected()) { return false; } + virtual bool close() + { + if (!isConnected()) { return false; } #if defined TARGET_OS_Linux || defined TARGET_OS_MacOS ::shutdown(m_socket, SHUT_RDWR); ::close(m_socket); #elif defined TARGET_OS_Windows - shutdown(m_socket, SD_BOTH); - closesocket(m_socket); + shutdown(m_socket, SD_BOTH); + closesocket(m_socket); #else #endif - m_socket = -1; - return true; - } + m_socket = -1; + return true; + } - virtual bool isReadyToSend(const size_t timeOut = 0) const - { - if (!isConnected()) { return false; } + virtual bool isReadyToSend(const size_t timeOut = 0) const + { + if (!isConnected()) { return false; } - struct timeval timeVal; - timeVal.tv_sec = int(timeOut / 1000); - timeVal.tv_usec = int((timeOut - timeVal.tv_sec * 1000) * 1000); + struct timeval timeVal; + timeVal.tv_sec = int(timeOut / 1000); + timeVal.tv_usec = int((timeOut - timeVal.tv_sec * 1000) * 1000); - fd_set writeFileDesc; - FD_ZERO(&writeFileDesc); - FD_SET(m_socket, &writeFileDesc); + fd_set writeFileDesc; + FD_ZERO(&writeFileDesc); + FD_SET(m_socket, &writeFileDesc); - if (select(int(m_socket + 1), nullptr, &writeFileDesc, nullptr, &timeVal) < 0) { return false; } - if (!FD_ISSET_PROXY(int(m_socket), &writeFileDesc)) { return false; } - return true; - } + if (select(int(m_socket + 1), nullptr, &writeFileDesc, nullptr, &timeVal) < 0) { return false; } + if (!FD_ISSET_PROXY(int(m_socket), &writeFileDesc)) { return false; } + return true; + } - virtual bool isReadyToReceive(const size_t timeOut = 0) const - { - if (!isConnected()) { return false; } + virtual bool isReadyToReceive(const size_t timeOut = 0) const + { + if (!isConnected()) { return false; } - struct timeval timeVal; - timeVal.tv_sec = int(timeOut / 1000); - timeVal.tv_usec = int((timeOut - timeVal.tv_sec * 1000) * 1000); + struct timeval timeVal; + timeVal.tv_sec = int(timeOut / 1000); + timeVal.tv_usec = int((timeOut - timeVal.tv_sec * 1000) * 1000); - fd_set readFileDesc; - FD_ZERO(&readFileDesc); - FD_SET(m_socket, &readFileDesc); + fd_set readFileDesc; + FD_ZERO(&readFileDesc); + FD_SET(m_socket, &readFileDesc); - if (select(int(m_socket + 1), &readFileDesc, nullptr, nullptr, &timeVal) < 0) { return false; } - if (!(FD_ISSET_PROXY(int(m_socket), &readFileDesc))) { return false; } - return true; - } + if (select(int(m_socket + 1), &readFileDesc, nullptr, nullptr, &timeVal) < 0) { return false; } + if (!(FD_ISSET_PROXY(int(m_socket), &readFileDesc))) { return false; } + return true; + } - virtual size_t sendBuffer(const void* buffer, const size_t size) - { - if (!isConnected()) { return 0; } - const int res = send(m_socket, static_cast<const char*>(buffer), int(size), Socket_SendFlags); - if (size != 0 && res <= 0) { close(); } - return res <= 0 ? 0 : size_t(res); - } + virtual size_t sendBuffer(const void* buffer, const size_t size) + { + if (!isConnected()) { return 0; } + const int res = send(m_socket, static_cast<const char*>(buffer), int(size), Socket_SendFlags); + if (size != 0 && res <= 0) { close(); } + return res <= 0 ? 0 : size_t(res); + } - virtual size_t receiveBuffer(void* buffer, const size_t size) - { - if (!isConnected() || !size) { return 0; } - const int res = recv(m_socket, static_cast<char *>(buffer), int(size), Socket_ReceiveFlags); - if (size != 0 && res <= 0) { close(); } - return res <= 0 ? 0 : size_t(res); - } + virtual size_t receiveBuffer(void* buffer, const size_t size) + { + if (!isConnected() || !size) { return 0; } + const int res = recv(m_socket, static_cast<char*>(buffer), int(size), Socket_ReceiveFlags); + if (size != 0 && res <= 0) { close(); } + return res <= 0 ? 0 : size_t(res); + } - virtual bool sendBufferBlocking(const void* buffer, const size_t size) - { - size_t leftBytes = size; - const char* tmpBuffer = static_cast<const char*>(buffer); - do - { - leftBytes -= sendBuffer(tmpBuffer + size - leftBytes, leftBytes); - if (!isConnected()) { return false; } - } while (leftBytes != 0); - return true; - } - - virtual bool receiveBufferBlocking(void* buffer, const size_t size) + virtual bool sendBufferBlocking(const void* buffer, const size_t size) + { + size_t leftBytes = size; + const char* tmpBuffer = static_cast<const char*>(buffer); + do { - size_t leftBytes = size; - char* tmpBuffer = static_cast<char*>(buffer); - do - { - leftBytes -= receiveBuffer(tmpBuffer + size - leftBytes, leftBytes); - if (!isConnected()) { return false; } - } while (leftBytes != 0); - return true; - } - - virtual bool isConnected() const { return m_socket != size_t(-1); } - - virtual void release() + leftBytes -= sendBuffer(tmpBuffer + size - leftBytes, leftBytes); + if (!isConnected()) { return false; } + } while (leftBytes != 0); + return true; + } + + virtual bool receiveBufferBlocking(void* buffer, const size_t size) + { + size_t leftBytes = size; + char* tmpBuffer = static_cast<char*>(buffer); + do { - if (isConnected()) { close(); } - delete this; - } + leftBytes -= receiveBuffer(tmpBuffer + size - leftBytes, leftBytes); + if (!isConnected()) { return false; } + } while (leftBytes != 0); + return true; + } + + virtual bool isConnected() const { return m_socket != size_t(-1); } + + virtual void release() + { + if (isConnected()) { close(); } + delete this; + } - protected: +protected: - size_t m_socket; - }; -} // namespace Socket + size_t m_socket; +}; +} // namespace Socket diff --git a/modules/socket/src/IConnectionBluetooth.cpp b/modules/socket/src/IConnectionBluetooth.cpp index 85f47e95916b2c1a3d4839f82d66cca6015b9f6a..9bbdfdbe24d5e2e8e48a0852097fbc8a21160081 100644 --- a/modules/socket/src/IConnectionBluetooth.cpp +++ b/modules/socket/src/IConnectionBluetooth.cpp @@ -25,417 +25,418 @@ #include <assert.h> #include <vector> +#include <string> -namespace Socket +namespace Socket { +class CConnectionBluetooth final : public IConnectionBluetooth { - class CConnectionBluetooth final : public IConnectionBluetooth - { - public: +public: #if defined TARGET_OS_Windows - CConnectionBluetooth() : m_Socket(INVALID_SOCKET) { } + CConnectionBluetooth() : m_Socket(INVALID_SOCKET) { } #elif defined TARGET_OS_Linux || defined TARGET_OS_MacOS CConnectionBluetooth() : m_LastError() { } #endif #if defined TARGET_OS_Windows - bool initialize() - { - WSADATA wsaData; + bool initialize() + { + WSADATA wsaData; - // Ask for Winsock version. - if (_WINSOCK2API_::WSAStartup(MAKEWORD(WIN_SOCKET_MAJOR_VERSION, WIN_SOCKET_MINOR_VERSION), &wsaData) != 0) - { - m_LastError = "Failed to start Winsock " + std::to_string(WIN_SOCKET_MAJOR_VERSION) + "." + std::to_string(WIN_SOCKET_MINOR_VERSION) + ": " + this->getLastErrorFormated(); - return false; - } + // Ask for Winsock version. + if (_WINSOCK2API_::WSAStartup(MAKEWORD(WIN_SOCKET_MAJOR_VERSION, WIN_SOCKET_MINOR_VERSION), &wsaData) != 0) + { + m_LastError = "Failed to start Winsock " + std::to_string(WIN_SOCKET_MAJOR_VERSION) + "." + std::to_string(WIN_SOCKET_MINOR_VERSION) + ": " + this-> + getLastErrorFormated(); + return false; + } - // Confirm that the WinSock DLL supports version requested. - // Note that if the DLL supports versions greater than the version requested, in addition to the version requested, it will still return the version requested in wVersion. - if (LOBYTE(wsaData.wVersion) != WIN_SOCKET_MAJOR_VERSION || HIBYTE(wsaData.wVersion) != WIN_SOCKET_MINOR_VERSION) - { - m_LastError = "Could not find a usable version of Winsock.dll."; - _WINSOCK2API_::WSACleanup(); - return false; - } - return true; + // Confirm that the WinSock DLL supports version requested. + // Note that if the DLL supports versions greater than the version requested, in addition to the version requested, it will still return the version requested in wVersion. + if (LOBYTE(wsaData.wVersion) != WIN_SOCKET_MAJOR_VERSION || HIBYTE(wsaData.wVersion) != WIN_SOCKET_MINOR_VERSION) + { + m_LastError = "Could not find a usable version of Winsock.dll."; + _WINSOCK2API_::WSACleanup(); + return false; } + return true; + } #elif defined TARGET_OS_Linux || defined TARGET_OS_MacOS bool initialize() { return false; } #endif - bool open() override { return false; } + bool open() override { return false; } - bool close() override + bool close() override + { + if (!this->isConnected()) { - if (!this->isConnected()) - { - m_LastError = "Bluetooth device is not connected."; - return false; - } + m_LastError = "Bluetooth device is not connected."; + return false; + } #if defined TARGET_OS_Windows - bool isSuccess = true; - if (m_Socket != INVALID_SOCKET) + bool isSuccess = true; + if (m_Socket != INVALID_SOCKET) + { + // shutdown the connection since no more data will be sent or received + if (_WINSOCK2API_::shutdown(m_Socket, SD_BOTH) == SOCKET_ERROR) { - // shutdown the connection since no more data will be sent or received - if (_WINSOCK2API_::shutdown(m_Socket, SD_BOTH) == SOCKET_ERROR) - { - m_LastError = "Failed to shutdown the bluetooth socket:" + this->getLastErrorFormated(); - isSuccess = false; - } - - if (_WINSOCK2API_::closesocket(m_Socket) == SOCKET_ERROR) - { - m_LastError = "Failed to close the bluetooth socket:" + this->getLastErrorFormated(); - isSuccess = false; - } + m_LastError = "Failed to shutdown the bluetooth socket:" + this->getLastErrorFormated(); + isSuccess = false; + } - if (_WINSOCK2API_::WSACleanup() == SOCKET_ERROR) - { - m_LastError = "Failed to cleanup the bluetooth socket:" + this->getLastErrorFormated(); - isSuccess = false; - } + if (_WINSOCK2API_::closesocket(m_Socket) == SOCKET_ERROR) + { + m_LastError = "Failed to close the bluetooth socket:" + this->getLastErrorFormated(); + isSuccess = false; + } - m_Socket = INVALID_SOCKET; + if (_WINSOCK2API_::WSACleanup() == SOCKET_ERROR) + { + m_LastError = "Failed to cleanup the bluetooth socket:" + this->getLastErrorFormated(); + isSuccess = false; } - return isSuccess; + m_Socket = INVALID_SOCKET; + } + + return isSuccess; #elif defined TARGET_OS_Linux || defined TARGET_OS_MacOS return false; #endif - } + } - bool isReadyToSend(const size_t /*timeOut*/) const override { return this->isConnected(); } + bool isReadyToSend(const size_t /*timeOut*/) const override { return this->isConnected(); } - bool isReadyToReceive(const size_t /*timeOut*/) const override - { - if (!this->isConnected()) { return false; } + bool isReadyToReceive(const size_t /*timeOut*/) const override + { + if (!this->isConnected()) { return false; } #if defined TARGET_OS_Windows - unsigned long nPendingBytes = 0; + unsigned long nPendingBytes = 0; - if (_WINSOCK2API_::ioctlsocket(m_Socket, FIONREAD, &nPendingBytes) == SOCKET_ERROR) - { - //m_LastError = "Failed to get the pending bytes count: " + this->getLastErrorFormated(); - return false; - } + if (_WINSOCK2API_::ioctlsocket(m_Socket, FIONREAD, &nPendingBytes) == SOCKET_ERROR) + { + //m_LastError = "Failed to get the pending bytes count: " + this->getLastErrorFormated(); + return false; + } - return nPendingBytes != 0; + return nPendingBytes != 0; #elif defined TARGET_OS_Linux || defined TARGET_OS_MacOS return false; #endif - } + } - size_t getPendingByteCount() override + size_t getPendingByteCount() override + { + if (!this->isConnected()) { - if (!this->isConnected()) - { - m_LastError = "Bluetooth device not connected."; - return 0; - } + m_LastError = "Bluetooth device not connected."; + return 0; + } #if defined TARGET_OS_Windows - unsigned long nPendingBytes = 0; + unsigned long nPendingBytes = 0; - if (_WINSOCK2API_::ioctlsocket(m_Socket, FIONREAD, &nPendingBytes) == SOCKET_ERROR) - { - m_LastError = "Failed to get the pending bytes count: " + this->getLastErrorFormated(); - return 0; - } + if (_WINSOCK2API_::ioctlsocket(m_Socket, FIONREAD, &nPendingBytes) == SOCKET_ERROR) + { + m_LastError = "Failed to get the pending bytes count: " + this->getLastErrorFormated(); + return 0; + } - return nPendingBytes; + return nPendingBytes; #elif defined TARGET_OS_Linux || defined TARGET_OS_MacOS return 0; #endif - } + } - size_t sendBuffer(const void* buffer, const size_t size) override + size_t sendBuffer(const void* buffer, const size_t size) override + { + if (!this->isConnected()) { - if (!this->isConnected()) - { - m_LastError = "Bluetooth device is not connected."; - return 0; - } + m_LastError = "Bluetooth device is not connected."; + return 0; + } #if defined TARGET_OS_Windows - const int nBytesSent = _WINSOCK2API_::send(m_Socket, reinterpret_cast<const char*>(buffer), int(size), 0); + const int nBytesSent = _WINSOCK2API_::send(m_Socket, reinterpret_cast<const char*>(buffer), int(size), 0); - if (nBytesSent == SOCKET_ERROR) - { - m_LastError = "Failed to write on the bluetooth port: " + getLastErrorFormated(); - this->close(); - return 0; - } + if (nBytesSent == SOCKET_ERROR) + { + m_LastError = "Failed to write on the bluetooth port: " + getLastErrorFormated(); + this->close(); + return 0; + } - return size_t(nBytesSent); + return size_t(nBytesSent); #elif defined TARGET_OS_Linux || defined TARGET_OS_MacOS return 0; #endif - } + } - size_t receiveBuffer(void* buffer, const size_t size) override + size_t receiveBuffer(void* buffer, const size_t size) override + { + if (!this->isConnected()) { - if (!this->isConnected()) - { - m_LastError = "Bluetooth device is not connected."; - return 0; - } + m_LastError = "Bluetooth device is not connected."; + return 0; + } #if defined TARGET_OS_Windows - const int nBytesReceived = _WINSOCK2API_::recv(m_Socket, static_cast<char *>(buffer), int(size), 0); + const int nBytesReceived = _WINSOCK2API_::recv(m_Socket, static_cast<char*>(buffer), int(size), 0); - if (nBytesReceived == SOCKET_ERROR) - { - m_LastError = "Failed to receive data from bluetooth: " + getLastErrorFormated(); + if (nBytesReceived == SOCKET_ERROR) + { + m_LastError = "Failed to receive data from bluetooth: " + getLastErrorFormated(); - this->close(); - return 0; - } + this->close(); + return 0; + } - return size_t(nBytesReceived); + return size_t(nBytesReceived); #elif defined TARGET_OS_Linux || defined TARGET_OS_MacOS return 0; #endif - } + } - bool sendBufferBlocking(const void* buffer, const size_t size) override + bool sendBufferBlocking(const void* buffer, const size_t size) override + { + if (!this->isConnected()) { - if (!this->isConnected()) - { - m_LastError = "Bluetooth device is not connected."; - return false; - } - - const char* p = reinterpret_cast<const char*>(buffer); - size_t bytesLeft = size; + m_LastError = "Bluetooth device is not connected."; + return false; + } - while (bytesLeft != 0 && this->isConnected()) - { - bytesLeft -= this->sendBuffer(p + size - bytesLeft, bytesLeft); + const char* p = reinterpret_cast<const char*>(buffer); + size_t bytesLeft = size; - if (this->isErrorRaised()) { return false; } - } + while (bytesLeft != 0 && this->isConnected()) + { + bytesLeft -= this->sendBuffer(p + size - bytesLeft, bytesLeft); - return bytesLeft == 0; + if (this->isErrorRaised()) { return false; } } - bool receiveBufferBlocking(void* buffer, const size_t size) override - { - if (!this->isConnected()) - { - m_LastError = "Bluetooth device is not connected."; - return false; - } + return bytesLeft == 0; + } - char* p = reinterpret_cast<char*>(buffer); - size_t bytesLeft = size; + bool receiveBufferBlocking(void* buffer, const size_t size) override + { + if (!this->isConnected()) + { + m_LastError = "Bluetooth device is not connected."; + return false; + } - while (bytesLeft != 0 && this->isConnected()) - { - bytesLeft -= this->receiveBuffer(p + size - bytesLeft, bytesLeft); + char* p = reinterpret_cast<char*>(buffer); + size_t bytesLeft = size; - if (this->isErrorRaised()) { return false; } - } + while (bytesLeft != 0 && this->isConnected()) + { + bytesLeft -= this->receiveBuffer(p + size - bytesLeft, bytesLeft); - return bytesLeft == 0; + if (this->isErrorRaised()) { return false; } } - bool isConnected() const override - { + return bytesLeft == 0; + } + + bool isConnected() const override + { #if defined TARGET_OS_Windows - return m_Socket != INVALID_SOCKET; + return m_Socket != INVALID_SOCKET; #elif defined TARGET_OS_Linux || defined TARGET_OS_MacOS return false; #endif - } + } - void release() override { delete this; } + void release() override { delete this; } - bool connect(const uint64_t u64BluetoothAddress) override - { - m_LastError.clear(); + bool connect(const uint64_t u64BluetoothAddress) override + { + m_LastError.clear(); - if (this->isConnected()) - { - m_LastError = "Bluetooth device is already connected"; - return false; - } + if (this->isConnected()) + { + m_LastError = "Bluetooth device is already connected"; + return false; + } #if defined TARGET_OS_Windows - if (!this->initialize()) { return false; } + if (!this->initialize()) { return false; } - m_Socket = _WINSOCK2API_::socket(AF_BTH, SOCK_STREAM, BTHPROTO_RFCOMM); + m_Socket = _WINSOCK2API_::socket(AF_BTH, SOCK_STREAM, BTHPROTO_RFCOMM); - if (m_Socket == INVALID_SOCKET) - { - m_LastError = "Failed to create bluetooth socket: " + getLastErrorFormated(); - _WINSOCK2API_::WSACleanup(); - return false; - } + if (m_Socket == INVALID_SOCKET) + { + m_LastError = "Failed to create bluetooth socket: " + getLastErrorFormated(); + _WINSOCK2API_::WSACleanup(); + return false; + } - SOCKADDR_BTH sockAddressBlutoothServer; - sockAddressBlutoothServer.btAddr = u64BluetoothAddress; - sockAddressBlutoothServer.addressFamily = AF_BTH; - sockAddressBlutoothServer.serviceClassId = RFCOMM_PROTOCOL_UUID; - sockAddressBlutoothServer.port = BT_PORT_ANY; + SOCKADDR_BTH sockAddressBlutoothServer; + sockAddressBlutoothServer.btAddr = u64BluetoothAddress; + sockAddressBlutoothServer.addressFamily = AF_BTH; + sockAddressBlutoothServer.serviceClassId = RFCOMM_PROTOCOL_UUID; + sockAddressBlutoothServer.port = BT_PORT_ANY; - if (_WINSOCK2API_::connect(m_Socket, reinterpret_cast<SOCKADDR*>(&sockAddressBlutoothServer), sizeof(SOCKADDR_BTH)) == SOCKET_ERROR) - { - m_LastError = "Failed to connect the socket to the bluetooth address [" + std::to_string(sockAddressBlutoothServer.btAddr) + "]: " + - getLastErrorFormated(); + if (_WINSOCK2API_::connect(m_Socket, reinterpret_cast<SOCKADDR*>(&sockAddressBlutoothServer), sizeof(SOCKADDR_BTH)) == SOCKET_ERROR) + { + m_LastError = "Failed to connect the socket to the bluetooth address [" + std::to_string(sockAddressBlutoothServer.btAddr) + "]: " + + getLastErrorFormated(); - _WINSOCK2API_::closesocket(m_Socket); // Returned code not checked. - _WINSOCK2API_::WSACleanup(); // Returned code not checked. + _WINSOCK2API_::closesocket(m_Socket); // Returned code not checked. + _WINSOCK2API_::WSACleanup(); // Returned code not checked. - m_Socket = INVALID_SOCKET; - return false; - } + m_Socket = INVALID_SOCKET; + return false; + } - return true; + return true; #elif defined TARGET_OS_Linux || defined TARGET_OS_MacOS return false; #endif - } + } - bool isErrorRaised() const { return !m_LastError.empty(); } + bool isErrorRaised() const { return !m_LastError.empty(); } - const char* getLastError() const override { return m_LastError.c_str(); } + const char* getLastError() const override { return m_LastError.c_str(); } - static std::string getLastErrorFormated() - { + static std::string getLastErrorFormated() + { #if defined TARGET_OS_Windows - LPTSTR text; - const DWORD errCode = GetLastError(); + LPTSTR text; + const DWORD errCode = GetLastError(); - const size_t size = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | // use system message tables to retrieve error text - FORMAT_MESSAGE_ALLOCATE_BUFFER | // allocate buffer on local heap for error text - FORMAT_MESSAGE_IGNORE_INSERTS, // Important! will fail otherwise, since we're not (and CANNOT) pass insertion parameters - nullptr, // unused with FORMAT_MESSAGE_FROM_SYSTEM - errCode, MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), - LPTSTR(&text), // output - 0, // minimum size for output buffer - nullptr); + const size_t size = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | // use system message tables to retrieve error text + FORMAT_MESSAGE_ALLOCATE_BUFFER | // allocate buffer on local heap for error text + FORMAT_MESSAGE_IGNORE_INSERTS, // Important! will fail otherwise, since we're not (and CANNOT) pass insertion parameters + nullptr, // unused with FORMAT_MESSAGE_FROM_SYSTEM + errCode, MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), + LPTSTR(&text), // output + 0, // minimum size for output buffer + nullptr); - // Converts std::wstring to std::string and returns it. - const std::wstring message(text, size); - LocalFree(text); - std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> converter; - return converter.to_bytes(message); + // Converts std::wstring to std::string and returns it. + const std::wstring message(text, size); + LocalFree(text); + std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> converter; + return converter.to_bytes(message); #elif defined TARGET_OS_Linux || defined TARGET_OS_MacOS return ""; #endif - } + } - void clearError() override { m_LastError.clear(); } + void clearError() override { m_LastError.clear(); } - bool listPairedBluetoothDevices(size_t* nPairedBluetoothDevices, char** names, uint64_t** addresses) override - { - std::vector<std::string> devicesNames; - std::vector<uint64_t> devicesAddresses; + bool listPairedBluetoothDevices(size_t* nPairedBluetoothDevices, char** names, uint64_t** addresses) override + { + std::vector<std::string> devicesNames; + std::vector<uint64_t> devicesAddresses; #if defined TARGET_OS_Windows - HANDLE handle; - WSAQUERYSET wsaQuerySet; + HANDLE handle; + WSAQUERYSET wsaQuerySet; - memset((void *)&wsaQuerySet, 0, sizeof(wsaQuerySet)); - wsaQuerySet.dwSize = sizeof(wsaQuerySet); - wsaQuerySet.dwNameSpace = NS_BTH; - wsaQuerySet.lpcsaBuffer = nullptr; + memset((void*)&wsaQuerySet, 0, sizeof(wsaQuerySet)); + wsaQuerySet.dwSize = sizeof(wsaQuerySet); + wsaQuerySet.dwNameSpace = NS_BTH; + wsaQuerySet.lpcsaBuffer = nullptr; - if (_WINSOCK2API_::WSALookupServiceBegin(&wsaQuerySet, LUP_CONTAINERS | LUP_RETURN_NAME | LUP_RETURN_ADDR, &handle) == SOCKET_ERROR) - { - m_LastError = "Failed to start the Bluetooth lookup service: " + getLastErrorFormated(); - return false; - } + if (_WINSOCK2API_::WSALookupServiceBegin(&wsaQuerySet, LUP_CONTAINERS | LUP_RETURN_NAME | LUP_RETURN_ADDR, &handle) == SOCKET_ERROR) + { + m_LastError = "Failed to start the Bluetooth lookup service: " + getLastErrorFormated(); + return false; + } - char buffer[5000]; - const LPWSAQUERYSET wsaQuerySetW = LPWSAQUERYSET(buffer); - DWORD size = sizeof(buffer); + char buffer[5000]; + const LPWSAQUERYSET wsaQuerySetW = LPWSAQUERYSET(buffer); + DWORD size = sizeof(buffer); - memset((void *)wsaQuerySetW, 0, sizeof(WSAQUERYSET)); - wsaQuerySetW->dwSize = sizeof(WSAQUERYSET); - wsaQuerySetW->dwNameSpace = NS_BTH; - wsaQuerySetW->lpBlob = nullptr; + memset((void*)wsaQuerySetW, 0, sizeof(WSAQUERYSET)); + wsaQuerySetW->dwSize = sizeof(WSAQUERYSET); + wsaQuerySetW->dwNameSpace = NS_BTH; + wsaQuerySetW->lpBlob = nullptr; - bool lookup = true; + bool lookup = true; - while (lookup) - { - // Check next bluetooth device - const int res = _WINSOCK2API_::WSALookupServiceNext(handle, LUP_RETURN_NAME | LUP_RETURN_ADDR, &size, wsaQuerySetW); + while (lookup) + { + // Check next bluetooth device + const int res = _WINSOCK2API_::WSALookupServiceNext(handle, LUP_RETURN_NAME | LUP_RETURN_ADDR, &size, wsaQuerySetW); - if (res == SOCKET_ERROR) + if (res == SOCKET_ERROR) + { + // If it is a "real" error, we trace it and return false. + if (_WINSOCK2API_::WSAGetLastError() != WSA_E_NO_MORE) { - // If it is a "real" error, we trace it and return false. - if (_WINSOCK2API_::WSAGetLastError() != WSA_E_NO_MORE) - { - m_LastError = "Lookup service next operation failed: " + getLastErrorFormated(); - return false; - } - - // Else, it is because there is no more Bluetooth devices available. - lookup = false; - break; + m_LastError = "Lookup service next operation failed: " + getLastErrorFormated(); + return false; } - // Get bluetooth MAC address and name - devicesAddresses.push_back(reinterpret_cast<SOCKADDR_BTH *>(wsaQuerySetW->lpcsaBuffer->RemoteAddr.lpSockaddr)->btAddr); - std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> converterX; - devicesNames.push_back(converterX.to_bytes(wsaQuerySetW->lpszServiceInstanceName)); + // Else, it is because there is no more Bluetooth devices available. + lookup = false; + break; } + // Get bluetooth MAC address and name + devicesAddresses.push_back(reinterpret_cast<SOCKADDR_BTH*>(wsaQuerySetW->lpcsaBuffer->RemoteAddr.lpSockaddr)->btAddr); - if (_WINSOCK2API_::WSALookupServiceEnd(handle) == SOCKET_ERROR) - { - m_LastError = "Failed to stop the Bluetooth lookup service: " + getLastErrorFormated(); - return false; - } + std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> converterX; + devicesNames.push_back(converterX.to_bytes(wsaQuerySetW->lpszServiceInstanceName)); + } - *nPairedBluetoothDevices = devicesAddresses.size(); - names = new char*[*nPairedBluetoothDevices]; + if (_WINSOCK2API_::WSALookupServiceEnd(handle) == SOCKET_ERROR) + { + m_LastError = "Failed to stop the Bluetooth lookup service: " + getLastErrorFormated(); + return false; + } - for (size_t i = 0; i < *nPairedBluetoothDevices; ++i) - { - names[i] = new char[devicesNames[i].size() + 1]; - std::strcpy(names[i], devicesNames[i].c_str()); - } + *nPairedBluetoothDevices = devicesAddresses.size(); + names = new char*[*nPairedBluetoothDevices]; - addresses = new uint64_t*[*nPairedBluetoothDevices]; + for (size_t i = 0; i < *nPairedBluetoothDevices; ++i) + { + names[i] = new char[devicesNames[i].size() + 1]; + std::strcpy(names[i], devicesNames[i].c_str()); + } - return true; + addresses = new uint64_t*[*nPairedBluetoothDevices]; + + return true; #elif defined TARGET_OS_Linux || defined TARGET_OS_MacOS return false; #endif - } + } - std::string m_LastError; + std::string m_LastError; #if defined TARGET_OS_Windows - SOCKET m_Socket; + SOCKET m_Socket; #elif defined TARGET_OS_Linux || defined TARGET_OS_MacOS #endif - }; +}; - IConnectionBluetooth* createConnectionBluetooth() { return new CConnectionBluetooth(); } -} // namespace Socket +IConnectionBluetooth* createConnectionBluetooth() { return new CConnectionBluetooth(); } +} // namespace Socket diff --git a/modules/socket/src/IConnectionClient.cpp b/modules/socket/src/IConnectionClient.cpp index 3028609a888381fad38c4ee0371e9fb74241e488..cd521400ef19f44ee8043cd5c3cfb56ef92acd94 100644 --- a/modules/socket/src/IConnectionClient.cpp +++ b/modules/socket/src/IConnectionClient.cpp @@ -19,15 +19,14 @@ #else #endif -namespace Socket +namespace Socket { +class CConnectionClient final : public TConnection<IConnectionClient> { - class CConnectionClient final : public TConnection<IConnectionClient> - { - public: +public: - bool connect(const char* sServerName, const size_t serverPort, const size_t timeOut) override - { - if (!open()) { return false; } + bool connect(const char* sServerName, const size_t serverPort, const size_t timeOut) override + { + if (!open()) { return false; } #if defined TARGET_OS_Linux || defined TARGET_OS_MacOS long value; @@ -54,92 +53,92 @@ namespace Socket #elif defined TARGET_OS_Windows - // Sets non blocking - unsigned long mode = 1; - ioctlsocket(m_socket, FIONBIO, &mode); - - struct addrinfo hints; - ZeroMemory(&hints, sizeof(hints)); - hints.ai_family = AF_INET; - PADDRINFOA addr; - if (getaddrinfo(sServerName, nullptr, &hints, &addr) != 0) - { - close(); - return false; - } - const auto sockaddrIPV4 = reinterpret_cast<sockaddr_in*>(addr->ai_addr); + // Sets non blocking + unsigned long mode = 1; + ioctlsocket(m_socket, FIONBIO, &mode); + + struct addrinfo hints; + ZeroMemory(&hints, sizeof(hints)); + hints.ai_family = AF_INET; + PADDRINFOA addr; + if (getaddrinfo(sServerName, nullptr, &hints, &addr) != 0) + { + close(); + return false; + } + const auto sockaddrIPV4 = reinterpret_cast<sockaddr_in*>(addr->ai_addr); #endif - // Connects - struct sockaddr_in serverAddress; - memset(&serverAddress, 0, sizeof(serverAddress)); - serverAddress.sin_family = AF_INET; - serverAddress.sin_port = htons(static_cast<unsigned short>(serverPort)); + // Connects + struct sockaddr_in serverAddress; + memset(&serverAddress, 0, sizeof(serverAddress)); + serverAddress.sin_family = AF_INET; + serverAddress.sin_port = htons(static_cast<unsigned short>(serverPort)); #if defined TARGET_OS_Linux || defined TARGET_OS_MacOS serverAddress.sin_addr=*((struct in_addr*)serverHostEntry->h_addr); #elif defined TARGET_OS_Windows - serverAddress.sin_addr = sockaddrIPV4->sin_addr; - freeaddrinfo(addr); + serverAddress.sin_addr = sockaddrIPV4->sin_addr; + freeaddrinfo(addr); #endif - errno = 0; - if (::connect(m_socket, reinterpret_cast<struct sockaddr*>(&serverAddress), sizeof(struct sockaddr_in)) < 0) - { - bool inProgress; + errno = 0; + if (::connect(m_socket, reinterpret_cast<struct sockaddr*>(&serverAddress), sizeof(struct sockaddr_in)) < 0) + { + bool inProgress; #if defined TARGET_OS_Linux || defined TARGET_OS_MacOS inProgress = (errno==EINPROGRESS); #elif defined TARGET_OS_Windows - inProgress = (WSAGetLastError() == WSAEINPROGRESS || WSAGetLastError() == WSAEWOULDBLOCK); + inProgress = (WSAGetLastError() == WSAEINPROGRESS || WSAGetLastError() == WSAEWOULDBLOCK); #else inProgress = false; #endif - if (inProgress) + if (inProgress) + { + const int t = (timeOut == 0xffffffff) ? 125 : int(timeOut); + // Performs time out + + struct timeval timeVal; + timeVal.tv_sec = (t / 1000); + timeVal.tv_usec = ((t - timeVal.tv_sec * 1000) * 1000); + + fd_set writeFileDesc; + FD_ZERO(&writeFileDesc); + FD_SET(m_socket, &writeFileDesc); + + if (select(int(m_socket + 1), nullptr, &writeFileDesc, nullptr, &timeVal) < 0) { - const int t = (timeOut == 0xffffffff) ? 125 : int(timeOut); - // Performs time out - - struct timeval timeVal; - timeVal.tv_sec = (t / 1000); - timeVal.tv_usec = ((t - timeVal.tv_sec * 1000) * 1000); - - fd_set writeFileDesc; - FD_ZERO(&writeFileDesc); - FD_SET(m_socket, &writeFileDesc); - - if (select(int(m_socket + 1), nullptr, &writeFileDesc, nullptr, &timeVal) < 0) - { - close(); - return false; - } - if (!FD_ISSET_PROXY(int(m_socket), &writeFileDesc)) - { - close(); - return false; - } - - // Checks error status - int option = 0; + close(); + return false; + } + if (!FD_ISSET_PROXY(int(m_socket), &writeFileDesc)) + { + close(); + return false; + } + + // Checks error status + int option = 0; #if defined TARGET_OS_Linux || defined TARGET_OS_MacOS socklen_t length = sizeof(option); ::getsockopt(m_socket, SOL_SOCKET, SO_ERROR, (void*)(&option), &length); #elif defined TARGET_OS_Windows - int length = sizeof(option); - getsockopt(m_socket, SOL_SOCKET, SO_ERROR, reinterpret_cast<char*>(&option), &length); + int length = sizeof(option); + getsockopt(m_socket, SOL_SOCKET, SO_ERROR, reinterpret_cast<char*>(&option), &length); #endif - if (option != 0) - { - close(); - return false; - } - } - else + if (option != 0) { close(); return false; } } + else + { + close(); + return false; + } + } #if defined TARGET_OS_Linux || defined TARGET_OS_MacOS @@ -158,15 +157,15 @@ namespace Socket #elif defined TARGET_OS_Windows - // Sets back to blocking - mode = 0; - ioctlsocket(m_socket, FIONBIO, &mode); + // Sets back to blocking + mode = 0; + ioctlsocket(m_socket, FIONBIO, &mode); #endif - return true; - } - }; + return true; + } +}; - IConnectionClient* createConnectionClient() { return new CConnectionClient(); } -} // namespace Socket +IConnectionClient* createConnectionClient() { return new CConnectionClient(); } +} // namespace Socket diff --git a/modules/socket/src/IConnectionParallel.cpp b/modules/socket/src/IConnectionParallel.cpp index 38c556cde3d8d1af560f8a89d78b5d9dbca48d3b..3ecce999a4295142ec3af81e141cda26d39dbf37 100644 --- a/modules/socket/src/IConnectionParallel.cpp +++ b/modules/socket/src/IConnectionParallel.cpp @@ -22,65 +22,64 @@ #include <assert.h> -namespace Socket +namespace Socket { +class CConnectionParallel final : public IConnectionParallel { - class CConnectionParallel final : public IConnectionParallel - { - protected: - unsigned short m_portNumber; - std::string m_lastError; - public: +protected: + unsigned short m_portNumber; + std::string m_lastError; +public: - CConnectionParallel() + CConnectionParallel() #if defined TARGET_OS_Linux || defined TARGET_OS_MacOS :m_file(0) #endif - { + { #if defined TARGET_OS_Windows - m_portNumber = 0; - m_port = LoadLibrary(TEXT("TVicPort.dll")); + m_portNumber = 0; + m_port = LoadLibrary(TEXT("TVicPort.dll")); - if (m_port != nullptr) - { - m_isDriverOpened = port_is_driver_opened_t(GetProcAddress(m_port, "IsDriverOpened")); - m_portOpen = port_open_t(GetProcAddress(m_port, "OpenTVicPort")); - m_portClose = port_close_t(GetProcAddress(m_port, "CloseTVicPort")); - m_portWrite = port_write_t(GetProcAddress(m_port, "WritePort")); + if (m_port != nullptr) + { + m_isDriverOpened = port_is_driver_opened_t(GetProcAddress(m_port, "IsDriverOpened")); + m_portOpen = port_open_t(GetProcAddress(m_port, "OpenTVicPort")); + m_portClose = port_close_t(GetProcAddress(m_port, "CloseTVicPort")); + m_portWrite = port_write_t(GetProcAddress(m_port, "WritePort")); - if (!m_isDriverOpened || !m_portOpen || !m_portClose || !m_portWrite) - { - m_lastError = "Cannot load function from TVicPort.dll: " + this->getLastErrorFormated(); - this->release(); - } + if (!m_isDriverOpened || !m_portOpen || !m_portClose || !m_portWrite) + { + m_lastError = "Cannot load function from TVicPort.dll: " + this->getLastErrorFormated(); + this->release(); } - else { m_lastError = "Cannot found or open TVicPort.dll: " + this->getLastErrorFormated(); } -#endif } + else { m_lastError = "Cannot found or open TVicPort.dll: " + this->getLastErrorFormated(); } +#endif + } - bool open() override - { - // Should never be used - return false; - } + bool open() override + { + // Should never be used + return false; + } - bool close() override - { + bool close() override + { #if defined TARGET_OS_Windows - if (m_port != nullptr) + if (m_port != nullptr) + { + if (m_isDriverOpened()) { - if (m_isDriverOpened()) - { - m_portNumber = 0; - m_portClose(); - return true; - } - m_lastError = "Cannot close the TVicPort library because it is not opened."; - return false; + m_portNumber = 0; + m_portClose(); + return true; } + m_lastError = "Cannot close the TVicPort library because it is not opened."; return false; + } + return false; #elif defined TARGET_OS_Linux || defined TARGET_OS_MacOS @@ -94,21 +93,21 @@ namespace Socket m_file = -1; }*/ #endif - } + } - bool isReadyToSend(const size_t /*timeOut*/ = 0) const override { return this->isConnected(); } - bool isReadyToReceive(const size_t /*timeOut*/ = 0) const override { return this->isConnected(); } - size_t getPendingByteCount() const { return (this->isConnected() ? 0 : 1); } + bool isReadyToSend(const size_t /*timeOut*/ = 0) const override { return this->isConnected(); } + bool isReadyToReceive(const size_t /*timeOut*/ = 0) const override { return this->isConnected(); } + size_t getPendingByteCount() const { return (this->isConnected() ? 0 : 1); } - size_t sendBuffer(const void* buffer, const size_t size = 8) override - { - if (!this->isConnected()) { return 0; } + size_t sendBuffer(const void* buffer, const size_t size = 8) override + { + if (!this->isConnected()) { return 0; } #if defined TARGET_OS_Windows - const uint8_t value = *(static_cast<const uint8_t*>(buffer)); + const uint8_t value = *(static_cast<const uint8_t*>(buffer)); - m_portWrite(m_portNumber, value); - return size; + m_portWrite(m_portNumber, value); + return size; #elif defined TARGET_OS_Linux || defined TARGET_OS_MacOS @@ -117,91 +116,91 @@ namespace Socket /*if (ioctl(m_file, PPWDATA, &value) < 0) { return size; }*/ #endif - } + } - size_t receiveBuffer(void* /*buffer*/, const size_t /*size*/ = 8) override - { - if (!this->isConnected()) { return 0; } + size_t receiveBuffer(void* /*buffer*/, const size_t /*size*/ = 8) override + { + if (!this->isConnected()) { return 0; } #if defined TARGET_OS_Windows #elif defined TARGET_OS_Linux || defined TARGET_OS_MacOS - /* - unsigned char valin; - int dirin=1; - int dirout=0; + /* + unsigned char valin; + int dirin=1; + int dirout=0; - if (ioctl (fd, PPDATADIR, &dirin) < 0) { return 0; } - if (ioctl(fd, PPRDATA, &valin) < 0) { return 0; } + if (ioctl (fd, PPDATADIR, &dirin) < 0) { return 0; } + if (ioctl(fd, PPRDATA, &valin) < 0) { return 0; } - int res = ::read(m_file, buffer, size); - if(res < 0) - { - this->close(); - return 0; - } + int res = ::read(m_file, buffer, size); + if(res < 0) + { + this->close(); + return 0; + } - return res; - */ + return res; + */ #endif - return 0; - } + return 0; + } - bool sendBufferBlocking(const void* buffer, const size_t size) override - { - const char* p = reinterpret_cast<const char*>(buffer); - size_t bytesLeft = size; + bool sendBufferBlocking(const void* buffer, const size_t size) override + { + const char* p = reinterpret_cast<const char*>(buffer); + size_t bytesLeft = size; - while (bytesLeft != 0 && this->isConnected()) { bytesLeft -= this->sendBuffer(p + size - bytesLeft, bytesLeft); } + while (bytesLeft != 0 && this->isConnected()) { bytesLeft -= this->sendBuffer(p + size - bytesLeft, bytesLeft); } - return this->isConnected(); - } + return this->isConnected(); + } - bool receiveBufferBlocking(void* buffer, const size_t size) override - { - char* p = reinterpret_cast<char*>(buffer); - size_t bytesLeft = size; + bool receiveBufferBlocking(void* buffer, const size_t size) override + { + char* p = reinterpret_cast<char*>(buffer); + size_t bytesLeft = size; - while (bytesLeft != 0 && this->isConnected()) { bytesLeft -= this->receiveBuffer(p + size - bytesLeft, bytesLeft); } + while (bytesLeft != 0 && this->isConnected()) { bytesLeft -= this->receiveBuffer(p + size - bytesLeft, bytesLeft); } - return this->isConnected(); - } + return this->isConnected(); + } #if defined TARGET_OS_Windows - bool isConnected() const override { return m_portNumber != 0; } + bool isConnected() const override { return m_portNumber != 0; } #elif defined TARGET_OS_Linux || defined TARGET_OS_MacOS bool isConnected() const override { return m_file != 0; } #endif - void release() override - { + void release() override + { #if defined TARGET_OS_Windows - if (m_port != nullptr && !FreeLibrary(m_port)) { m_lastError = getLastErrorFormated(); } + if (m_port != nullptr && !FreeLibrary(m_port)) { m_lastError = getLastErrorFormated(); } #endif - delete this; - } + delete this; + } - bool connect(const unsigned short portNumber) override - { - if (this->isConnected()) { return false; } + bool connect(const unsigned short portNumber) override + { + if (this->isConnected()) { return false; } #if defined TARGET_OS_Windows - if (m_port != nullptr) + if (m_port != nullptr) + { + if (m_portOpen()) { - if (m_portOpen()) - { - m_lastError = "No error"; - m_portNumber = portNumber; - return true; - } - m_lastError = "Cannot open the TVic library"; - m_portNumber = 0; - return false; + m_lastError = "No error"; + m_portNumber = portNumber; + return true; } - m_lastError = "TVicPort library is not loaded."; + m_lastError = "Cannot open the TVic library"; + m_portNumber = 0; return false; + } + m_lastError = "TVicPort library is not loaded."; + return false; #elif defined TARGET_OS_Linux || defined TARGET_OS_MacOS @@ -225,38 +224,38 @@ namespace Socket */ #endif - } + } - std::string getLastError() override { return m_lastError; } + std::string getLastError() override { return m_lastError; } - std::string getLastErrorFormated() - { + std::string getLastErrorFormated() + { #if defined TARGET_OS_Windows - LPTSTR errorText; - const DWORD error = GetLastError(); + LPTSTR errorText; + const DWORD error = GetLastError(); - FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM // use system message tables to retrieve error text - | FORMAT_MESSAGE_ALLOCATE_BUFFER // allocate buffer on local heap for error text - | FORMAT_MESSAGE_IGNORE_INSERTS, // Important! will fail otherwise, since we're not (and CANNOT) pass insertion parameters - nullptr, // unused with FORMAT_MESSAGE_FROM_SYSTEM - error, - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), - LPTSTR(&errorText), // output - 0, // minimum size for output buffer - nullptr); // arguments - see note + FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM // use system message tables to retrieve error text + | FORMAT_MESSAGE_ALLOCATE_BUFFER // allocate buffer on local heap for error text + | FORMAT_MESSAGE_IGNORE_INSERTS, // Important! will fail otherwise, since we're not (and CANNOT) pass insertion parameters + nullptr, // unused with FORMAT_MESSAGE_FROM_SYSTEM + error, + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + LPTSTR(&errorText), // output + 0, // minimum size for output buffer + nullptr); // arguments - see note - return errorText + std::to_string(static_cast<uint64_t>(error)); + return errorText + std::to_string(static_cast<uint64_t>(error)); #elif defined TARGET_OS_Linux || defined TARGET_OS_MacOS return "Not implemented."; #endif - } + } #if defined TARGET_OS_Linux || defined TARGET_OS_MacOS int m_file; #endif - }; +}; - IConnectionParallel* createConnectionParallel() { return new CConnectionParallel(); } -} // namespace Socket +IConnectionParallel* createConnectionParallel() { return new CConnectionParallel(); } +} // namespace Socket diff --git a/modules/socket/src/IConnectionSerial.cpp b/modules/socket/src/IConnectionSerial.cpp index d52db6d10e1549262b40d51c4e4121101996470d..deb5332d943ac7658847e79c7c3b3f1588080075 100755 --- a/modules/socket/src/IConnectionSerial.cpp +++ b/modules/socket/src/IConnectionSerial.cpp @@ -25,37 +25,36 @@ // Good resources at http://www.tldp.org/HOWTO/html_single/Serial-HOWTO/ #endif -namespace Socket +namespace Socket { +class CConnectionSerial final : public IConnectionSerial { - class CConnectionSerial final : public IConnectionSerial - { - public: +public: #if defined TARGET_OS_Windows - CConnectionSerial() : m_file(nullptr) { } + CConnectionSerial() : m_file(nullptr) { } #elif defined TARGET_OS_Linux || defined TARGET_OS_MacOS CConnectionSerial() : m_file(0) { } #endif - bool open() override { return false; } // Should never be used + bool open() override { return false; } // Should never be used - bool close() override - { + bool close() override + { #if defined TARGET_OS_Windows - if (m_file != nullptr) + if (m_file != nullptr) + { + if (!CloseHandle(m_file)) { - if (!CloseHandle(m_file)) - { - m_LastError = "Failed to close the serial port:" + this->getLastErrorFormated(); - m_file = nullptr; - return false; - } - - m_file = nullptr; + m_LastError = "Failed to close the serial port:" + this->getLastErrorFormated(); + m_file = nullptr; + return false; } + m_file = nullptr; + } + #elif defined TARGET_OS_Linux || defined TARGET_OS_MacOS if(m_file != -1) @@ -66,17 +65,17 @@ namespace Socket #endif - return true; - } + return true; + } #if defined TARGET_OS_Windows - bool isReadyToSend(const size_t /*timeOut*/) const override - { - if (!this->isConnected()) { return false; } - return true; - } + bool isReadyToSend(const size_t /*timeOut*/) const override + { + if (!this->isConnected()) { return false; } + return true; + } #elif defined TARGET_OS_Linux || defined TARGET_OS_MacOS bool isReadyToSend(const size_t timeOut) const override @@ -99,15 +98,15 @@ namespace Socket #endif #if defined TARGET_OS_Windows - bool isReadyToReceive(const size_t /*timeOut*/) const override - { - if (!this->isConnected()) { return false; } - struct _COMSTAT status; - DWORD state; + bool isReadyToReceive(const size_t /*timeOut*/) const override + { + if (!this->isConnected()) { return false; } + struct _COMSTAT status; + DWORD state; - if (ClearCommError(m_file, &state, &status) != 0) { return status.cbInQue != 0; } - return false; - } + if (ClearCommError(m_file, &state, &status) != 0) { return status.cbInQue != 0; } + return false; + } #elif defined TARGET_OS_Linux || defined TARGET_OS_MacOS bool isReadyToReceive(const size_t timeOut) const override { @@ -127,25 +126,25 @@ namespace Socket } #endif - size_t getPendingByteCount() override + size_t getPendingByteCount() override + { + if (!this->isConnected()) { - if (!this->isConnected()) - { - m_LastError = "Serial port not connected."; - return 0; - } + m_LastError = "Serial port not connected."; + return 0; + } #if defined TARGET_OS_Windows - struct _COMSTAT status; - DWORD state; + struct _COMSTAT status; + DWORD state; - if (ClearCommError(m_file, &state, &status) == 0) - { - m_LastError = "Failed to clear the serial port communication error: " + this->getLastErrorFormated(); - return 0; - } - return status.cbInQue; + if (ClearCommError(m_file, &state, &status) == 0) + { + m_LastError = "Failed to clear the serial port communication error: " + this->getLastErrorFormated(); + return 0; + } + return status.cbInQue; #elif defined TARGET_OS_Linux || defined TARGET_OS_MacOS @@ -158,23 +157,23 @@ namespace Socket return byteCount; #endif - } + } - bool flush() override + bool flush() override + { + if (!this->isConnected()) { - if (!this->isConnected()) - { - m_LastError = "Serial port not connected."; - return false; - } + m_LastError = "Serial port not connected."; + return false; + } #if defined TARGET_OS_Windows - if (!FlushFileBuffers(m_file)) - { - m_LastError = "Failed to flush serial port buffer: " + this->getLastErrorFormated(); - return false; - } - return true; + if (!FlushFileBuffers(m_file)) + { + m_LastError = "Failed to flush serial port buffer: " + this->getLastErrorFormated(); + return false; + } + return true; #elif defined TARGET_OS_Linux || defined TARGET_OS_MacOS if(-1 == ::tcdrain(m_file)) { @@ -185,34 +184,34 @@ namespace Socket #else return false; #endif - } + } - size_t sendBuffer(const void* buffer, const size_t size) override + size_t sendBuffer(const void* buffer, const size_t size) override + { + if (!this->isConnected()) { - if (!this->isConnected()) - { - m_LastError = "Serial port not connected."; - return 0; - } + m_LastError = "Serial port not connected."; + return 0; + } #if defined TARGET_OS_Windows - DWORD written = 0; + DWORD written = 0; - if (!WriteFile(m_file, buffer, DWORD(size), &written, nullptr)) - { - m_LastError = "Failed to write on serial port: " + this->getLastErrorFormated(); - this->close(); - return 0; - } + if (!WriteFile(m_file, buffer, DWORD(size), &written, nullptr)) + { + m_LastError = "Failed to write on serial port: " + this->getLastErrorFormated(); + this->close(); + return 0; + } - if (written == 0) - { - m_LastError = "Serial port timeout when trying to write."; - this->close(); - return 0; - } + if (written == 0) + { + m_LastError = "Serial port timeout when trying to write."; + this->close(); + return 0; + } - return written; + return written; #elif defined TARGET_OS_Linux || defined TARGET_OS_MacOS @@ -228,35 +227,35 @@ namespace Socket #else return 0; #endif - } + } - size_t receiveBuffer(void* buffer, const size_t size) override + size_t receiveBuffer(void* buffer, const size_t size) override + { + if (!this->isConnected()) { - if (!this->isConnected()) - { - m_LastError = "Serial port not connected."; - return 0; - } + m_LastError = "Serial port not connected."; + return 0; + } #if defined TARGET_OS_Windows - DWORD read = 0; + DWORD read = 0; - if (!ReadFile(m_file, buffer, DWORD(size), &read, nullptr)) - { - m_LastError = "Failed to read on serial port: " + this->getLastErrorFormated(); - this->close(); - return 0; - } + if (!ReadFile(m_file, buffer, DWORD(size), &read, nullptr)) + { + m_LastError = "Failed to read on serial port: " + this->getLastErrorFormated(); + this->close(); + return 0; + } - if (read == 0) - { - m_LastError = "Serial port timeout when trying to read."; - this->close(); - return 0; - } + if (read == 0) + { + m_LastError = "Serial port timeout when trying to read."; + this->close(); + return 0; + } - return read; + return read; #elif defined TARGET_OS_Linux || defined TARGET_OS_MacOS @@ -272,90 +271,90 @@ namespace Socket #else return 0; #endif - } + } + + bool sendBufferBlocking(const void* buffer, const size_t size) override + { + const char* p = reinterpret_cast<const char*>(buffer); + size_t bytesLeft = size; - bool sendBufferBlocking(const void* buffer, const size_t size) override + while (bytesLeft != 0 && this->isConnected()) { - const char* p = reinterpret_cast<const char*>(buffer); - size_t bytesLeft = size; + bytesLeft -= this->sendBuffer(p + size - bytesLeft, bytesLeft); + if (this->isErrorRaised()) { return false; } + } - while (bytesLeft != 0 && this->isConnected()) - { - bytesLeft -= this->sendBuffer(p + size - bytesLeft, bytesLeft); - if (this->isErrorRaised()) { return false; } - } + return bytesLeft == 0; + } - return bytesLeft == 0; - } + bool receiveBufferBlocking(void* buffer, const size_t size) override + { + char* p = reinterpret_cast<char*>(buffer); + size_t bytesLeft = size; - bool receiveBufferBlocking(void* buffer, const size_t size) override + while (bytesLeft != 0 && this->isConnected()) { - char* p = reinterpret_cast<char*>(buffer); - size_t bytesLeft = size; - - while (bytesLeft != 0 && this->isConnected()) - { - bytesLeft -= this->receiveBuffer(p + size - bytesLeft, bytesLeft); - if (this->isErrorRaised()) { return false; } - } - return bytesLeft == 0; + bytesLeft -= this->receiveBuffer(p + size - bytesLeft, bytesLeft); + if (this->isErrorRaised()) { return false; } } + return bytesLeft == 0; + } - bool isConnected() const override - { + bool isConnected() const override + { #if defined TARGET_OS_Windows - return ((m_file != nullptr) && (m_file != INVALID_HANDLE_VALUE)); + return ((m_file != nullptr) && (m_file != INVALID_HANDLE_VALUE)); #elif defined TARGET_OS_Linux || defined TARGET_OS_MacOS return m_file != 0; #endif - } + } - void release() override { delete this; } + void release() override { delete this; } - bool connect(const char* sURL, const size_t baudrate) override - { - m_LastError.clear(); + bool connect(const char* sURL, const size_t baudrate) override + { + m_LastError.clear(); - if (this->isConnected()) - { - m_LastError = "Serial port already connected"; - return false; - } + if (this->isConnected()) + { + m_LastError = "Serial port already connected"; + return false; + } #if defined TARGET_OS_Windows - m_file = ::CreateFile(sURL, GENERIC_READ | GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + m_file = ::CreateFile(sURL, GENERIC_READ | GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); - if (m_file == INVALID_HANDLE_VALUE || m_file == nullptr) - { - m_LastError = "Failed to open serial port: " + this->getLastErrorFormated(); - m_file = nullptr; - return false; - } + if (m_file == INVALID_HANDLE_VALUE || m_file == nullptr) + { + m_LastError = "Failed to open serial port: " + this->getLastErrorFormated(); + m_file = nullptr; + return false; + } - DCB dcb = { 0 }; + DCB dcb = { 0 }; - if (!GetCommState(m_file, &dcb)) - { - m_LastError = "Failed to get communication state: " + this->getLastErrorFormated(); - this->close(); - return false; - } + if (!GetCommState(m_file, &dcb)) + { + m_LastError = "Failed to get communication state: " + this->getLastErrorFormated(); + this->close(); + return false; + } - dcb.DCBlength = sizeof(dcb); - dcb.BaudRate = DWORD(baudrate); - dcb.ByteSize = 8; - dcb.Parity = NOPARITY; - dcb.StopBits = ONESTOPBIT; + dcb.DCBlength = sizeof(dcb); + dcb.BaudRate = DWORD(baudrate); + dcb.ByteSize = 8; + dcb.Parity = NOPARITY; + dcb.StopBits = ONESTOPBIT; - ClearCommError(m_file, nullptr, nullptr); + ClearCommError(m_file, nullptr, nullptr); - if (!SetCommState(m_file, &dcb)) - { - m_LastError = "Could not set communication state: " + this->getLastErrorFormated(); - this->close(); - return false; - } + if (!SetCommState(m_file, &dcb)) + { + m_LastError = "Could not set communication state: " + this->getLastErrorFormated(); + this->close(); + return false; + } #elif defined TARGET_OS_Linux || defined TARGET_OS_MacOS @@ -387,33 +386,33 @@ namespace Socket return false; } #endif - return true; - } + return true; + } - bool setTimeouts(const size_t decisecondsTimeout) override - { - if (!this->isConnected()) { return false; } + bool setTimeouts(const size_t decisecondsTimeout) override + { + if (!this->isConnected()) { return false; } #if defined TARGET_OS_Windows - COMMTIMEOUTS timeouts; + COMMTIMEOUTS timeouts; - if (!GetCommTimeouts(m_file, &timeouts)) - { - m_LastError = "Could not get communication timeouts: " + this->getLastErrorFormated(); - this->close(); - return false; - } + if (!GetCommTimeouts(m_file, &timeouts)) + { + m_LastError = "Could not get communication timeouts: " + this->getLastErrorFormated(); + this->close(); + return false; + } - timeouts.ReadTotalTimeoutConstant = decisecondsTimeout * 100; // Deciseconds to milliseconds - timeouts.WriteTotalTimeoutConstant = decisecondsTimeout * 100; // Deciseconds to milliseconds + timeouts.ReadTotalTimeoutConstant = decisecondsTimeout * 100; // Deciseconds to milliseconds + timeouts.WriteTotalTimeoutConstant = decisecondsTimeout * 100; // Deciseconds to milliseconds - if (!SetCommTimeouts(m_file, &timeouts)) - { - m_LastError = "Could not set communication timeouts: " + this->getLastErrorFormated(); - this->close(); - return false; - } + if (!SetCommTimeouts(m_file, &timeouts)) + { + m_LastError = "Could not set communication timeouts: " + this->getLastErrorFormated(); + this->close(); + return false; + } #elif defined TARGET_OS_Linux || defined TARGET_OS_MacOS @@ -435,42 +434,42 @@ namespace Socket } #endif - return true; - } + return true; + } - const char* getLastError() override { return m_LastError.c_str(); } + const char* getLastError() override { return m_LastError.c_str(); } - static std::string getLastErrorFormated() - { + static std::string getLastErrorFormated() + { #if defined TARGET_OS_Windows - LPTSTR errorText; - const DWORD error = GetLastError(); - FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | // use system message tables to retrieve error text - FORMAT_MESSAGE_ALLOCATE_BUFFER | // allocate buffer on local heap for error text - FORMAT_MESSAGE_IGNORE_INSERTS, // Important! will fail otherwise, since we're not (and CANNOT) pass insertion parameters - nullptr, // unused with FORMAT_MESSAGE_FROM_SYSTEM - error, - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), - LPTSTR(&errorText), // output - 0, // minimum size for output buffer - nullptr); // arguments - see note - return errorText; + LPTSTR errorText; + const DWORD error = GetLastError(); + FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | // use system message tables to retrieve error text + FORMAT_MESSAGE_ALLOCATE_BUFFER | // allocate buffer on local heap for error text + FORMAT_MESSAGE_IGNORE_INSERTS, // Important! will fail otherwise, since we're not (and CANNOT) pass insertion parameters + nullptr, // unused with FORMAT_MESSAGE_FROM_SYSTEM + error, + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + LPTSTR(&errorText), // output + 0, // minimum size for output buffer + nullptr); // arguments - see note + return errorText; #elif defined TARGET_OS_Linux || defined TARGET_OS_MacOS return ""; // TODO #endif - } + } - bool isErrorRaised() override { return !m_LastError.empty(); } - void clearError() override { m_LastError.clear(); } + bool isErrorRaised() override { return !m_LastError.empty(); } + void clearError() override { m_LastError.clear(); } - std::string m_LastError; + std::string m_LastError; #if defined TARGET_OS_Windows - void* m_file; + void* m_file; #elif defined TARGET_OS_Linux || defined TARGET_OS_MacOS int m_file; #endif - }; +}; - IConnectionSerial* createConnectionSerial() { return new CConnectionSerial(); } -} // namespace Socket +IConnectionSerial* createConnectionSerial() { return new CConnectionSerial(); } +} // namespace Socket diff --git a/modules/socket/src/IConnectionSerialDelegate.cpp b/modules/socket/src/IConnectionSerialDelegate.cpp index 7c91c8b99345cb619d1c2e7d6c5e64d54f83651f..dfd9b756dc3f66238032e0845e4d05e6f02130b4 100644 --- a/modules/socket/src/IConnectionSerialDelegate.cpp +++ b/modules/socket/src/IConnectionSerialDelegate.cpp @@ -1,40 +1,36 @@ #include "IConnectionSerialDelegate.h" -namespace Socket +namespace Socket { +class CConnectionSerialDelegate final : public IConnectionSerialDelegate { - class CConnectionSerialDelegate final : public IConnectionSerialDelegate +public: + explicit CConnectionSerialDelegate(const SConnectionSerialDelegate connectionSerialDelegate) : IConnectionSerialDelegate(connectionSerialDelegate) { - public: - explicit CConnectionSerialDelegate(const SConnectionSerialDelegate connectionSerialDelegate) : IConnectionSerialDelegate(connectionSerialDelegate) - { - m_connectionSerialDelegate = connectionSerialDelegate; - } + m_connectionSerialDelegate = connectionSerialDelegate; + } - ~CConnectionSerialDelegate() override { } + ~CConnectionSerialDelegate() override { } - bool connect(const char* url, const size_t baudRate) override - { - return m_connectionSerialDelegate.fpConnect(m_connectionSerialDelegate.connectionDelegate.data, url, baudRate); - } + bool connect(const char* url, const size_t baudRate) override + { + return m_connectionSerialDelegate.fpConnect(m_connectionSerialDelegate.connectionDelegate.data, url, baudRate); + } - size_t getPendingByteCount() override - { - return m_connectionSerialDelegate.fpGetPendingByteCount(m_connectionSerialDelegate.connectionDelegate.data); - } + size_t getPendingByteCount() override { return m_connectionSerialDelegate.fpGetPendingByteCount(m_connectionSerialDelegate.connectionDelegate.data); } - bool flush() override { return m_connectionSerialDelegate.fpFlush(m_connectionSerialDelegate.connectionDelegate.data); } + bool flush() override { return m_connectionSerialDelegate.fpFlush(m_connectionSerialDelegate.connectionDelegate.data); } - const char* getLastError() override { return m_connectionSerialDelegate.fpGetLastError(m_connectionSerialDelegate.connectionDelegate.data); } + const char* getLastError() override { return m_connectionSerialDelegate.fpGetLastError(m_connectionSerialDelegate.connectionDelegate.data); } - bool isErrorRaised() - override { return false; } // return m_connectionSerialDelegate.fpIsErrorRaised(m_connectionSerialDelegate.connectionDelegate.data); - void clearError() override { } // return m_connectionSerialDelegate.fpClearError(m_connectionSerialDelegate.connectionDelegate.data); - bool setTimeouts(const size_t /*timeout*/) - override { return true; } // return m_connectionSerialDelegate.fpSetTimeouts(m_connectionSerialDelegate.connectionDelegate.data, decisecondsTimeout); - }; + bool isErrorRaised() + override { return false; } // return m_connectionSerialDelegate.fpIsErrorRaised(m_connectionSerialDelegate.connectionDelegate.data); + void clearError() override { } // return m_connectionSerialDelegate.fpClearError(m_connectionSerialDelegate.connectionDelegate.data); + bool setTimeouts(const size_t /*timeout*/) + override { return true; } // return m_connectionSerialDelegate.fpSetTimeouts(m_connectionSerialDelegate.connectionDelegate.data, decisecondsTimeout); +}; - IConnectionSerialDelegate* createConnectionSerialDelegate(const SConnectionSerialDelegate connectionSerialDelegate) - { - return new CConnectionSerialDelegate(connectionSerialDelegate); - } -} // namespace Socket +IConnectionSerialDelegate* createConnectionSerialDelegate(const SConnectionSerialDelegate connectionSerialDelegate) +{ + return new CConnectionSerialDelegate(connectionSerialDelegate); +} +} // namespace Socket diff --git a/modules/socket/src/IConnectionServer.cpp b/modules/socket/src/IConnectionServer.cpp index 2fea0ea30bd5a44edf31e2d8ceea15db0ac437a4..443c9e63efe2038b383a3a1776ff1b9f972acab7 100644 --- a/modules/socket/src/IConnectionServer.cpp +++ b/modules/socket/src/IConnectionServer.cpp @@ -14,100 +14,99 @@ #else #endif -namespace Socket +namespace Socket { +class CConnectionServer final : public TConnection<IConnectionServer> { - class CConnectionServer final : public TConnection<IConnectionServer> - { - public: +public: - bool listen(const size_t port) override - { - if (!open()) { return false; } + bool listen(const size_t port) override + { + if (!open()) { return false; } - int reuseAddress = 1; + int reuseAddress = 1; #if defined TARGET_OS_Windows - setsockopt(m_socket, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<const char*>(&reuseAddress), sizeof(reuseAddress)); + setsockopt(m_socket, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<const char*>(&reuseAddress), sizeof(reuseAddress)); #else ::setsockopt(m_socket, SOL_SOCKET, SO_REUSEADDR, &reuseAddress, sizeof(reuseAddress)); #endif - struct sockaddr_in localHostAddress; - memset(&localHostAddress, 0, sizeof(localHostAddress)); - localHostAddress.sin_family = AF_INET; - localHostAddress.sin_port = htons(static_cast<unsigned short>(port)); - localHostAddress.sin_addr.s_addr = htonl(INADDR_ANY); + struct sockaddr_in localHostAddress; + memset(&localHostAddress, 0, sizeof(localHostAddress)); + localHostAddress.sin_family = AF_INET; + localHostAddress.sin_port = htons(static_cast<unsigned short>(port)); + localHostAddress.sin_addr.s_addr = htonl(INADDR_ANY); - if (bind(m_socket, reinterpret_cast<struct sockaddr*>(&localHostAddress), sizeof(localHostAddress)) == -1) + if (bind(m_socket, reinterpret_cast<struct sockaddr*>(&localHostAddress), sizeof(localHostAddress)) == -1) + { + /* + switch(errno) { - /* - switch(errno) - { - case EBADF: std::cout << "EBADF" << std::endl; break; - case ENOTSOCK: std::cout << "ENOTSOCK" << std::endl; break; - case EADDRINUSE: std::cout << "EADDRINUSE" << std::endl; break; - case EINVAL: std::cout << "EINVAL" << std::endl; break; - case EROFS: std::cout << "EROFS" << std::endl; break; - case EFAULT: std::cout << "EFAULT" << std::endl; break; - case ENAMETOOLONG: std::cout << "ENAMETOOLONG" << std::endl; break; - case ENOENT: std::cout << "ENOENT" << std::endl; break; - case ENOMEM: std::cout << "ENOMEM" << std::endl; break; - case ENOTDIR: std::cout << "ENOTDIR" << std::endl; break; - case EACCES: std::cout << "EACCES" << std::endl; break; - case ELOOP: std::cout << "ELOOP" << std::endl; break; - default: std::cout << "Bind_unknown" << std::endl; - } - */ - return false; + case EBADF: std::cout << "EBADF" << std::endl; break; + case ENOTSOCK: std::cout << "ENOTSOCK" << std::endl; break; + case EADDRINUSE: std::cout << "EADDRINUSE" << std::endl; break; + case EINVAL: std::cout << "EINVAL" << std::endl; break; + case EROFS: std::cout << "EROFS" << std::endl; break; + case EFAULT: std::cout << "EFAULT" << std::endl; break; + case ENAMETOOLONG: std::cout << "ENAMETOOLONG" << std::endl; break; + case ENOENT: std::cout << "ENOENT" << std::endl; break; + case ENOMEM: std::cout << "ENOMEM" << std::endl; break; + case ENOTDIR: std::cout << "ENOTDIR" << std::endl; break; + case EACCES: std::cout << "EACCES" << std::endl; break; + case ELOOP: std::cout << "ELOOP" << std::endl; break; + default: std::cout << "Bind_unknown" << std::endl; } + */ + return false; + } - if (::listen(m_socket, 32) == -1) + if (::listen(m_socket, 32) == -1) + { + /* + switch(errno) { - /* - switch(errno) - { - case EADDRINUSE: std::cout << "EADDRINUSE" << std::endl; break; - case EBADF: std::cout << "EBADF" << std::endl; break; - case ENOTSOCK: std::cout << "ENOTSOCK" << std::endl; break; - case EOPNOTSUPP: std::cout << "EOPNOTSUPP" << std::endl; break; - default: std::cout << "Listen_unknown" << std::endl; - } - */ - return false; + case EADDRINUSE: std::cout << "EADDRINUSE" << std::endl; break; + case EBADF: std::cout << "EBADF" << std::endl; break; + case ENOTSOCK: std::cout << "ENOTSOCK" << std::endl; break; + case EOPNOTSUPP: std::cout << "EOPNOTSUPP" << std::endl; break; + default: std::cout << "Listen_unknown" << std::endl; } - - return true; + */ + return false; } - IConnection* accept() override - { - struct sockaddr_in clientAddress; + return true; + } + + IConnection* accept() override + { + struct sockaddr_in clientAddress; #if defined TARGET_OS_Linux || defined TARGET_OS_MacOS socklen_t clientAddressSize = sizeof(clientAddress); #elif defined TARGET_OS_Windows - int clientAddressSize = sizeof(clientAddress); + int clientAddressSize = sizeof(clientAddress); #else #endif - const int clientSocket = int(::accept(m_socket, reinterpret_cast<struct sockaddr*>(&clientAddress), &clientAddressSize)); - if (clientSocket == -1) { return nullptr; } - return new TConnection<IConnection>(int(clientSocket)); - } + const int clientSocket = int(::accept(m_socket, reinterpret_cast<struct sockaddr*>(&clientAddress), &clientAddressSize)); + if (clientSocket == -1) { return nullptr; } + return new TConnection<IConnection>(int(clientSocket)); + } - bool getSocketPort(size_t& port) override - { - struct sockaddr_in socketInfo; + bool getSocketPort(size_t& port) override + { + struct sockaddr_in socketInfo; #if defined TARGET_OS_Linux || defined TARGET_OS_MacOS socklen_t socketInfoLength = sizeof(socketInfo); #elif defined TARGET_OS_Windows - int socketInfoLength = sizeof(socketInfo); + int socketInfoLength = sizeof(socketInfo); #endif - if (getsockname(m_socket, reinterpret_cast<sockaddr*>(&socketInfo), &socketInfoLength) == -1) { return false; } + if (getsockname(m_socket, reinterpret_cast<sockaddr*>(&socketInfo), &socketInfoLength) == -1) { return false; } - port = size_t(ntohs(socketInfo.sin_port)); - return true; - } - }; + port = size_t(ntohs(socketInfo.sin_port)); + return true; + } +}; - IConnectionServer* createConnectionServer() { return new CConnectionServer(); } -} // namespace Socket +IConnectionServer* createConnectionServer() { return new CConnectionServer(); } +} // namespace Socket diff --git a/modules/system/CMakeLists.txt b/modules/system/CMakeLists.txt index 4edba04ab56f7c2428e693e30aaea27c3d2d9eca..8c6aa795fae4a4721e7e7dd638385820a9f92214 100755 --- a/modules/system/CMakeLists.txt +++ b/modules/system/CMakeLists.txt @@ -33,12 +33,14 @@ ADD_LIBRARY(${PROJECT_NAME} SHARED ${SRC_FILES}) SET_TARGET_PROPERTIES(${PROJECT_NAME} PROPERTIES VERSION ${PROJECT_VERSION} SOVERSION ${PROJECT_VERSION_MAJOR} + FOLDER ${MODULES_FOLDER} COMPILE_FLAGS "-DSystem_Shared -DSystem_Exports") ADD_LIBRARY(${PROJECT_NAME}-static STATIC ${SRC_FILES}) SET_TARGET_PROPERTIES(${PROJECT_NAME}-static PROPERTIES VERSION ${PROJECT_VERSION} SOVERSION ${PROJECT_VERSION_MAJOR} + FOLDER ${MODULES_FOLDER} COMPILE_FLAGS "-DSystem_Static -DSystem_Exports") IF(UNIX) @@ -89,9 +91,7 @@ ENDIF() # --------------------------------- # Target macros -# Defines target operating system -# Defines target architecture -# Defines target compiler +# Defines target operating system, architecture and compiler # --------------------------------- SET_BUILD_PLATFORM() diff --git a/modules/system/include/system/WindowsUtilities.h b/modules/system/include/system/WindowsUtilities.h index 98cc2a26a7f4f24be30f5ea58f09a807e32820e4..925db5e9ddc39ffb426b7d560c6e4d0f7aca6842 100644 --- a/modules/system/include/system/WindowsUtilities.h +++ b/modules/system/include/system/WindowsUtilities.h @@ -4,29 +4,28 @@ #if defined TARGET_OS_Windows #include <windows.h> -namespace System +namespace System { +class System_API WindowsUtilities { - class System_API WindowsUtilities - { - public: - // Load a library in a matter compliant with non-ascii path - // returns the eventual error code - static void* utf16CompliantLoadLibrary(const char* path, HANDLE file = nullptr, DWORD flags = LOAD_WITH_ALTERED_SEARCH_PATH); +public: + // Load a library in a matter compliant with non-ascii path + // returns the eventual error code + static void* utf16CompliantLoadLibrary(const char* path, HANDLE file = nullptr, DWORD flags = LOAD_WITH_ALTERED_SEARCH_PATH); - static BOOL utf16CompliantSetEnvironmentVariable(const char* name, const char* value); - - // Load a library in a matter compliant with non-ascii path - // returns the eventual error code - static BOOL utf16CompliantCreateProcess(char* applicationName, char* commandLine, LPSECURITY_ATTRIBUTES processAttributes, - LPSECURITY_ATTRIBUTES threadAttributes, BOOL inheritHandles, DWORD creationFlags, LPVOID environment, - char* currentDirectory, LPSTARTUPINFO startupInfo, LPPROCESS_INFORMATION processInformation); - - // Load a library in a matter compliant with non-ascii path - // returns the eventual error code - static HINSTANCE utf16CompliantShellExecute(HWND hwnd, LPCTSTR operation, LPCTSTR file, LPCTSTR parameters, LPCTSTR directory, INT nShowCmd); - private: - WindowsUtilities() = delete; - }; -} // namespace System + static BOOL utf16CompliantSetEnvironmentVariable(const char* name, const char* value); + + // Load a library in a matter compliant with non-ascii path + // returns the eventual error code + static BOOL utf16CompliantCreateProcess(char* applicationName, char* commandLine, LPSECURITY_ATTRIBUTES processAttributes, + LPSECURITY_ATTRIBUTES threadAttributes, BOOL inheritHandles, DWORD creationFlags, LPVOID environment, + char* currentDirectory, LPSTARTUPINFO startupInfo, LPPROCESS_INFORMATION processInformation); + + // Load a library in a matter compliant with non-ascii path + // returns the eventual error code + static HINSTANCE utf16CompliantShellExecute(HWND hwnd, LPCTSTR operation, LPCTSTR file, LPCTSTR parameters, LPCTSTR directory, INT nShowCmd); +private: + WindowsUtilities() = delete; +}; +} // namespace System #endif // TARGET_OS_Windows diff --git a/modules/system/include/system/defines.h b/modules/system/include/system/defines.h index 429240ef5457717c6ea730b6b0ceb32773b749d5..fd84d2613318bd271abc29cb251a6f5800ab7dce 100644 --- a/modules/system/include/system/defines.h +++ b/modules/system/include/system/defines.h @@ -3,23 +3,23 @@ #include <ov_common_defines.h> #if defined System_Shared -#if defined TARGET_OS_Windows -#define System_API_Export __declspec(dllexport) -#define System_API_Import __declspec(dllimport) -#elif defined TARGET_OS_Linux || defined TARGET_OS_MacOS - #define System_API_Export __attribute__((visibility("default"))) - #define System_API_Import __attribute__((visibility("default"))) +# if defined TARGET_OS_Windows +# define System_API_Export __declspec(dllexport) +# define System_API_Import __declspec(dllimport) +# elif defined TARGET_OS_Linux || defined TARGET_OS_MacOS +# define System_API_Export __attribute__((visibility("default"))) +# define System_API_Import __attribute__((visibility("default"))) +# else +# define System_API_Export +# define System_API_Import +# endif #else - #define System_API_Export - #define System_API_Import -#endif -#else -#define System_API_Export -#define System_API_Import +# define System_API_Export +# define System_API_Import #endif #if defined System_Exports -#define System_API System_API_Export +# define System_API System_API_Export #else - #define System_API System_API_Import +# define System_API System_API_Import #endif diff --git a/modules/system/include/system/ovCChrono.h b/modules/system/include/system/ovCChrono.h index ad1695674445b68469eaf210a6206114c3e3b440..1c577bf16ffef30b20c0ad7028209f13dac206d3 100644 --- a/modules/system/include/system/ovCChrono.h +++ b/modules/system/include/system/ovCChrono.h @@ -3,39 +3,38 @@ #include "defines.h" #include <cstdlib> // fix Unix compatibility -namespace System +namespace System { +class System_API CChrono final { - class System_API CChrono final - { - public: +public: - CChrono() { } - ~CChrono(); + CChrono() { } + ~CChrono(); - bool reset(size_t nStep); + bool reset(size_t nStep); - bool stepIn(); - bool stepOut(); + bool stepIn(); + bool stepOut(); - uint64_t getTotalStepInDuration() const; - uint64_t getTotalStepOutDuration() const; - uint64_t getAverageStepInDuration() const; - uint64_t getAverageStepOutDuration() const; - double getStepInPercentage() const; - double getStepOutPercentage() const; + uint64_t getTotalStepInDuration() const; + uint64_t getTotalStepOutDuration() const; + uint64_t getAverageStepInDuration() const; + uint64_t getAverageStepOutDuration() const; + double getStepInPercentage() const; + double getStepOutPercentage() const; - bool hasNewEstimation(); + bool hasNewEstimation(); - private: +private: - uint64_t* m_stepInTime = nullptr; - uint64_t* m_stepOutTime = nullptr; - size_t m_nStep = 0; - size_t m_stepIdx = 0; - bool m_isInStep = false; - bool m_hasNewEstimation = false; + uint64_t* m_stepInTime = nullptr; + uint64_t* m_stepOutTime = nullptr; + size_t m_nStep = 0; + size_t m_stepIdx = 0; + bool m_isInStep = false; + bool m_hasNewEstimation = false; - uint64_t m_totalStepInTime = 0; - uint64_t m_totalStepOutTime = 0; - }; -} // namespace System + uint64_t m_totalStepInTime = 0; + uint64_t m_totalStepOutTime = 0; +}; +} // namespace System diff --git a/modules/system/include/system/ovCDynamicModule.h b/modules/system/include/system/ovCDynamicModule.h index c2e177a3f5988a7d7b4f2d957b9708b11ab3e22b..41974187b867b6501e08966e66b46c92638ce10e 100644 --- a/modules/system/include/system/ovCDynamicModule.h +++ b/modules/system/include/system/ovCDynamicModule.h @@ -13,252 +13,252 @@ #include <string> -namespace System -{ - class CDynamicModuleSymbolLoader; // forward declare to make function declaration possible +namespace System { +class CDynamicModuleSymbolLoader; // forward declare to make function declaration possible - class System_API CDynamicModule final +class System_API CDynamicModule final +{ +public: + enum ELogErrorCodes : size_t { - public: - enum ELogErrorCodes : size_t - { - LogErrorCodes_NoError = 0, - LogErrorCodes_ModuleAlreadyLoaded = 1, - LogErrorCodes_NoModuleLoaded = 2, - LogErrorCodes_FilenameEmpty = 3, - LogErrorCodes_FolderPathInvalid = 4, - LogErrorCodes_RegistryQueryFailed = 5, - LogErrorCodes_UnloadModuleFailed = 6, - LogErrorCodes_FailToLoadModule = 7, - LogErrorCodes_InvalidSymbol = 8, - LogErrorCodes_EnvironmentVariableInvalid = 9, - LogErrorCodes_ModuleNotFound = 10 - }; + LogErrorCodes_NoError = 0, + LogErrorCodes_ModuleAlreadyLoaded = 1, + LogErrorCodes_NoModuleLoaded = 2, + LogErrorCodes_FilenameEmpty = 3, + LogErrorCodes_FolderPathInvalid = 4, + LogErrorCodes_RegistryQueryFailed = 5, + LogErrorCodes_UnloadModuleFailed = 6, + LogErrorCodes_FailToLoadModule = 7, + LogErrorCodes_InvalidSymbol = 8, + LogErrorCodes_EnvironmentVariableInvalid = 9, + LogErrorCodes_ModuleNotFound = 10 + }; - CDynamicModule(); - ~CDynamicModule(); + CDynamicModule(); + ~CDynamicModule(); - /** - * \brief Load module from a path. - * - * \param modulePath - * \param symbolNameCheck Symbol to check if it is present in the module. It is optionnal and is nullptr by default. - * - * \retval true If the module loaded successfully. - * \retval false If module loading failed. - */ - bool loadFromPath(const char* modulePath, const char* symbolNameCheck = nullptr); + /** + * \brief Load module from a path. + * + * \param modulePath + * \param symbolNameCheck Symbol to check if it is present in the module. It is optionnal and is nullptr by default. + * + * \retval true If the module loaded successfully. + * \retval false If module loading failed. + */ + bool loadFromPath(const char* modulePath, const char* symbolNameCheck = nullptr); #if defined TARGET_OS_Windows - /** - * \brief Load existing module that was already loaded by the process. - * - * \param modulePath The path to the module. - * \param symbolNameCheck Symbol to check if it is present in the module. It is optionnal and is nullptr by default. - * - * \retval true If the module loaded successfully. - * \retval false If module loading failed. - */ - bool loadFromExisting(const char* modulePath, const char* symbolNameCheck = nullptr); - /** - * \brief Load module from known path. Windows only. - * - * \param standardPath A CSIDL value that identifies the folder whose path is to be retrieved. - * Only real folders are valid. If a virtual folder is specified, this function fails. - * You can force creation of a folder by combining the folder's CSIDL with CSIDL_FLAG_CREATE. - * \param modulePath Path of the module to load. - * \param symbolNameCheck Symbol to check if it is present in the module. It is optional and is nullptr by default. - * - * \retval true If the module loaded successfully. - * \retval false If module loading failed. - */ - bool loadFromKnownPath(int standardPath, const char* modulePath, const char* symbolNameCheck = nullptr); + /** + * \brief Load existing module that was already loaded by the process. + * + * \param modulePath The path to the module. + * \param symbolNameCheck Symbol to check if it is present in the module. It is optionnal and is nullptr by default. + * + * \retval true If the module loaded successfully. + * \retval false If module loading failed. + */ + bool loadFromExisting(const char* modulePath, const char* symbolNameCheck = nullptr); + /** + * \brief Load module from known path. Windows only. + * + * \param standardPath A CSIDL value that identifies the folder whose path is to be retrieved. + * Only real folders are valid. If a virtual folder is specified, this function fails. + * You can force creation of a folder by combining the folder's CSIDL with CSIDL_FLAG_CREATE. + * \param modulePath Path of the module to load. + * \param symbolNameCheck Symbol to check if it is present in the module. It is optional and is nullptr by default. + * + * \retval true If the module loaded successfully. + * \retval false If module loading failed. + */ + bool loadFromKnownPath(int standardPath, const char* modulePath, const char* symbolNameCheck = nullptr); - /** - * \brief Load module from Windows environment. Windows only. - * - * \param environmentPath Environment path. - * \param modulePath Module file path. - * \param symbolNameCheck Symbol to check if it is present in the module. It is optionnal and is nullptr by default. - * - * \retval true If the module loaded successfully. - * \retval false If module loading failed. - */ - bool loadFromEnvironment(const char* environmentPath, const char* modulePath, const char* symbolNameCheck = nullptr); + /** + * \brief Load module from Windows environment. Windows only. + * + * \param environmentPath Environment path. + * \param modulePath Module file path. + * \param symbolNameCheck Symbol to check if it is present in the module. It is optionnal and is nullptr by default. + * + * \retval true If the module loaded successfully. + * \retval false If module loading failed. + */ + bool loadFromEnvironment(const char* environmentPath, const char* modulePath, const char* symbolNameCheck = nullptr); - /** - * \brief Load module from the registry. Windows only. - * - * \param key Registry key. Check https://msdn.microsoft.com/en-us/library/windows/desktop/ms724836 - * \param registryPath Registry path. - * \param registryKeyName Key name. - * \param samDesired A mask that specifies the desired access rights to the key to be opened. - * The function fails if the security descriptor of the key does not permit the requested access for the calling process - * Check https://msdn.microsoft.com/fr-fr/library/windows/desktop/ms724878 - * \param modulePath sModulePath Module path. - * \param symbolNameCheck Symbol to check if it is present in the module. It is optionnal and is nullptr by default. - * - * \retval true If the module loaded successfully. - * \retval false If module loading failed. - */ - bool loadFromRegistry(HKEY key, const char* registryPath, const char* registryKeyName, REGSAM samDesired, const char* modulePath, const char* symbolNameCheck = nullptr); + /** + * \brief Load module from the registry. Windows only. + * + * \param key Registry key. Check https://msdn.microsoft.com/en-us/library/windows/desktop/ms724836 + * \param registryPath Registry path. + * \param registryKeyName Key name. + * \param samDesired A mask that specifies the desired access rights to the key to be opened. + * The function fails if the security descriptor of the key does not permit the requested access for the calling process + * Check https://msdn.microsoft.com/fr-fr/library/windows/desktop/ms724878 + * \param modulePath sModulePath Module path. + * \param symbolNameCheck Symbol to check if it is present in the module. It is optionnal and is nullptr by default. + * + * \retval true If the module loaded successfully. + * \retval false If module loading failed. + */ + bool loadFromRegistry(HKEY key, const char* registryPath, const char* registryKeyName, REGSAM samDesired, const char* modulePath, + const char* symbolNameCheck = nullptr); - /** - * \brief Check the module architecture. Windows only. - * The architecture type of the computer. An image file can only be run on the specified computer or a system that emulates the specified computer. - * This member can be one of the following values. - * - x86: 0x014c - * - x64: 0x8664 - * - ia64: 0x0200 - * - * \param filePath Module file path - * \param architecture Architecture code - * - * \retval true If the module architecture is equal to the architecture parameter. - * \retval false If the module is unequal to the architecture parameter. - */ - static bool isModuleCompatible(const char* filePath, int architecture); + /** + * \brief Check the module architecture. Windows only. + * The architecture type of the computer. An image file can only be run on the specified computer or a system that emulates the specified computer. + * This member can be one of the following values. + * - x86: 0x014c + * - x64: 0x8664 + * - ia64: 0x0200 + * + * \param filePath Module file path + * \param architecture Architecture code + * + * \retval true If the module architecture is equal to the architecture parameter. + * \retval false If the module is unequal to the architecture parameter. + */ + static bool isModuleCompatible(const char* filePath, int architecture); #endif - // -------------------------------------- + // -------------------------------------- - /** - * \brief Unload the module. If setShouldFreeModule(false) is called, the unload() has no effect. - * - * \retval true In case of success. - * \retval false In case of failure. - * - * \sa setShouldFreeModule - * \sa isLoaded - */ - bool unload(); + /** + * \brief Unload the module. If setShouldFreeModule(false) is called, the unload() has no effect. + * + * \retval true In case of success. + * \retval false In case of failure. + * + * \sa setShouldFreeModule + * \sa isLoaded + */ + bool unload(); - /** - * \brief Check if the module is loaded. - * - * \retval true If the module is loaded. - * \retval false If no module are loaded. - * - * \sa unload - * \sa setShouldFreeModule - */ - bool isLoaded() const { return m_Handle != nullptr; } + /** + * \brief Check if the module is loaded. + * + * \retval true If the module is loaded. + * \retval false If no module are loaded. + * + * \sa unload + * \sa setShouldFreeModule + */ + bool isLoaded() const { return m_Handle != nullptr; } - /** - * \brief Get the filename of the module. - * - * \return the file name of the module. - */ - const char* getFilename() const { return m_Filename; } + /** + * \brief Get the filename of the module. + * + * \return the file name of the module. + */ + const char* getFilename() const { return m_Filename; } - /** - * \brief Should be used to avoid the warning "Missing dll" when loading acquisition server - * This can happen when the loaded library needs a second library that is not detected. - * - * \param errorMode - */ - void setDynamicModuleErrorMode(const size_t errorMode) { m_ErrorMode = errorMode; } + /** + * \brief Should be used to avoid the warning "Missing dll" when loading acquisition server + * This can happen when the loaded library needs a second library that is not detected. + * + * \param errorMode + */ + void setDynamicModuleErrorMode(const size_t errorMode) { m_ErrorMode = errorMode; } - /** - * \brief Set if the module should, or not, be free. By default the module will be free. - * - * \param shouldFreeModule Set to true to free the module when unload is called. False otherwise. - * - * \sa unload - */ - void setShouldFreeModule(const bool shouldFreeModule) { m_ShouldFreeModule = shouldFreeModule; } + /** + * \brief Set if the module should, or not, be free. By default the module will be free. + * + * \param shouldFreeModule Set to true to free the module when unload is called. False otherwise. + * + * \sa unload + */ + void setShouldFreeModule(const bool shouldFreeModule) { m_ShouldFreeModule = shouldFreeModule; } - /** - * \brief Get the last error code. - * - * \return The error code. - */ - size_t getLastError() const; + /** + * \brief Get the last error code. + * + * \return The error code. + */ + size_t getLastError() const; - /** - * \brief Get the error message corresponding to the error code. - * - * \param errorCode The error code. - * - * \return the message corresponding to the error code. - */ - static const char* getErrorString(size_t errorCode); + /** + * \brief Get the error message corresponding to the error code. + * + * \param errorCode The error code. + * + * \return the message corresponding to the error code. + */ + static const char* getErrorString(size_t errorCode); - /** - * \brief Get the detailed error - * - * \return A string with detailed information about the last error. - */ - const char* getErrorDetails() const; + /** + * \brief Get the detailed error + * + * \return A string with detailed information about the last error. + */ + const char* getErrorDetails() const; - private: - void* m_Handle = nullptr; +private: + void* m_Handle = nullptr; #if defined TARGET_OS_Windows - char m_Filename[MAX_PATH]; + char m_Filename[MAX_PATH]; #elif defined TARGET_OS_Linux || defined TARGET_OS_MacOS char m_Filename[PATH_MAX]; #endif - size_t m_ErrorMode = 0; - bool m_ShouldFreeModule = true; - typedef void (*symbol_t)(); + size_t m_ErrorMode = 0; + bool m_ShouldFreeModule = true; + typedef void (*symbol_t)(); - char m_ErrorDetails[1024]; - mutable ELogErrorCodes m_ErrorCode; + char m_ErrorDetails[1024]; + mutable ELogErrorCodes m_ErrorCode; - static const size_t m_ErrorModeNull = 0xffffffff; + static const size_t m_ErrorModeNull = 0xffffffff; - friend class CDynamicModuleSymbolLoader; - /** - * \brief Set the error code and details. - * - * \param errorCode Error code. - * \param details Detailed string error. - */ - void setError(ELogErrorCodes errorCode, const std::string& details = std::string()); + friend class CDynamicModuleSymbolLoader; + /** + * \brief Set the error code and details. + * + * \param errorCode Error code. + * \param details Detailed string error. + */ + void setError(ELogErrorCodes errorCode, const std::string& details = std::string()); - /** - * \brief Get a symbol from the module. - * - * \param symbolName Symbol name. - * - * \return The symbol. - */ - symbol_t getSymbolGeneric(const char* symbolName) const; + /** + * \brief Get a symbol from the module. + * + * \param symbolName Symbol name. + * + * \return The symbol. + */ + symbol_t getSymbolGeneric(const char* symbolName) const; #ifdef TARGET_OS_Windows - /** - * \brief Get the image file headers. Windows only. - * - * \param filename The file path. - * \param headers [out] The header. - * - * \retval true In case of success. - * \retval false In case of failure. - */ - static bool getImageFileHeaders(const char* filename, IMAGE_NT_HEADERS& headers); + /** + * \brief Get the image file headers. Windows only. + * + * \param filename The file path. + * \param headers [out] The header. + * + * \retval true In case of success. + * \retval false In case of failure. + */ + static bool getImageFileHeaders(const char* filename, IMAGE_NT_HEADERS& headers); #endif - }; +}; - class CDynamicModuleSymbolLoader +class CDynamicModuleSymbolLoader +{ +public: + /** + * \brief Get a symbol from the module. + * + * \param dynamicModule + * \param symbolName The symbol name. + * \param symbol [out] The symbol. + * + * \retval true If the symbol exists. + * \retval false If the symbol does not exist. + */ + template <typename T> + static bool getSymbol(CDynamicModule& dynamicModule, const char* symbolName, T* symbol) { - public: - /** - * \brief Get a symbol from the module. - * - * \param dynamicModule - * \param symbolName The symbol name. - * \param symbol [out] The symbol. - * - * \retval true If the symbol exists. - * \retval false If the symbol does not exist. - */ - template <typename T> - static bool getSymbol(CDynamicModule& dynamicModule, const char* symbolName, T* symbol) - { - *symbol = reinterpret_cast<T>(dynamicModule.getSymbolGeneric(symbolName)); - return *symbol != nullptr; - } - }; -} // namespace System + *symbol = reinterpret_cast<T>(dynamicModule.getSymbolGeneric(symbolName)); + return *symbol != nullptr; + } +}; +} // namespace System diff --git a/modules/system/include/system/ovCMath.h b/modules/system/include/system/ovCMath.h index 86c589ffa32b1db879d60ce204c2ba1945b8fc53..fba4d23160586b0e79f13b1120259f83ab22da68 100644 --- a/modules/system/include/system/ovCMath.h +++ b/modules/system/include/system/ovCMath.h @@ -5,21 +5,20 @@ #include <cmath> #include <cstdlib> // fix Unix compatibility -namespace System +namespace System { +class System_API Math { - class System_API Math - { - public: +public: - static bool initializeRandomMachine(size_t randomSeed); + static bool initializeRandomMachine(size_t randomSeed); - static size_t randomI(); - // returns a value in [0,upperLimit( -- i.e. upperLimit not included in range - static size_t randomWithCeiling(const size_t upperLimit); - static double random0To1(); - static uint64_t random(); + static size_t randomI(); + // returns a value in [0,upperLimit( -- i.e. upperLimit not included in range + static size_t randomWithCeiling(const size_t upperLimit); + static double random0To1(); + static uint64_t random(); - private: - Math() = delete; - }; -} // namespace System +private: + Math() = delete; +}; +} // namespace System diff --git a/modules/system/include/system/ovCMemory.h b/modules/system/include/system/ovCMemory.h index 44c6e31ef37504feef4cc880595c701eb6ae2bfc..b23acbf94b83f83529dbd156529c9198b897af1e 100644 --- a/modules/system/include/system/ovCMemory.h +++ b/modules/system/include/system/ovCMemory.h @@ -3,51 +3,50 @@ #include "defines.h" #include <cstdlib> // fix Unix compatibility -namespace System +namespace System { +class System_API Memory { - class System_API Memory - { - public: +public: - static bool hostToLittleEndian(uint16_t value, uint8_t* buffer); - static bool hostToLittleEndian(uint32_t value, uint8_t* buffer); - static bool hostToLittleEndian(uint64_t value, uint8_t* buffer); - static bool hostToLittleEndian(int16_t value, uint8_t* buffer); - static bool hostToLittleEndian(int value, uint8_t* buffer); - static bool hostToLittleEndian(int64_t value, uint8_t* buffer); - static bool hostToLittleEndian(float value, uint8_t* buffer); - static bool hostToLittleEndian(double value, uint8_t* buffer); - static bool hostToLittleEndian(long double value, uint8_t* buffer); - static bool hostToBigEndian(uint16_t value, uint8_t* buffer); - static bool hostToBigEndian(uint32_t value, uint8_t* buffer); - static bool hostToBigEndian(uint64_t value, uint8_t* buffer); - static bool hostToBigEndian(int16_t value, uint8_t* buffer); - static bool hostToBigEndian(int value, uint8_t* buffer); - static bool hostToBigEndian(int64_t value, uint8_t* buffer); - static bool hostToBigEndian(float value, uint8_t* buffer); - static bool hostToBigEndian(double value, uint8_t* buffer); - static bool hostToBigEndian(long double value, uint8_t* buffer); + static bool hostToLittleEndian(uint16_t value, uint8_t* buffer); + static bool hostToLittleEndian(uint32_t value, uint8_t* buffer); + static bool hostToLittleEndian(uint64_t value, uint8_t* buffer); + static bool hostToLittleEndian(int16_t value, uint8_t* buffer); + static bool hostToLittleEndian(int value, uint8_t* buffer); + static bool hostToLittleEndian(int64_t value, uint8_t* buffer); + static bool hostToLittleEndian(float value, uint8_t* buffer); + static bool hostToLittleEndian(double value, uint8_t* buffer); + static bool hostToLittleEndian(long double value, uint8_t* buffer); + static bool hostToBigEndian(uint16_t value, uint8_t* buffer); + static bool hostToBigEndian(uint32_t value, uint8_t* buffer); + static bool hostToBigEndian(uint64_t value, uint8_t* buffer); + static bool hostToBigEndian(int16_t value, uint8_t* buffer); + static bool hostToBigEndian(int value, uint8_t* buffer); + static bool hostToBigEndian(int64_t value, uint8_t* buffer); + static bool hostToBigEndian(float value, uint8_t* buffer); + static bool hostToBigEndian(double value, uint8_t* buffer); + static bool hostToBigEndian(long double value, uint8_t* buffer); - static bool littleEndianToHost(const uint8_t* buffer, uint16_t* value); - static bool littleEndianToHost(const uint8_t* buffer, uint32_t* value); - static bool littleEndianToHost(const uint8_t* buffer, uint64_t* value); - static bool littleEndianToHost(const uint8_t* buffer, int16_t* value); - static bool littleEndianToHost(const uint8_t* buffer, int* value); - static bool littleEndianToHost(const uint8_t* buffer, int64_t* value); - static bool littleEndianToHost(const uint8_t* buffer, float* value); - static bool littleEndianToHost(const uint8_t* buffer, double* value); - static bool littleEndianToHost(const uint8_t* buffer, long double* value); - static bool bigEndianToHost(const uint8_t* buffer, uint16_t* value); - static bool bigEndianToHost(const uint8_t* buffer, uint32_t* value); - static bool bigEndianToHost(const uint8_t* buffer, uint64_t* value); - static bool bigEndianToHost(const uint8_t* buffer, int16_t* value); - static bool bigEndianToHost(const uint8_t* buffer, int* value); - static bool bigEndianToHost(const uint8_t* buffer, int64_t* value); - static bool bigEndianToHost(const uint8_t* buffer, float* value); - static bool bigEndianToHost(const uint8_t* buffer, double* value); - static bool bigEndianToHost(const uint8_t* buffer, long double* value); + static bool littleEndianToHost(const uint8_t* buffer, uint16_t* value); + static bool littleEndianToHost(const uint8_t* buffer, uint32_t* value); + static bool littleEndianToHost(const uint8_t* buffer, uint64_t* value); + static bool littleEndianToHost(const uint8_t* buffer, int16_t* value); + static bool littleEndianToHost(const uint8_t* buffer, int* value); + static bool littleEndianToHost(const uint8_t* buffer, int64_t* value); + static bool littleEndianToHost(const uint8_t* buffer, float* value); + static bool littleEndianToHost(const uint8_t* buffer, double* value); + static bool littleEndianToHost(const uint8_t* buffer, long double* value); + static bool bigEndianToHost(const uint8_t* buffer, uint16_t* value); + static bool bigEndianToHost(const uint8_t* buffer, uint32_t* value); + static bool bigEndianToHost(const uint8_t* buffer, uint64_t* value); + static bool bigEndianToHost(const uint8_t* buffer, int16_t* value); + static bool bigEndianToHost(const uint8_t* buffer, int* value); + static bool bigEndianToHost(const uint8_t* buffer, int64_t* value); + static bool bigEndianToHost(const uint8_t* buffer, float* value); + static bool bigEndianToHost(const uint8_t* buffer, double* value); + static bool bigEndianToHost(const uint8_t* buffer, long double* value); - private: - Memory() = delete; - }; -} // namespace System +private: + Memory() = delete; +}; +} // namespace System diff --git a/modules/system/include/system/ovCTime.h b/modules/system/include/system/ovCTime.h index 356ae59b753bdf039739a400da3e6afc7497f815..6e3fdb7b4121a5f240ad1f59796c13fc49fd2880 100644 --- a/modules/system/include/system/ovCTime.h +++ b/modules/system/include/system/ovCTime.h @@ -3,71 +3,70 @@ #include "defines.h" #include <cstdlib> // For Unix Compatibility -namespace System +namespace System { +/** + * \class Time + * \brief Static functions to handle time within the framework + * + */ +class System_API Time { +public: + /** - * \class Time - * \brief Static functions to handle time within the framework - * + * \brief Make the calling thread sleep + * \param milliSeconds : sleep duration in ms + * \return Always true */ - class System_API Time - { - public: + static bool sleep(const size_t milliSeconds); - /** - * \brief Make the calling thread sleep - * \param milliSeconds : sleep duration in ms - * \return Always true - */ - static bool sleep(const size_t milliSeconds); - - /** - * \brief Make the calling thread sleep - * \param seconds : sleep duration in fixed point 32:32 seconds - * \return Always true - */ - static bool zsleep(const uint64_t seconds); - - /** - * \brief Retrieve time in ms (turn the 32:32 fixed point seconds to milliseconds). - * \return Elapsed time in ms since the first call to this function or zgetTime functions - */ - static uint32_t getTime() { return uint32_t((zgetTime() * 1000) >> 32); } + /** + * \brief Make the calling thread sleep + * \param seconds : sleep duration in fixed point 32:32 seconds + * \return Always true + */ + static bool zsleep(const uint64_t seconds); - /** - * \brief Retrieve time in fixed point 32:32 seconds - * \return Elapsed time since the first call to the zgetTime functions or getTime. - */ - static uint64_t zgetTime() { return zgetTimeRaw(true); } + /** + * \brief Retrieve time in ms (turn the 32:32 fixed point seconds to milliseconds). + * \return Elapsed time in ms since the first call to this function or zgetTime functions + */ + static uint32_t getTime() { return uint32_t((zgetTime() * 1000) >> 32); } - /** - * \brief Retrieve time in fixed point 32:32 seconds - * \param sinceFirstCall: If sinceFirstCall is true, returns the time since the first call to the zgetTime function or getTime. - * Otherwise, returns time since epoch of the clock. - * \return Elapsed time - */ - static uint64_t zgetTimeRaw(bool sinceFirstCall = true); + /** + * \brief Retrieve time in fixed point 32:32 seconds + * \return Elapsed time since the first call to the zgetTime functions or getTime. + */ + static uint64_t zgetTime() { return zgetTimeRaw(true); } - /** - * \brief Check if the internal clock used by the framework is steady - * \return True if the clock is steady, false otherwise - * \note This is a theoretical check that queries the internal - * clock implementation for available services - */ - static bool isClockSteady(); - - /** - * \brief Check if the internal clock used by the framework has - * a resolution higher than the required one - * \param milliSeconds : Expected clock resolution (period between ticks) in ms (must be non-zero value) - * \return True if the clock meets the requirements, false otherwise - * \note This is a theoretical check that queries the internal - * clock implementation for available services - */ - static bool checkResolution(const size_t milliSeconds); + /** + * \brief Retrieve time in fixed point 32:32 seconds + * \param sinceFirstCall: If sinceFirstCall is true, returns the time since the first call to the zgetTime function or getTime. + * Otherwise, returns time since epoch of the clock. + * \return Elapsed time + */ + static uint64_t zgetTimeRaw(bool sinceFirstCall = true); + + /** + * \brief Check if the internal clock used by the framework is steady + * \return True if the clock is steady, false otherwise + * \note This is a theoretical check that queries the internal + * clock implementation for available services + */ + static bool isClockSteady(); + + /** + * \brief Check if the internal clock used by the framework has + * a resolution higher than the required one + * \param milliSeconds : Expected clock resolution (period between ticks) in ms (must be non-zero value) + * \return True if the clock meets the requirements, false otherwise + * \note This is a theoretical check that queries the internal + * clock implementation for available services + */ + static bool checkResolution(const size_t milliSeconds); - private: +private: - Time() = delete; - }; -} // namespace System + Time() = delete; +}; +} // namespace System diff --git a/modules/system/src/WindowsUtilities.cpp b/modules/system/src/WindowsUtilities.cpp index d46b4a4d163f625306d940e96d3d0ec0fee15fbb..a7ee0d65deeba1db450345951d978e5072786496 100644 --- a/modules/system/src/WindowsUtilities.cpp +++ b/modules/system/src/WindowsUtilities.cpp @@ -18,11 +18,12 @@ void* WindowsUtilities::utf16CompliantLoadLibrary(const char* path, const HANDLE } BOOL WindowsUtilities::utf16CompliantSetEnvironmentVariable(const char* name, const char* value) { return SetEnvironmentVariable(name, value); } - + // Load a library in a matter compliant with non-ascii path // returns the eventual error code BOOL WindowsUtilities::utf16CompliantCreateProcess(char* applicationName, char* commandLine, LPSECURITY_ATTRIBUTES processAttributes, - LPSECURITY_ATTRIBUTES threadAttributes, const BOOL inheritHandles, const DWORD creationFlags, LPVOID environment, + LPSECURITY_ATTRIBUTES threadAttributes, const BOOL inheritHandles, const DWORD creationFlags, + LPVOID environment, char* currentDirectory, LPSTARTUPINFO startupInfo, LPPROCESS_INFORMATION processInformation) { return CreateProcess(applicationName, const_cast<char*>(commandLine), processAttributes, threadAttributes, diff --git a/modules/system/src/ovCChrono.cpp b/modules/system/src/ovCChrono.cpp index 5e4dcce64a769834b9add10362ec611419fec54d..cf71bda71ff1ddfea9ede10795f694131313901b 100644 --- a/modules/system/src/ovCChrono.cpp +++ b/modules/system/src/ovCChrono.cpp @@ -83,11 +83,8 @@ bool CChrono::stepOut() } uint64_t CChrono::getTotalStepInDuration() const { return m_totalStepInTime; } - uint64_t CChrono::getTotalStepOutDuration() const { return m_totalStepOutTime; } - uint64_t CChrono::getAverageStepInDuration() const { return m_nStep ? this->getTotalStepInDuration() / m_nStep : 0; } - uint64_t CChrono::getAverageStepOutDuration() const { return m_nStep ? this->getTotalStepOutDuration() / m_nStep : 0; } double CChrono::getStepInPercentage() const diff --git a/modules/system/src/ovCDynamicModule.cpp b/modules/system/src/ovCDynamicModule.cpp index 1aaf8068d3cd7f4541cd345141a86388e496152c..16ae4ed8a3bfa81af1ef4e5221a6051e2453da4c 100644 --- a/modules/system/src/ovCDynamicModule.cpp +++ b/modules/system/src/ovCDynamicModule.cpp @@ -12,55 +12,54 @@ using namespace System; -namespace +namespace { +const std::map<CDynamicModule::ELogErrorCodes, std::string> ERROR_MAP = { - const std::map<CDynamicModule::ELogErrorCodes, std::string> ERROR_MAP = - { - { CDynamicModule::LogErrorCodes_ModuleAlreadyLoaded, "A module is already loaded." }, - { CDynamicModule::LogErrorCodes_NoModuleLoaded, "No module loaded." }, - { CDynamicModule::LogErrorCodes_FilenameEmpty, "The filename is empty." }, - { CDynamicModule::LogErrorCodes_FolderPathInvalid, "The folder path is invalid." }, - { CDynamicModule::LogErrorCodes_RegistryQueryFailed, "The registry query is invalid." }, - { CDynamicModule::LogErrorCodes_UnloadModuleFailed, "Fail to unload the module." }, - { CDynamicModule::LogErrorCodes_FailToLoadModule, "Fail to load the module." }, - { CDynamicModule::LogErrorCodes_InvalidSymbol, "The symbol is invalid." }, - { CDynamicModule::LogErrorCodes_ModuleNotFound, "Module not found." } - }; + { CDynamicModule::LogErrorCodes_ModuleAlreadyLoaded, "A module is already loaded." }, + { CDynamicModule::LogErrorCodes_NoModuleLoaded, "No module loaded." }, + { CDynamicModule::LogErrorCodes_FilenameEmpty, "The filename is empty." }, + { CDynamicModule::LogErrorCodes_FolderPathInvalid, "The folder path is invalid." }, + { CDynamicModule::LogErrorCodes_RegistryQueryFailed, "The registry query is invalid." }, + { CDynamicModule::LogErrorCodes_UnloadModuleFailed, "Fail to unload the module." }, + { CDynamicModule::LogErrorCodes_FailToLoadModule, "Fail to load the module." }, + { CDynamicModule::LogErrorCodes_InvalidSymbol, "The symbol is invalid." }, + { CDynamicModule::LogErrorCodes_ModuleNotFound, "Module not found." } +}; #if defined TARGET_OS_Windows - std::vector<std::string> split(char* str, const char* delim) - { - char* token = strtok(str, delim); - - std::vector<std::string> result; - - while (token != nullptr) - { - result.push_back(token); - token = strtok(nullptr, delim); - } +std::vector<std::string> split(char* str, const char* delim) +{ + char* token = strtok(str, delim); - return result; - } + std::vector<std::string> result; - std::string formatWindowsError(const DWORD code) + while (token != nullptr) { - LPTSTR text; - - FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | // use system message tables to retrieve error text - FORMAT_MESSAGE_ALLOCATE_BUFFER | // allocate buffer on local heap for error text - FORMAT_MESSAGE_IGNORE_INSERTS, // Important! will fail otherwise, since we're not (and CANNOT) pass insertion parameters - nullptr, // unused with FORMAT_MESSAGE_FROM_SYSTEM - code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), - LPTSTR(&text), // output - 0, // minimum size for output buffer - nullptr - ); // arguments - see note - - return std::string(text); + result.push_back(token); + token = strtok(nullptr, delim); } + + return result; +} + +std::string formatWindowsError(const DWORD code) +{ + LPTSTR text; + + FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | // use system message tables to retrieve error text + FORMAT_MESSAGE_ALLOCATE_BUFFER | // allocate buffer on local heap for error text + FORMAT_MESSAGE_IGNORE_INSERTS, // Important! will fail otherwise, since we're not (and CANNOT) pass insertion parameters + nullptr, // unused with FORMAT_MESSAGE_FROM_SYSTEM + code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + LPTSTR(&text), // output + 0, // minimum size for output buffer + nullptr + ); // arguments - see note + + return std::string(text); +} #endif -} // namespace +} // namespace const char* CDynamicModule::getErrorString(size_t errorCode) { @@ -69,7 +68,6 @@ const char* CDynamicModule::getErrorString(size_t errorCode) } const char* CDynamicModule::getErrorDetails() const { return &m_ErrorDetails[0]; } - size_t CDynamicModule::getLastError() const { return m_ErrorCode; } CDynamicModule::CDynamicModule() @@ -283,7 +281,7 @@ bool CDynamicModule::unload() this->setError(LogErrorCodes_NoModuleLoaded); return false; } - + // If the flag m_shouldFreeModule, set to true per default, is set to false, // the module is not unloaded. // This flag was first set for Enobio3G driver which dll freezes when unloaded diff --git a/modules/system/src/ovCMemory.cpp b/modules/system/src/ovCMemory.cpp index 3a4e988a0f15e9ff578d8c1102945c0f920f70f5..5612009086cbd38ab9d9092e3dfb03892c12aaea 100644 --- a/modules/system/src/ovCMemory.cpp +++ b/modules/system/src/ovCMemory.cpp @@ -45,15 +45,10 @@ bool HostToLittleEndian(const T& value, uint8_t* buffer) // bool Memory::hostToLittleEndian(const uint16_t value, uint8_t* buffer) { return HostToLittleEndian<uint16_t>(value, buffer); } - bool Memory::hostToLittleEndian(const uint32_t value, uint8_t* buffer) { return HostToLittleEndian<uint32_t>(value, buffer); } - bool Memory::hostToLittleEndian(const uint64_t value, uint8_t* buffer) { return HostToLittleEndian<uint64_t>(value, buffer); } - bool Memory::hostToLittleEndian(const int16_t value, uint8_t* buffer) { return HostToLittleEndian<int16_t>(value, buffer); } - bool Memory::hostToLittleEndian(const int value, uint8_t* buffer) { return HostToLittleEndian<int>(value, buffer); } - bool Memory::hostToLittleEndian(const int64_t value, uint8_t* buffer) { return HostToLittleEndian<int64_t>(value, buffer); } bool Memory::hostToLittleEndian(const float value, uint8_t* buffer) @@ -81,15 +76,10 @@ bool Memory::hostToLittleEndian(const long double /*value*/, uint8_t* /*buffer*/ // bool Memory::hostToBigEndian(const uint16_t value, uint8_t* buffer) { return HostToBigEndian<uint16_t>(value, buffer); } - bool Memory::hostToBigEndian(const uint32_t value, uint8_t* buffer) { return HostToBigEndian<uint32_t>(value, buffer); } - bool Memory::hostToBigEndian(const uint64_t value, uint8_t* buffer) { return HostToBigEndian<uint64_t>(value, buffer); } - bool Memory::hostToBigEndian(const int16_t value, uint8_t* buffer) { return HostToBigEndian<int16_t>(value, buffer); } - bool Memory::hostToBigEndian(const int value, uint8_t* buffer) { return HostToBigEndian<int>(value, buffer); } - bool Memory::hostToBigEndian(const int64_t value, uint8_t* buffer) { return HostToBigEndian<int64_t>(value, buffer); } bool Memory::hostToBigEndian(const float value, uint8_t* buffer) @@ -116,15 +106,10 @@ bool Memory::hostToBigEndian(const long double /*value*/, uint8_t* /*buffer*/) // bool Memory::littleEndianToHost(const uint8_t* buffer, uint16_t* value) { return LittleEndianToHost<uint16_t>(buffer, value); } - bool Memory::littleEndianToHost(const uint8_t* buffer, uint32_t* value) { return LittleEndianToHost<uint32_t>(buffer, value); } - bool Memory::littleEndianToHost(const uint8_t* buffer, uint64_t* value) { return LittleEndianToHost<uint64_t>(buffer, value); } - bool Memory::littleEndianToHost(const uint8_t* buffer, int16_t* value) { return LittleEndianToHost<int16_t>(buffer, value); } - bool Memory::littleEndianToHost(const uint8_t* buffer, int* value) { return LittleEndianToHost<int>(buffer, value); } - bool Memory::littleEndianToHost(const uint8_t* buffer, int64_t* value) { return LittleEndianToHost<int64_t>(buffer, value); } bool Memory::littleEndianToHost(const uint8_t* buffer, float* value) @@ -153,15 +138,10 @@ bool Memory::littleEndianToHost(const uint8_t* /*buffer*/, long double* /*value* // bool Memory::bigEndianToHost(const uint8_t* buffer, uint16_t* value) { return BigEndianToHost<uint16_t>(buffer, value); } - bool Memory::bigEndianToHost(const uint8_t* buffer, uint32_t* value) { return BigEndianToHost<uint32_t>(buffer, value); } - bool Memory::bigEndianToHost(const uint8_t* buffer, uint64_t* value) { return BigEndianToHost<uint64_t>(buffer, value); } - bool Memory::bigEndianToHost(const uint8_t* buffer, int16_t* value) { return BigEndianToHost<int16_t>(buffer, value); } - bool Memory::bigEndianToHost(const uint8_t* buffer, int* value) { return BigEndianToHost<int>(buffer, value); } - bool Memory::bigEndianToHost(const uint8_t* buffer, int64_t* value) { return BigEndianToHost<int64_t>(buffer, value); } bool Memory::bigEndianToHost(const uint8_t* buffer, float* value) diff --git a/modules/xml/CMakeLists.txt b/modules/xml/CMakeLists.txt index 3dc9394b989e184598f26e3062acf26df1cd8474..e05b74cfb41e995564fc0e8f3b5265b638e63662 100644 --- a/modules/xml/CMakeLists.txt +++ b/modules/xml/CMakeLists.txt @@ -13,12 +13,14 @@ ADD_LIBRARY(${PROJECT_NAME} SHARED ${SRC_FILES}) SET_TARGET_PROPERTIES(${PROJECT_NAME} PROPERTIES VERSION ${PROJECT_VERSION} SOVERSION ${PROJECT_VERSION_MAJOR} + FOLDER ${MODULES_FOLDER} COMPILE_FLAGS "-DXML_Shared -DXML_Exports") ADD_LIBRARY(${PROJECT_NAME}-static STATIC ${SRC_FILES}) SET_TARGET_PROPERTIES(${PROJECT_NAME}-static PROPERTIES VERSION ${PROJECT_VERSION} SOVERSION ${PROJECT_VERSION_MAJOR} + FOLDER ${MODULES_FOLDER} COMPILE_FLAGS "-DXML_Static -DXML_Exports") IF(UNIX) @@ -32,9 +34,7 @@ INCLUDE("FindThirdPartyExpat") # --------------------------------- # Target macros -# Defines target operating system -# Defines target architecture -# Defines target compiler +# Defines target operating system, architecture and compiler # --------------------------------- SET_BUILD_PLATFORM() diff --git a/modules/xml/include/xml/IReader.h b/modules/xml/include/xml/IReader.h index e42746732e92bb003c2c4183e2078a0cd00414f4..d9c1ffa9d3f6fa2c90005eb14393975a190590a5 100644 --- a/modules/xml/include/xml/IReader.h +++ b/modules/xml/include/xml/IReader.h @@ -3,27 +3,26 @@ #include "defines.h" #include <cstdlib> // fix Unix compatibility -namespace XML +namespace XML { +class XML_API IReaderCallback { - class XML_API IReaderCallback - { - public: - virtual ~IReaderCallback() { } - virtual void openChild(const char* name, const char** attributeName, const char** attributeValue, const size_t nAttribute) = 0; - virtual void processChildData(const char* data) = 0; - virtual void closeChild() = 0; - }; +public: + virtual ~IReaderCallback() { } + virtual void openChild(const char* name, const char** attributeName, const char** attributeValue, const size_t nAttribute) = 0; + virtual void processChildData(const char* data) = 0; + virtual void closeChild() = 0; +}; - class XML_API IReaderCallBack : public IReaderCallback { }; +class XML_API IReaderCallBack : public IReaderCallback { }; - class XML_API IReader - { - public: - virtual bool processData(const void* buffer, const size_t size) = 0; - virtual void release() = 0; - protected: - virtual ~IReader() { } - }; +class XML_API IReader +{ +public: + virtual bool processData(const void* buffer, const size_t size) = 0; + virtual void release() = 0; +protected: + virtual ~IReader() { } +}; - extern XML_API IReader* createReader(IReaderCallback& callback); -} // namespace XML +extern XML_API IReader* createReader(IReaderCallback& callback); +} // namespace XML diff --git a/modules/xml/include/xml/IWriter.h b/modules/xml/include/xml/IWriter.h index 640ed0376412c5efd6a9a68480dcd9d546953533..56607b02b19098f341cbd43e43ced8711fade141 100644 --- a/modules/xml/include/xml/IWriter.h +++ b/modules/xml/include/xml/IWriter.h @@ -2,28 +2,27 @@ #include "defines.h" -namespace XML +namespace XML { +class XML_API IWriterCallback { - class XML_API IWriterCallback - { - public: - virtual ~IWriterCallback() { } - virtual void write(const char* sString) = 0; - }; +public: + virtual ~IWriterCallback() { } + virtual void write(const char* sString) = 0; +}; - class XML_API IWriterCallBack : public IWriterCallback { }; +class XML_API IWriterCallBack : public IWriterCallback { }; - class XML_API IWriter - { - public: - virtual bool openChild(const char* name) = 0; - virtual bool setAttribute(const char* name, const char* value) = 0; - virtual bool setChildData(const char* data) = 0; - virtual bool closeChild() = 0; - virtual void release() = 0; - protected: - virtual ~IWriter() { } - }; +class XML_API IWriter +{ +public: + virtual bool openChild(const char* name) = 0; + virtual bool setAttribute(const char* name, const char* value) = 0; + virtual bool setChildData(const char* data) = 0; + virtual bool closeChild() = 0; + virtual void release() = 0; +protected: + virtual ~IWriter() { } +}; - extern XML_API IWriter* createWriter(IWriterCallback& callback); -} // namespace XML +extern XML_API IWriter* createWriter(IWriterCallback& callback); +} // namespace XML diff --git a/modules/xml/include/xml/IXMLHandler.h b/modules/xml/include/xml/IXMLHandler.h index 62c6ccb9f4e87dfb8765a95bcc032989cd362b78..c6fc25c1640d027dd4ca44048ef957cd65c160f6 100644 --- a/modules/xml/include/xml/IXMLHandler.h +++ b/modules/xml/include/xml/IXMLHandler.h @@ -5,57 +5,56 @@ #include <string> #include <cstdlib> // fix Unix compatibility -namespace XML +namespace XML { +/** + * @class IXMLHandler + * @author Serrière Guillaume (INRIA/Loria) + * @brief This class is design to help about XML manipulation. + * @sa XML + */ +class XML_API IXMLHandler { +public: /** - * @class IXMLHandler - * @author Serrière Guillaume (INRIA/Loria) - * @brief This class is design to help about XML manipulation. - * @sa XML + * @brief Release the handler. */ - class XML_API IXMLHandler - { - public: - /** - * @brief Release the handler. - */ - virtual void release() = 0; - - //Parsing - /** - * @brief Parse file points by sPath and return the root name of the document. - * @param path [in] : Path to the File - * @return The root node of the document, or NULL if there is an error. - */ - virtual IXMLNode* parseFile(const char* path) = 0; - - /** - * @brief Parse the string sString on uiSize caracters and return the root name of the document. - * @param str [in] : String which contains the XML - * @param size [in] : Size of the part to analyze - * @return The root node of the parse part, or NULL if there is an error. - */ - virtual IXMLNode* parseString(const char* str, const size_t& size) = 0; - - //XML extraction - /** - * @brief Write the XML corresponding to the node rNode in the file points by sPath. If the file exists - * it will be erase. - * @param node [in] : The node to write. - * @param path [in] : The path to the file. - * @return True on success, false otherwise. - */ - virtual bool writeXMLInFile(const IXMLNode& node, const char* path) const = 0; - - /** - * @brief Get the description of the last error that ocurred - * @return A string object containing the error description - */ - virtual std::string getLastErrorString() const = 0; - - protected: - virtual ~IXMLHandler() { } - }; - - extern XML_API IXMLHandler* createXMLHandler(); + virtual void release() = 0; + + //Parsing + /** + * @brief Parse file points by sPath and return the root name of the document. + * @param path [in] : Path to the File + * @return The root node of the document, or NULL if there is an error. + */ + virtual IXMLNode* parseFile(const char* path) = 0; + + /** + * @brief Parse the string sString on uiSize caracters and return the root name of the document. + * @param str [in] : String which contains the XML + * @param size [in] : Size of the part to analyze + * @return The root node of the parse part, or NULL if there is an error. + */ + virtual IXMLNode* parseString(const char* str, const size_t& size) = 0; + + //XML extraction + /** + * @brief Write the XML corresponding to the node rNode in the file points by sPath. If the file exists + * it will be erase. + * @param node [in] : The node to write. + * @param path [in] : The path to the file. + * @return True on success, false otherwise. + */ + virtual bool writeXMLInFile(const IXMLNode& node, const char* path) const = 0; + + /** + * @brief Get the description of the last error that ocurred + * @return A string object containing the error description + */ + virtual std::string getLastErrorString() const = 0; + +protected: + virtual ~IXMLHandler() { } +}; + +extern XML_API IXMLHandler* createXMLHandler(); } // namespace XML diff --git a/modules/xml/include/xml/IXMLNode.h b/modules/xml/include/xml/IXMLNode.h index 7dd013538d827be43d540b671123805b3aaa41ba..3ed25ff4295b50c9837d3064065e613bcbe27d64 100644 --- a/modules/xml/include/xml/IXMLNode.h +++ b/modules/xml/include/xml/IXMLNode.h @@ -4,108 +4,107 @@ #include <string> #include <cstdlib> // fix Unix compatibility -namespace XML +namespace XML { +/** + * @class IXMLNode + * @author Serrière Guillaume (INRIA/Loria) + * @brief Symbolize a node in a XML tree structure. + * @sa XML + */ +class XML_API IXMLNode { +public: + virtual void release() = 0; + + virtual const char* getName() const = 0; + + //Attribute + /** + * @brief Add the attribute name with value + * value to the node. + * @param name [in] : Name of the attribute + * @param value [in] : Value of the attribute + * @return true in success, false otherwise + */ + virtual bool addAttribute(const char* name, const char* value) = 0; + + /** + * @brief Indicate if an attribute exists or not. + * @param name [in] : Name of the attribute + * @return true if attribute exists, false otherwise + */ + virtual bool hasAttribute(const char* name) const = 0; + + /** + * @brief Return the value of an attribute. + * @param name [in] : Name of the attribute + * @return Value of the attribute + */ + virtual const char* getAttribute(const char* name) const = 0; + + //PCDATA + /** + * @brief Set the PCDATA of the node. + * @param data [in] : Value of the PCDATA + */ + virtual void setPCData(const char* data) = 0; + + /** + * @brief Apppend a string to the current PCDATA of the node + * @param data [in] : Value of teh PCDATA to append + */ + virtual void appendPCData(const char* data) = 0; + + /** + * @brief Return the PCDATA of the node. + * @return Value of PCDATA + */ + virtual const char* getPCData() const = 0; + + //Child + /** + * @brief Add a node child of the + * @param node [in] : The Node that will became the new child + */ + virtual void addChild(IXMLNode* node) = 0; + + /** + * @brief Return the ith child of the node. + * @param index [in] : index of the child. + * @return The ith child of the node. + */ + virtual IXMLNode* getChild(const size_t index) const = 0; + + /** + * @brief Return the first child with the name name. + * @param name [in]] : Name of th child + * @return The first child of the node which name is name. + */ + virtual IXMLNode* getChildByName(const char* name) const = 0; + /** - * @class IXMLNode - * @author Serrière Guillaume (INRIA/Loria) - * @brief Symbolize a node in a XML tree structure. - * @sa XML + * @brief Return the amount of child the node has. + * @return Amount of child. */ - class XML_API IXMLNode - { - public: - virtual void release() = 0; - - virtual const char* getName() const = 0; - - //Attribute - /** - * @brief Add the attribute name with value - * value to the node. - * @param name [in] : Name of the attribute - * @param value [in] : Value of the attribute - * @return true in success, false otherwise - */ - virtual bool addAttribute(const char* name, const char* value) = 0; - - /** - * @brief Indicate if an attribute exists or not. - * @param name [in] : Name of the attribute - * @return true if attribute exists, false otherwise - */ - virtual bool hasAttribute(const char* name) const = 0; - - /** - * @brief Return the value of an attribute. - * @param name [in] : Name of the attribute - * @return Value of the attribute - */ - virtual const char* getAttribute(const char* name) const = 0; - - //PCDATA - /** - * @brief Set the PCDATA of the node. - * @param data [in] : Value of the PCDATA - */ - virtual void setPCData(const char* data) = 0; - - /** - * @brief Apppend a string to the current PCDATA of the node - * @param data [in] : Value of teh PCDATA to append - */ - virtual void appendPCData(const char* data) = 0; - - /** - * @brief Return the PCDATA of the node. - * @return Value of PCDATA - */ - virtual const char* getPCData() const = 0; - - //Child - /** - * @brief Add a node child of the - * @param node [in] : The Node that will became the new child - */ - virtual void addChild(IXMLNode* node) = 0; - - /** - * @brief Return the ith child of the node. - * @param index [in] : index of the child. - * @return The ith child of the node. - */ - virtual IXMLNode* getChild(const size_t index) const = 0; - - /** - * @brief Return the first child with the name name. - * @param name [in]] : Name of th child - * @return The first child of the node which name is name. - */ - virtual IXMLNode* getChildByName(const char* name) const = 0; - - /** - * @brief Return the amount of child the node has. - * @return Amount of child. - */ - virtual size_t getChildCount() const = 0; - - //XML generation - /** - * @brief Return a string which contains the XML of the node. The string is dynamically instantiate so - * it requires to be free. - * @param depth [in] : Amount of indentation - * @return XML string describing the node and its childs. - */ - virtual char* getXML(const size_t depth = 0) const = 0; - - protected: - virtual ~IXMLNode() {} - }; + virtual size_t getChildCount() const = 0; + //XML generation /** - * @brief Create a new node with the name name. The node is created dynamically and requires to be free. - * @param name [in] : Name of the node - * @return New node + * @brief Return a string which contains the XML of the node. The string is dynamically instantiate so + * it requires to be free. + * @param depth [in] : Amount of indentation + * @return XML string describing the node and its childs. */ - extern XML_API IXMLNode* createNode(const char* name); + virtual char* getXML(const size_t depth = 0) const = 0; + +protected: + virtual ~IXMLNode() {} +}; + +/** + * @brief Create a new node with the name name. The node is created dynamically and requires to be free. + * @param name [in] : Name of the node + * @return New node + */ +extern XML_API IXMLNode* createNode(const char* name); } // namespace XML diff --git a/modules/xml/include/xml/TReaderCallbackProxy.h b/modules/xml/include/xml/TReaderCallbackProxy.h index 440e336a8b22616af59e671d930fa2853a756651..c2d82b82d17f48f46056d661b1c4a98e66440fbb 100644 --- a/modules/xml/include/xml/TReaderCallbackProxy.h +++ b/modules/xml/include/xml/TReaderCallbackProxy.h @@ -2,60 +2,59 @@ #include "IReader.h" -namespace XML -{ +namespace XML { + +// ________________________________________________________________________________________________________________ +// - // ________________________________________________________________________________________________________________ - // +template <class TOwnerClass> +class TReaderCallbackProxy1 final : public IReaderCallback +{ +public: + TReaderCallbackProxy1(TOwnerClass& ownerObject, + void (TOwnerClass::*mfpOpenChild)(const char* name, const char** attributeName, const char** attributeValue, size_t nAttribute), + void (TOwnerClass::*mfpProcessChildData)(const char* data), void (TOwnerClass::*mfpCloseChild)()) + : m_ownerObject(ownerObject), m_mfpOpenChild(mfpOpenChild), m_mfpProcessChildData(mfpProcessChildData), m_mfpCloseChild(mfpCloseChild) { } - template <class TOwnerClass> - class TReaderCallbackProxy1 final : public IReaderCallback + void openChild(const char* name, const char** attributeName, const char** attributeValue, const size_t nAttribute) override { - public: - TReaderCallbackProxy1(TOwnerClass& ownerObject, - void (TOwnerClass::*mfpOpenChild)(const char* name, const char** attributeName, const char** attributeValue, size_t nAttribute), - void (TOwnerClass::*mfpProcessChildData)(const char* data), void (TOwnerClass::*mfpCloseChild)()) - : m_ownerObject(ownerObject), m_mfpOpenChild(mfpOpenChild), m_mfpProcessChildData(mfpProcessChildData), m_mfpCloseChild(mfpCloseChild) { } - - void openChild(const char* name, const char** attributeName, const char** attributeValue, const size_t nAttribute) override - { - if (m_mfpOpenChild) { m_ownerObject.m_mfpOpenChild(name, attributeName, attributeValue, nAttribute); } - } - - void processChildData(const char* data) override { if (m_mfpProcessChildData) { m_ownerObject.m_mfpProcessChildData(data); } } - void closeChild() override { if (m_mfpCloseChild) { m_ownerObject.m_mfpCloseChild(); } } - - protected: - TOwnerClass& m_ownerObject; - void (TOwnerClass::*m_mfpOpenChild)(const char* name, const char** attributeName, const char** attributeValue, size_t nAttribute); - void (TOwnerClass::*m_mfpProcessChildData)(const char* data); - void (TOwnerClass::*m_mfpCloseChild)(); - }; - - // ________________________________________________________________________________________________________________ - // - - template <class TOwnerClass, - void (TOwnerClass::*TMfpOpenChild)(const char* name, const char** attributeName, const char** attributeValue, size_t nAttribute), - void (TOwnerClass::*TMfpProcessChildData)(const char* data), void (TOwnerClass::*mfpCloseChild)()> - class TReaderCallbackProxy2 final : public IReaderCallback + if (m_mfpOpenChild) { m_ownerObject.m_mfpOpenChild(name, attributeName, attributeValue, nAttribute); } + } + + void processChildData(const char* data) override { if (m_mfpProcessChildData) { m_ownerObject.m_mfpProcessChildData(data); } } + void closeChild() override { if (m_mfpCloseChild) { m_ownerObject.m_mfpCloseChild(); } } + +protected: + TOwnerClass& m_ownerObject; + void (TOwnerClass::*m_mfpOpenChild)(const char* name, const char** attributeName, const char** attributeValue, size_t nAttribute); + void (TOwnerClass::*m_mfpProcessChildData)(const char* data); + void (TOwnerClass::*m_mfpCloseChild)(); +}; + +// ________________________________________________________________________________________________________________ +// + +template <class TOwnerClass, + void (TOwnerClass::*TMfpOpenChild)(const char* name, const char** attributeName, const char** attributeValue, size_t nAttribute), + void (TOwnerClass::*TMfpProcessChildData)(const char* data), void (TOwnerClass::*mfpCloseChild)()> +class TReaderCallbackProxy2 final : public IReaderCallback +{ +public: + TReaderCallbackProxy2(TOwnerClass ownerObject) + : m_ownerObject(ownerObject), m_mfpOpenChild(TMfpOpenChild), m_mfpProcessChildData(TMfpProcessChildData), m_mfpCloseChild(mfpCloseChild) { } + + void openChild(const char* name, const char** attributeName, const char** attributeValue, const size_t nAttribute) override { - public: - TReaderCallbackProxy2(TOwnerClass ownerObject) - : m_ownerObject(ownerObject), m_mfpOpenChild(TMfpOpenChild), m_mfpProcessChildData(TMfpProcessChildData), m_mfpCloseChild(mfpCloseChild) { } - - void openChild(const char* name, const char** attributeName, const char** attributeValue, const size_t nAttribute) override - { - if (TMfpOpenChild) { m_ownerObject.mfpOpenChild(name, attributeName, attributeValue, nAttribute); } - } - - void processChildData(const char* data) override { if (TMfpProcessChildData) { m_ownerObject.mfpProcessChildData(data); } } - void closeChild() override { if (mfpCloseChild) { m_ownerObject.mfpCloseChild(); } } - - protected: - TOwnerClass& m_ownerObject; - void (TOwnerClass::*m_mfpOpenChild)(const char* name, const char** attributeName, const char** attributeValue, size_t nAttribute); - void (TOwnerClass::*m_mfpProcessChildData)(const char* data); - void (TOwnerClass::*m_mfpCloseChild)(); - }; + if (TMfpOpenChild) { m_ownerObject.mfpOpenChild(name, attributeName, attributeValue, nAttribute); } + } + + void processChildData(const char* data) override { if (TMfpProcessChildData) { m_ownerObject.mfpProcessChildData(data); } } + void closeChild() override { if (mfpCloseChild) { m_ownerObject.mfpCloseChild(); } } + +protected: + TOwnerClass& m_ownerObject; + void (TOwnerClass::*m_mfpOpenChild)(const char* name, const char** attributeName, const char** attributeValue, size_t nAttribute); + void (TOwnerClass::*m_mfpProcessChildData)(const char* data); + void (TOwnerClass::*m_mfpCloseChild)(); +}; } // namespace XML diff --git a/modules/xml/include/xml/TWriterCallbackProxy.h b/modules/xml/include/xml/TWriterCallbackProxy.h index 781befa0959ccee1a956a0c4d6873e028deb61bd..ccda02a280b2279007c5819e5ce88d3bd258799e 100644 --- a/modules/xml/include/xml/TWriterCallbackProxy.h +++ b/modules/xml/include/xml/TWriterCallbackProxy.h @@ -2,42 +2,41 @@ #include "IWriter.h" -namespace XML -{ +namespace XML { - // ________________________________________________________________________________________________________________ - // +// ________________________________________________________________________________________________________________ +// - template <class TOwnerClass> - class TWriterCallbackProxy1 final : public IWriterCallback - { - public: - TWriterCallbackProxy1(TOwnerClass& ownerObject, void (TOwnerClass::*mfpWrite)(const char* str)) - : m_ownerObject(ownerObject), m_mfpWrite(mfpWrite) { } +template <class TOwnerClass> +class TWriterCallbackProxy1 final : public IWriterCallback +{ +public: + TWriterCallbackProxy1(TOwnerClass& ownerObject, void (TOwnerClass::*mfpWrite)(const char* str)) + : m_ownerObject(ownerObject), m_mfpWrite(mfpWrite) { } - void write(const char* str) override { if (m_mfpWrite) { m_ownerObject.m_mfpWrite(str); } } + void write(const char* str) override { if (m_mfpWrite) { m_ownerObject.m_mfpWrite(str); } } - protected: - TOwnerClass& m_ownerObject; - void (TOwnerClass::*m_mfpWrite)(const char* str); - }; +protected: + TOwnerClass& m_ownerObject; + void (TOwnerClass::*m_mfpWrite)(const char* str); +}; - // ________________________________________________________________________________________________________________ - // +// ________________________________________________________________________________________________________________ +// - template <class TOwnerClass, void (TOwnerClass::*TMfpWrite)(const char* str)> - class TWriterCallbackProxy2 final : public IWriterCallback - { - public: - TWriterCallbackProxy2(TOwnerClass ownerObject) : m_ownerObject(ownerObject), m_mfpWrite(TMfpWrite) { } +template <class TOwnerClass, void (TOwnerClass::*TMfpWrite)(const char* str)> +class TWriterCallbackProxy2 final : public IWriterCallback +{ +public: + TWriterCallbackProxy2(TOwnerClass ownerObject) : m_ownerObject(ownerObject), m_mfpWrite(TMfpWrite) { } - void write(const char* str) override { if (TMfpWrite) { m_ownerObject.mfpWrite(str); } } + void write(const char* str) override { if (TMfpWrite) { m_ownerObject.mfpWrite(str); } } - protected: - TOwnerClass& m_ownerObject; - void (TOwnerClass::*m_mfpWrite)(const char* str); - }; +protected: + TOwnerClass& m_ownerObject; + void (TOwnerClass::*m_mfpWrite)(const char* str); +}; - // ________________________________________________________________________________________________________________ - // -} // namespace XML +// ________________________________________________________________________________________________________________ +// +} // namespace XML diff --git a/modules/xml/include/xml/defines.h b/modules/xml/include/xml/defines.h index 665c6260e15175b3cfb08d61886bd0c5f0170907..1c6ed9830f6d3527651aaf1f48fde7eb35578e61 100644 --- a/modules/xml/include/xml/defines.h +++ b/modules/xml/include/xml/defines.h @@ -3,23 +3,23 @@ #include <ov_common_defines.h> #if defined XML_Shared -#if defined TARGET_OS_Windows -#define XML_API_Export __declspec(dllexport) -#define XML_API_Import __declspec(dllimport) -#elif defined TARGET_OS_Linux - #define XML_API_Export __attribute__((visibility("default"))) - #define XML_API_Import __attribute__((visibility("default"))) +# if defined TARGET_OS_Windows +# define XML_API_Export __declspec(dllexport) +# define XML_API_Import __declspec(dllimport) +# elif defined TARGET_OS_Linux +# define XML_API_Export __attribute__((visibility("default"))) +# define XML_API_Import __attribute__((visibility("default"))) +# else +# define XML_API_Export +# define XML_API_Import +# endif #else - #define XML_API_Export - #define XML_API_Import -#endif -#else -#define XML_API_Export -#define XML_API_Import +# define XML_API_Export +# define XML_API_Import #endif #if defined XML_Exports -#define XML_API XML_API_Export +# define XML_API XML_API_Export #else - #define XML_API XML_API_Import +# define XML_API XML_API_Import #endif diff --git a/modules/xml/src/IReader.cpp b/modules/xml/src/IReader.cpp index f4fe6b81cb82c189a44b4f5cd2833b268dcbd449..a6a1deae655c49883776f44582462ccd01f499b6 100644 --- a/modules/xml/src/IReader.cpp +++ b/modules/xml/src/IReader.cpp @@ -7,30 +7,29 @@ using namespace XML; using namespace std; -namespace XML +namespace XML { +class CReader final : public IReader { - class CReader final : public IReader - { - public: - explicit CReader(IReaderCallback& callback); - bool processData(const void* buffer, const size_t size) override; - void release() override; - - void openChild(const char* name, const char** sAttributeName, const char** sAttributeValue, const size_t nAttribute); - void processChildData(const char* data); - void closeChild(); - - protected: - - IReaderCallback& m_callback; - XML_Parser m_pXMLParser; - std::string m_data; - }; - - static void XMLCALL ExpatXMLStart(void* data, const char* element, const char** attribute); - static void XMLCALL ExpatXMLEnd(void* data, const char* element); - static void XMLCALL ExpatXMLData(void* data, const char* value, int length); -} // namespace XML +public: + explicit CReader(IReaderCallback& callback); + bool processData(const void* buffer, const size_t size) override; + void release() override; + + void openChild(const char* name, const char** sAttributeName, const char** sAttributeValue, const size_t nAttribute); + void processChildData(const char* data); + void closeChild(); + +protected: + + IReaderCallback& m_callback; + XML_Parser m_pXMLParser; + std::string m_data; +}; + +static void XMLCALL ExpatXMLStart(void* data, const char* element, const char** attribute); +static void XMLCALL ExpatXMLEnd(void* data, const char* element); +static void XMLCALL ExpatXMLData(void* data, const char* value, int length); +} // namespace XML CReader::CReader(IReaderCallback& callback) : m_callback(callback), m_pXMLParser(nullptr) { diff --git a/modules/xml/src/IWriter.cpp b/modules/xml/src/IWriter.cpp index 4f258fcc074a9c26a0f4ffefdb930308c758989d..5a25198e2925d0805147709a5dcef22da6c0a81f 100644 --- a/modules/xml/src/IWriter.cpp +++ b/modules/xml/src/IWriter.cpp @@ -6,29 +6,28 @@ using namespace XML; using namespace std; -namespace XML +namespace XML { +class CWriter final : public IWriter { - class CWriter final : public IWriter - { - public: - explicit CWriter(IWriterCallback& callback); - bool openChild(const char* name) override; - bool setChildData(const char* data) override; - bool setAttribute(const char* name, const char* value) override; - bool closeChild() override; - void release() override; - - private: - static void sanitize(string& str, bool escapeQuotes = true); - - protected: - IWriterCallback& m_callback; - stack<string> m_nodes; - bool m_hasChild = false; - bool m_hasData = false; - bool m_hasClosedOpeningNode = true; - }; -} // namespace XML +public: + explicit CWriter(IWriterCallback& callback); + bool openChild(const char* name) override; + bool setChildData(const char* data) override; + bool setAttribute(const char* name, const char* value) override; + bool closeChild() override; + void release() override; + +private: + static void sanitize(string& str, bool escapeQuotes = true); + +protected: + IWriterCallback& m_callback; + stack<string> m_nodes; + bool m_hasChild = false; + bool m_hasData = false; + bool m_hasClosedOpeningNode = true; +}; +} // namespace XML CWriter::CWriter(IWriterCallback& callback) : m_callback(callback) {} diff --git a/modules/xml/src/IXMLHandler.cpp b/modules/xml/src/IXMLHandler.cpp index 00004b2270a7faf83d771743cbb823c87c5f39cd..33e07ab67b7f18ebb8c193a717f76c502fb9780c 100644 --- a/modules/xml/src/IXMLHandler.cpp +++ b/modules/xml/src/IXMLHandler.cpp @@ -9,46 +9,45 @@ using namespace std; -namespace XML +namespace XML { +class IXMLHandlerImpl final : public IXMLHandler { - class IXMLHandlerImpl final : public IXMLHandler - { - public: - void release() override; - IXMLHandlerImpl(); +public: + void release() override; + IXMLHandlerImpl(); - //Parsing - IXMLNode* parseFile(const char* sPath) override; - IXMLNode* parseString(const char* str, const size_t& size) override; + //Parsing + IXMLNode* parseFile(const char* sPath) override; + IXMLNode* parseString(const char* str, const size_t& size) override; - //XML extraction - bool writeXMLInFile(const IXMLNode& rNode, const char* sPath) const override; + //XML extraction + bool writeXMLInFile(const IXMLNode& rNode, const char* sPath) const override; - //Error handling - std::string getLastErrorString() const override; + //Error handling + std::string getLastErrorString() const override; - //Internal function for parsing - void openChild(const char* name, const char** sAttributeName, const char** sAttributeValue, const size_t nAttribute); - void processChildData(const char* data); - void closeChild(); + //Internal function for parsing + void openChild(const char* name, const char** sAttributeName, const char** sAttributeValue, const size_t nAttribute); + void processChildData(const char* data); + void closeChild(); - std::stringstream& getErrorStringStream() const; + std::stringstream& getErrorStringStream() const; - protected: - ~IXMLHandlerImpl() override; +protected: + ~IXMLHandlerImpl() override; - private: - XML_Parser m_pXMLParser; - std::stack<IXMLNode *> m_oNodeStack; - IXMLNode* m_pRootNode; - mutable std::stringstream m_ssErrorStringStream; - }; +private: + XML_Parser m_pXMLParser; + std::stack<IXMLNode*> m_oNodeStack; + IXMLNode* m_pRootNode; + mutable std::stringstream m_ssErrorStringStream; +}; - //Callback for expat - static void XMLCALL ExpatXMLStart(void* pData, const char* element, const char** attribute); - static void XMLCALL ExpatXMLEnd(void* data, const char* element); - static void XMLCALL ExpatXMLData(void* data, const char* value, int length); -} // namespace XML +//Callback for expat +static void XMLCALL ExpatXMLStart(void* pData, const char* element, const char** attribute); +static void XMLCALL ExpatXMLEnd(void* data, const char* element); +static void XMLCALL ExpatXMLData(void* data, const char* value, int length); +} // namespace XML using namespace std; using namespace XML; @@ -68,8 +67,7 @@ IXMLHandlerImpl::~IXMLHandlerImpl() void IXMLHandlerImpl::release() { delete this; } -IXMLHandlerImpl::IXMLHandlerImpl(): m_pXMLParser(nullptr), - m_pRootNode(nullptr) +IXMLHandlerImpl::IXMLHandlerImpl(): m_pXMLParser(nullptr), m_pRootNode(nullptr) { m_pXMLParser = XML_ParserCreate(nullptr); XML_SetElementHandler(m_pXMLParser, ExpatXMLStart, ExpatXMLEnd); @@ -83,7 +81,6 @@ IXMLNode* IXMLHandlerImpl::parseFile(const char* sPath) FS::Files::openIFStream(file, sPath, ios::binary); if (file.is_open()) { - //Compute size file.seekg(0, ios::end); const size_t fileLen = size_t(file.tellg()); diff --git a/modules/xml/src/IXMLNode.cpp b/modules/xml/src/IXMLNode.cpp index 814d647f6d65da8eee8beec82392ae61e07975d9..f00fb94d708d71d91c57f8886a68b2db84fc9575 100644 --- a/modules/xml/src/IXMLNode.cpp +++ b/modules/xml/src/IXMLNode.cpp @@ -13,48 +13,47 @@ using namespace std; -namespace XML +namespace XML { +class IXMLNodeImpl final : public IXMLNode { - class IXMLNodeImpl final : public IXMLNode - { - public: - explicit IXMLNodeImpl(const char* name) : m_name(name) {} - const char* getName() const override { return m_name.c_str(); } - void release() override { delete this; } - - //Attribute - bool addAttribute(const char* name, const char* value) override; - bool hasAttribute(const char* name) const override { return m_attibutes.count(name) != 0; } - const char* getAttribute(const char* name) const override; - - //PCDATA - void setPCData(const char* data) override; - void appendPCData(const char* data) override; - const char* getPCData() const override { return m_pcData.c_str(); } - - //Child - void addChild(IXMLNode* node) override { m_nodes.push_back(node); } - IXMLNode* getChild(const size_t index) const override { return m_nodes[index]; } - IXMLNode* getChildByName(const char* name) const override; - size_t getChildCount() const override; - - //XMl generation - char* getXML(const size_t depth = 0) const override; - - protected: - ~IXMLNodeImpl() override { for (size_t i = 0; i < getChildCount(); ++i) { getChild(i)->release(); } } - - private: - static std::string sanitize(const std::string& str); - static void applyIndentation(std::string& str, const size_t depth); - - - std::vector<IXMLNode *> m_nodes; - std::map<std::string, std::string> m_attibutes; - std::string m_name = ""; - std::string m_pcData = ""; - bool m_hasPCData = false; - }; +public: + explicit IXMLNodeImpl(const char* name) : m_name(name) {} + const char* getName() const override { return m_name.c_str(); } + void release() override { delete this; } + + //Attribute + bool addAttribute(const char* name, const char* value) override; + bool hasAttribute(const char* name) const override { return m_attibutes.count(name) != 0; } + const char* getAttribute(const char* name) const override; + + //PCDATA + void setPCData(const char* data) override; + void appendPCData(const char* data) override; + const char* getPCData() const override { return m_pcData.c_str(); } + + //Child + void addChild(IXMLNode* node) override { m_nodes.push_back(node); } + IXMLNode* getChild(const size_t index) const override { return m_nodes[index]; } + IXMLNode* getChildByName(const char* name) const override; + size_t getChildCount() const override; + + //XMl generation + char* getXML(const size_t depth = 0) const override; + +protected: + ~IXMLNodeImpl() override { for (size_t i = 0; i < getChildCount(); ++i) { getChild(i)->release(); } } + +private: + static std::string sanitize(const std::string& str); + static void applyIndentation(std::string& str, const size_t depth); + + + std::vector<IXMLNode*> m_nodes; + std::map<std::string, std::string> m_attibutes; + std::string m_name = ""; + std::string m_pcData = ""; + bool m_hasPCData = false; +}; } // namespace XML using namespace std; @@ -80,7 +79,7 @@ const char* IXMLNodeImpl::getAttribute(const char* name) const void IXMLNodeImpl::setPCData(const char* data) { - m_pcData = data; + m_pcData = data; m_hasPCData = true; } @@ -151,7 +150,7 @@ char* IXMLNodeImpl::getXML(const size_t depth) const for (auto it = m_nodes.begin(); it != m_nodes.end(); ++it) { - IXMLNode* node = static_cast<IXMLNode *>(*it); + IXMLNode* node = static_cast<IXMLNode*>(*it); str += string("\n") + node->getXML(depth + 1); } diff --git a/openvibe/CMakeLists.txt b/openvibe/CMakeLists.txt index 7038862e41a5c0460cccea18d1355c3436e83109..71b829ad519592a0ce8f05a57b3079b400957458 100644 --- a/openvibe/CMakeLists.txt +++ b/openvibe/CMakeLists.txt @@ -14,6 +14,7 @@ ADD_LIBRARY(${PROJECT_NAME} SHARED ${SRC_FILES}) SET_TARGET_PROPERTIES(${PROJECT_NAME} PROPERTIES VERSION ${PROJECT_VERSION} SOVERSION ${PROJECT_VERSION_MAJOR} + FOLDER ${KERNEL_FOLDER} COMPILE_FLAGS "-DOV_Exports -DOV_Shared") INCLUDE("FindOpenViBECommon") @@ -50,9 +51,7 @@ ENDIF(UNIX) # --------------------------------- # Target macros -# Defines target operating system -# Defines target architecture -# Defines target compiler +# Defines target operating system, architecture and compiler # --------------------------------- SET_BUILD_PLATFORM() diff --git a/openvibe/include/openvibe/CTime.hpp b/openvibe/include/openvibe/CTime.hpp index 3b6194087ddeea90487aee293548159f045a2232..d1472b93f41bdfc3f53e6a8da916b5b1f1be8557 100644 --- a/openvibe/include/openvibe/CTime.hpp +++ b/openvibe/include/openvibe/CTime.hpp @@ -191,4 +191,4 @@ public: protected: uint64_t m_time = 0; ///< the 64 bit time value }; -} // namespace OpenViBE +} // namespace OpenViBE diff --git a/openvibe/include/openvibe/kernel/algorithm/ovIAlgorithmContext.h b/openvibe/include/openvibe/kernel/algorithm/ovIAlgorithmContext.h index df5baadcc9de76ccdd4587d52f96719ebd4bdb40..b4fda09125c27770fdfa9c04604f6fe1e389ec40 100644 --- a/openvibe/include/openvibe/kernel/algorithm/ovIAlgorithmContext.h +++ b/openvibe/include/openvibe/kernel/algorithm/ovIAlgorithmContext.h @@ -2,129 +2,127 @@ #include "../ovIKernelObject.h" -namespace OpenViBE -{ - namespace Kernel - { - class IParameter; +namespace OpenViBE { +namespace Kernel { +class IParameter; - /** - * \class IAlgorithmContext - * \author Yann Renard (INRIA/IRISA) - * \date 2007-11-06 - * \brief Exectution context for algorithm objects - * \ingroup Group_Algorithm - * \ingroup Group_Kernel - * \ingroup Group_Extend - * \sa Plugins::IAlgorithm - */ - class OV_API IAlgorithmContext : public IKernelObject - { - public: +/** + * \class IAlgorithmContext + * \author Yann Renard (INRIA/IRISA) + * \date 2007-11-06 + * \brief Exectution context for algorithm objects + * \ingroup Group_Algorithm + * \ingroup Group_Kernel + * \ingroup Group_Extend + * \sa Plugins::IAlgorithm + */ +class OV_API IAlgorithmContext : public IKernelObject +{ +public: - /** - * \brief Gets a reference on the current configuration manager - * \return a reference on the configuration manager - * - * \warning The algorithm should not use this reference after it - * has finished its work, it could be deprecated. - */ - virtual IConfigurationManager& getConfigurationManager() const = 0; - /** - * \brief Gets a reference on the current algorithm manager - * \return a reference on the algorithm manager - * - * \warning The algorithm should not use this reference after it - * has finished its work, it could be deprecated. - */ - virtual IAlgorithmManager& getAlgorithmManager() const = 0; - /** - * \brief Gets a reference on the current log manager - * \return a reference on the current log manager - * - * \warning The algorithm should not use this reference after it - * has finished its work, it could be deprecated. - */ - virtual ILogManager& getLogManager() const = 0; - /** - * \brief Gets a reference on the current error manager - * \return a reference on the current error manager - * - * \warning The algorithm should not use this reference after it - * has finished its work, it could be deprecated. - */ - virtual IErrorManager& getErrorManager() const = 0; - /** - * \brief Gets a reference on the current type manager - * \return a reference on the current type manager - */ - virtual ITypeManager& getTypeManager() const = 0; + /** + * \brief Gets a reference on the current configuration manager + * \return a reference on the configuration manager + * + * \warning The algorithm should not use this reference after it + * has finished its work, it could be deprecated. + */ + virtual IConfigurationManager& getConfigurationManager() const = 0; + /** + * \brief Gets a reference on the current algorithm manager + * \return a reference on the algorithm manager + * + * \warning The algorithm should not use this reference after it + * has finished its work, it could be deprecated. + */ + virtual IAlgorithmManager& getAlgorithmManager() const = 0; + /** + * \brief Gets a reference on the current log manager + * \return a reference on the current log manager + * + * \warning The algorithm should not use this reference after it + * has finished its work, it could be deprecated. + */ + virtual ILogManager& getLogManager() const = 0; + /** + * \brief Gets a reference on the current error manager + * \return a reference on the current error manager + * + * \warning The algorithm should not use this reference after it + * has finished its work, it could be deprecated. + */ + virtual IErrorManager& getErrorManager() const = 0; + /** + * \brief Gets a reference on the current type manager + * \return a reference on the current type manager + */ + virtual ITypeManager& getTypeManager() const = 0; - /** \name Input parameters */ - //@{ + /** \name Input parameters */ + //@{ - /** - * \brief Gets next input parameter identifier given the previous input parameter - * \param prevInputParameterID [in] : the previous input parameter - * \return the next input parameter identifier if existing. - * \return \c OV_UndefinedIdentifier if the previous was the last input parameter identifier. - * \note Passing \c OV_UndefinedIdentifier as \c prevInputParameterID will - * cause this function to return the firs input parameter identifier. - */ - virtual CIdentifier getNextInputParameterIdentifier(const CIdentifier& prevInputParameterID) const = 0; - /** - * \brief Gets the parameter details of a specific input parameter - * \param id [in] : the identifier of the parameter which details should be returned - * \return the parameter pointer that corresponds to the provided identifier. - * \return \c NULL in case of error. - */ - virtual IParameter* getInputParameter(const CIdentifier& id) = 0; + /** + * \brief Gets next input parameter identifier given the previous input parameter + * \param prevInputParameterID [in] : the previous input parameter + * \return the next input parameter identifier if existing. + * \return \c OV_UndefinedIdentifier if the previous was the last input parameter identifier. + * \note Passing \c OV_UndefinedIdentifier as \c prevInputParameterID will + * cause this function to return the firs input parameter identifier. + */ + virtual CIdentifier getNextInputParameterIdentifier(const CIdentifier& prevInputParameterID) const = 0; + /** + * \brief Gets the parameter details of a specific input parameter + * \param id [in] : the identifier of the parameter which details should be returned + * \return the parameter pointer that corresponds to the provided identifier. + * \return \c NULL in case of error. + */ + virtual IParameter* getInputParameter(const CIdentifier& id) = 0; - //@} - /** \name Output parameters */ - //@{ + //@} + /** \name Output parameters */ + //@{ - /** - * \brief Gets next output parameter identifier given the previous output parameter - * \param prevOutputParameterID [in] : the previous output parameter - * \return the next output parameter identifier if existing. - * \return \c OV_UndefinedIdentifier if the previous was the last output parameter identifier. - * \note Passing \c OV_UndefinedIdentifier as \c prevOutputParameterID will - * cause this function to return the firs output parameter identifier. - */ - virtual CIdentifier getNextOutputParameterIdentifier(const CIdentifier& prevOutputParameterID) const = 0; - /** - * \brief Gets the parameter details of a specific output parameter - * \param id [in] : the identifier of the parameter which details should be returned - * \return the parameter pointer that corresponds to the provided identifier. - * \return \c NULL in case of error. - */ - virtual IParameter* getOutputParameter(const CIdentifier& id) = 0; + /** + * \brief Gets next output parameter identifier given the previous output parameter + * \param prevOutputParameterID [in] : the previous output parameter + * \return the next output parameter identifier if existing. + * \return \c OV_UndefinedIdentifier if the previous was the last output parameter identifier. + * \note Passing \c OV_UndefinedIdentifier as \c prevOutputParameterID will + * cause this function to return the firs output parameter identifier. + */ + virtual CIdentifier getNextOutputParameterIdentifier(const CIdentifier& prevOutputParameterID) const = 0; + /** + * \brief Gets the parameter details of a specific output parameter + * \param id [in] : the identifier of the parameter which details should be returned + * \return the parameter pointer that corresponds to the provided identifier. + * \return \c NULL in case of error. + */ + virtual IParameter* getOutputParameter(const CIdentifier& id) = 0; - //@} - /** \name Trigger management */ - //@{ + //@} + /** \name Trigger management */ + //@{ - /** - * \brief Tests whether an input trigger is activated or not. - * \param id [in] : the identifier of the input trigger which activation status should be returned - * \return \e true if the provided trigger is currently active. - * \return \e false if the provided trigger is not currently active or does not exist. - */ - virtual bool isInputTriggerActive(const CIdentifier& id) const = 0; - /** - * \brief Activates an output trigger before calling the processing function. - * \param id [in] : the identifier of the output to activate - * \param state [in]: the new trigger state this output trigger should take - * (\e true for active, \e false for inactive) - * \return \e true in case the state was correctly changed. - * \return \e false in case the state was not changed or the provided trigger identifier does not exist. - */ - virtual bool activateOutputTrigger(const CIdentifier& id, const bool state) = 0; + /** + * \brief Tests whether an input trigger is activated or not. + * \param id [in] : the identifier of the input trigger which activation status should be returned + * \return \e true if the provided trigger is currently active. + * \return \e false if the provided trigger is not currently active or does not exist. + */ + virtual bool isInputTriggerActive(const CIdentifier& id) const = 0; + /** + * \brief Activates an output trigger before calling the processing function. + * \param id [in] : the identifier of the output to activate + * \param state [in]: the new trigger state this output trigger should take + * (\e true for active, \e false for inactive) + * \return \e true in case the state was correctly changed. + * \return \e false in case the state was not changed or the provided trigger identifier does not exist. + */ + virtual bool activateOutputTrigger(const CIdentifier& id, const bool state) = 0; - //@} + //@} - _IsDerivedFromClass_(IKernelObject, OV_ClassId_Kernel_Algorithm_AlgorithmContext) - }; - } // namespace Kernel -} // namespace OpenViBE + _IsDerivedFromClass_(IKernelObject, OV_ClassId_Kernel_Algorithm_AlgorithmContext) +}; +} // namespace Kernel +} // namespace OpenViBE diff --git a/openvibe/include/openvibe/kernel/algorithm/ovIAlgorithmManager.h b/openvibe/include/openvibe/kernel/algorithm/ovIAlgorithmManager.h index 3292aba970390f2b3b73b508183ca82824a32d41..cf76c05cfab13980fd43d001e142f834728c342d 100644 --- a/openvibe/include/openvibe/kernel/algorithm/ovIAlgorithmManager.h +++ b/openvibe/include/openvibe/kernel/algorithm/ovIAlgorithmManager.h @@ -2,81 +2,78 @@ #include "../ovIKernelObject.h" -namespace OpenViBE -{ - namespace Plugins - { - class IAlgorithmDesc; - } // namespace Plugins +namespace OpenViBE { +namespace Plugins { +class IAlgorithmDesc; +} // namespace Plugins - namespace Kernel - { - class IAlgorithmProxy; +namespace Kernel { +class IAlgorithmProxy; - /** - * \class IAlgorithmManager - * \author Yann Renard (INRIA/IRISA) - * \date 2007-11-06 - * \brief Manager for all kind of plugin algorithms - * \ingroup Group_Algorithm - * \ingroup Group_Kernel - * \sa Plugins::IAlgorithm - */ - class OV_API IAlgorithmManager : public IKernelObject - { - public: +/** + * \class IAlgorithmManager + * \author Yann Renard (INRIA/IRISA) + * \date 2007-11-06 + * \brief Manager for all kind of plugin algorithms + * \ingroup Group_Algorithm + * \ingroup Group_Kernel + * \sa Plugins::IAlgorithm + */ +class OV_API IAlgorithmManager : public IKernelObject +{ +public: - /** - * \brief Creates a new algorithm - * \param algorithmClassID [out] : the class identifier of - * the newly created algorithm - * \return \e true in case of success. - * \return \e OV_UndefinedIdentifier in case of error. - */ - virtual CIdentifier createAlgorithm(const CIdentifier& algorithmClassID) = 0; - /** - * \brief Creates a new algorithm - * \param algorithmDesc [in] : the algorithm descriptor of - * the algorithm to create - * \return \e identifier of the created algorithm - * \return \e OV_UndefinedIdentifier - */ - virtual CIdentifier createAlgorithm(const Plugins::IAlgorithmDesc& algorithmDesc) = 0; + /** + * \brief Creates a new algorithm + * \param algorithmClassID [out] : the class identifier of + * the newly created algorithm + * \return \e true in case of success. + * \return \e OV_UndefinedIdentifier in case of error. + */ + virtual CIdentifier createAlgorithm(const CIdentifier& algorithmClassID) = 0; + /** + * \brief Creates a new algorithm + * \param algorithmDesc [in] : the algorithm descriptor of + * the algorithm to create + * \return \e identifier of the created algorithm + * \return \e OV_UndefinedIdentifier + */ + virtual CIdentifier createAlgorithm(const Plugins::IAlgorithmDesc& algorithmDesc) = 0; - /** - * \brief Releases an existing algorithm - * \param id [in] : the existing algorithm identifier - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool releaseAlgorithm(const CIdentifier& id) = 0; - /** - * \brief Releases an existing algorithm - * \param algorithm [in] : the existing algorithm - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool releaseAlgorithm(IAlgorithmProxy& algorithm) = 0; - /** - * \brief Gets details on a specific algorithm - * \param id [in] : the algorithm identifier which details should be returned - * \return the corresponding algorithm reference. - * \warning Calling this function with a bad identifier causes a crash - */ - virtual IAlgorithmProxy& getAlgorithm(const CIdentifier& id) = 0; - /** - * \brief Gets next algorithm identifier - * \param previousID [in] : The identifier - * for the preceeding algorithm - * \return The identifier of the next algorithm in case of success. - * \return \c OV_UndefinedIdentifier on error. - * \note Giving \c OV_UndefinedIdentifier as \c previousID - * will cause this function to return the first algorithm - * identifier. - */ - virtual CIdentifier getNextAlgorithmIdentifier(const CIdentifier& previousID) const = 0; + /** + * \brief Releases an existing algorithm + * \param id [in] : the existing algorithm identifier + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool releaseAlgorithm(const CIdentifier& id) = 0; + /** + * \brief Releases an existing algorithm + * \param algorithm [in] : the existing algorithm + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool releaseAlgorithm(IAlgorithmProxy& algorithm) = 0; + /** + * \brief Gets details on a specific algorithm + * \param id [in] : the algorithm identifier which details should be returned + * \return the corresponding algorithm reference. + * \warning Calling this function with a bad identifier causes a crash + */ + virtual IAlgorithmProxy& getAlgorithm(const CIdentifier& id) = 0; + /** + * \brief Gets next algorithm identifier + * \param previousID [in] : The identifier + * for the preceeding algorithm + * \return The identifier of the next algorithm in case of success. + * \return \c OV_UndefinedIdentifier on error. + * \note Giving \c OV_UndefinedIdentifier as \c previousID + * will cause this function to return the first algorithm + * identifier. + */ + virtual CIdentifier getNextAlgorithmIdentifier(const CIdentifier& previousID) const = 0; - _IsDerivedFromClass_(IKernelObject, OV_ClassId_Kernel_Algorithm_AlgorithmManager) - }; - } // namespace Kernel -} // namespace OpenViBE + _IsDerivedFromClass_(IKernelObject, OV_ClassId_Kernel_Algorithm_AlgorithmManager) +}; +} // namespace Kernel +} // namespace OpenViBE diff --git a/openvibe/include/openvibe/kernel/algorithm/ovIAlgorithmProto.h b/openvibe/include/openvibe/kernel/algorithm/ovIAlgorithmProto.h index 8a4feecf39711d4a21a049d258db4358546c05cc..b941e9739f9eba1fd9301846cb99808cfe1d8571 100644 --- a/openvibe/include/openvibe/kernel/algorithm/ovIAlgorithmProto.h +++ b/openvibe/include/openvibe/kernel/algorithm/ovIAlgorithmProto.h @@ -2,67 +2,65 @@ #include "../ovIConfigurable.h" -namespace OpenViBE +namespace OpenViBE { +namespace Kernel { +/** + * \class IAlgorithmProto + * \brief Prototype interface for algorithm + * \author Yann Renard (INRIA/IRISA) + * \date 2007-11-21 + * \ingroup Group_Algorithm + * \ingroup Group_Kernel + * \ingroup Group_Extend + * \sa Plugins::IAlgorithm + * \sa Plugins::IAlgorithmDesc + */ +class OV_API IAlgorithmProto : public IKernelObject { - namespace Kernel - { - /** - * \class IAlgorithmProto - * \brief Prototype interface for algorithm - * \author Yann Renard (INRIA/IRISA) - * \date 2007-11-21 - * \ingroup Group_Algorithm - * \ingroup Group_Kernel - * \ingroup Group_Extend - * \sa Plugins::IAlgorithm - * \sa Plugins::IAlgorithmDesc - */ - class OV_API IAlgorithmProto : public IKernelObject - { - public: +public: - /** - * \brief Adds an input parameter - * \param id [in] : the identifier for this parameter - * \param name [in] : the name for this parameter - * \param type [in] : the type for this parameter - * \param subTypeID [in] : the optional sub type of this parameter (e.g. for enumerations) - * \return \e true in case of success. - * \return \e false in case of error. - * \sa IParameter - */ - virtual bool addInputParameter(const CIdentifier& id, const CString& name, EParameterType type, - const CIdentifier& subTypeID = OV_UndefinedIdentifier) = 0; - /** - * \brief Adds an output parameter - * \param id [in] : the identifier for this parameter - * \param name [in] : the name for this parameter - * \param type [in] : the type for this parameter - * \param subTypeID [in] : the optional sub type of this parameter (e.g. for enumerations) - * \return \e true in case of success. - * \return \e false in case of error. - * \sa IParameter - */ - virtual bool addOutputParameter(const CIdentifier& id, const CString& name, EParameterType type, - const CIdentifier& subTypeID = OV_UndefinedIdentifier) = 0; - /** - * \brief Adds an input trigger - * \param id [in] : the identifier for this trigger - * \param name [in] : the name for this trigger - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool addInputTrigger(const CIdentifier& id, const CString& name) = 0; - /** - * \brief Adds an output trigger - * \param id [in] : the identifier for this trigger - * \param name [in] : the name for this trigger - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool addOutputTrigger(const CIdentifier& id, const CString& name) = 0; + /** + * \brief Adds an input parameter + * \param id [in] : the identifier for this parameter + * \param name [in] : the name for this parameter + * \param type [in] : the type for this parameter + * \param subTypeID [in] : the optional sub type of this parameter (e.g. for enumerations) + * \return \e true in case of success. + * \return \e false in case of error. + * \sa IParameter + */ + virtual bool addInputParameter(const CIdentifier& id, const CString& name, EParameterType type, + const CIdentifier& subTypeID = OV_UndefinedIdentifier) = 0; + /** + * \brief Adds an output parameter + * \param id [in] : the identifier for this parameter + * \param name [in] : the name for this parameter + * \param type [in] : the type for this parameter + * \param subTypeID [in] : the optional sub type of this parameter (e.g. for enumerations) + * \return \e true in case of success. + * \return \e false in case of error. + * \sa IParameter + */ + virtual bool addOutputParameter(const CIdentifier& id, const CString& name, EParameterType type, + const CIdentifier& subTypeID = OV_UndefinedIdentifier) = 0; + /** + * \brief Adds an input trigger + * \param id [in] : the identifier for this trigger + * \param name [in] : the name for this trigger + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool addInputTrigger(const CIdentifier& id, const CString& name) = 0; + /** + * \brief Adds an output trigger + * \param id [in] : the identifier for this trigger + * \param name [in] : the name for this trigger + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool addOutputTrigger(const CIdentifier& id, const CString& name) = 0; - _IsDerivedFromClass_(IKernelObject, OV_ClassId_Kernel_Algorithm_AlgorithmProto) - }; - } // namespace Kernel -} // namespace OpenViBE + _IsDerivedFromClass_(IKernelObject, OV_ClassId_Kernel_Algorithm_AlgorithmProto) +}; +} // namespace Kernel +} // namespace OpenViBE diff --git a/openvibe/include/openvibe/kernel/algorithm/ovIAlgorithmProxy.h b/openvibe/include/openvibe/kernel/algorithm/ovIAlgorithmProxy.h index a74299e72a8c65874118e5555528b137e95c1cc9..4738f8c1d35753ba0c4b8d48e39e3200745fe539 100644 --- a/openvibe/include/openvibe/kernel/algorithm/ovIAlgorithmProxy.h +++ b/openvibe/include/openvibe/kernel/algorithm/ovIAlgorithmProxy.h @@ -2,181 +2,179 @@ #include "../ovIKernelObject.h" -namespace OpenViBE +namespace OpenViBE { +namespace Kernel { +class IParameter; + +/** + * \class IAlgorithmProxy + * \brief Application interface to an algorithm plugin + * \author Yann Renard (INRIA/IRISA) + * \date 2007-11-21 + * \ingroup Group_Algorithm + * \ingroup Group_Kernel + * \sa Plugins::IAlgorithm + * + * This class is an easier to user interface to an IAlgorihtm instanciated + * object. Its purpose is to automatically handle input / output trigger + * activation and to help in calling processing methods. + */ +class OV_API IAlgorithmProxy : public IKernelObject { - namespace Kernel - { - class IParameter; - - /** - * \class IAlgorithmProxy - * \brief Application interface to an algorithm plugin - * \author Yann Renard (INRIA/IRISA) - * \date 2007-11-21 - * \ingroup Group_Algorithm - * \ingroup Group_Kernel - * \sa Plugins::IAlgorithm - * - * This class is an easier to user interface to an IAlgorihtm instanciated - * object. Its purpose is to automatically handle input / output trigger - * activation and to help in calling processing methods. - */ - class OV_API IAlgorithmProxy : public IKernelObject - { - public: - - /** \name Input parameters */ - //@{ - - /** - * \brief Gets next input parameter identifier given the previous input parameter - * \param previousID [in] : the previous input parameter - * \return the next input parameter identifier if existing. - * \return \c OV_UndefinedIdentifier if the previous was the last input parameter identifier. - * \note Passing \c OV_UndefinedIdentifier as \c previousID will - * cause this function to return the first input parameter identifier. - */ - virtual CIdentifier getNextInputParameterIdentifier(const CIdentifier& previousID) const = 0; - /** - * \brief Gets the name of a specific input parameter - * \param id [in] : the identifier of the parameter which name should be returned - * \return The name of the specified input parameter on success - * \return En empty string on error - */ - virtual CString getInputParameterName(const CIdentifier& id) const = 0; - /** - * \brief Gets the parameter details of a specific input parameter - * \param id [in] : the identifier of the parameter which details should be returned - * \return the parameter pointer that corresponds to the provided id. - * \return \c NULL in case of error. - */ - virtual IParameter* getInputParameter(const CIdentifier& id) = 0; - - //@} - /** \name Output parameters */ - //@{ - - /** - * \brief Gets next output parameter identifier given the previous output parameter - * \param previousID [in] : the previous output parameter - * \return the next output parameter identifier if existing. - * \return \c OV_UndefinedIdentifier if the previous was the last output parameter identifier. - * \note Passing \c OV_UndefinedIdentifier as \c previousID will - * cause this function to return the first output parameter identifier. - */ - virtual CIdentifier getNextOutputParameterIdentifier(const CIdentifier& previousID) const = 0; - /** - * \brief Gets the name of a specific input parameter - * \param id [in] : the identifier of the parameter which name should be returned - * \return The name of the specified input parameter on success - * \return En empty string on error - */ - virtual CString getOutputParameterName(const CIdentifier& id) const = 0; - /** - * \brief Gets the parameter details of a specific output parameter - * \param id [in] : the identifier of the parameter which details should be returned - * \return the parameter pointer that corresponds to the provided id. - * \return \c NULL in case of error. - */ - virtual IParameter* getOutputParameter(const CIdentifier& id) = 0; - - //@} - /** \name Trigger management */ - //@{ - - /** - * \brief Gets next output trigger identifier given the previous output trigger - * \param previousID [in] : the previous output trigger - * \return the next output trigger identifier if existing. - * \return \c OV_UndefinedIdentifier if the previous was the last output trigger identifier. - * \note Passing \c OV_UndefinedIdentifier as \c previousID will - * cause this function to return the first output trigger identifier. - */ - virtual CIdentifier getNextOutputTriggerIdentifier(const CIdentifier& previousID) const = 0; - /** - * \brief Gets the name of a specific output trigger - * \param id [in] : the identifier of the trigger which name should be returned - * \return The name of the specified output trigger on success - * \return En empty string on error - */ - virtual CString getOutputTriggerName(const CIdentifier& id) const = 0; - /** - * \brief Tests whether an output trigger is activated or not. - * \param id [in] : the identifier of the output trigger which activation status should be returned - * \return \e true if the provided trigger is currently active. - * \return \e false if the provided trigger is not currently active or does not exist. - */ - virtual bool isOutputTriggerActive(const CIdentifier& id) const = 0; - - /** - * \brief Gets next input trigger identifier given the previous input trigger - * \param previousID [in] : the previous input trigger - * \return the next input trigger identifier if existing. - * \return \c OV_UndefinedIdentifier if the previous was the last input trigger identifier. - * \note Passing \c OV_UndefinedIdentifier as \c previousID will - * cause this function to return the first input trigger identifier. - */ - virtual CIdentifier getNextInputTriggerIdentifier(const CIdentifier& previousID) const = 0; - /** - * \brief Gets the name of a specific input trigger - * \param id [in] : the identifier of the trigger which name should be returned - * \return The name of the specified input trigger on success - * \return En empty string on error - */ - virtual CString getInputTriggerName(const CIdentifier& id) const = 0; - /** - * \brief Activates an input trigger before calling the processing function. - * \param id [in] : the identifier of the input to activate - * \param state [in]: the new trigger state this input trigger should take (\e true for active, \e false for inactive) - * \return \e true in case the state was correctly changed. - * \return \e false in case the state was not changed or the provided trigger id does not exist. - */ - virtual bool activateInputTrigger(const CIdentifier& id, bool state) = 0; - - //@} - /** \name Algorithm functions */ - //@{ - - /** - * \brief Initializes the algorithm - * \return \e true in case of success. - * \return \e false in case of error. - * \note The algorithm context is managed internally - * \pre The algorithm is not yet initialized - */ - virtual bool initialize() = 0; - /** - * \brief Uninitializes the algorithm - * \return \e true in case of success. - * \return \e false in case of error. - * \note The algorithm context is managed internally - * \pre The algorithm is initialized - */ - virtual bool uninitialize() = 0; - /** - * \brief Calls the processing method of the algorithm - * \return \e true in case of success. - * \return \e false in case of error. - * \note The algorithm context is managed internally - * \pre The algorithm is initialized - */ - virtual bool process() = 0; - /** - * \brief Activates an input trigger and immediatly calls the processing method - * \param id [in] : the identifier of the input trigger to activate - * \return \e true in case of success. - * \return \e false in case the trigger does not exist or the processing did not succeed. - * \note The algorithm context is managed internally - * \pre The algorithm is initialized - */ - virtual bool process(const CIdentifier& id) = 0; - - - virtual bool isAlgorithmDerivedFrom(const CIdentifier& classID) = 0; - - //@} - - _IsDerivedFromClass_(IKernelObject, OV_ClassId_Kernel_Algorithm_AlgorithmProxy) - }; - } // namespace Kernel -} // namespace OpenViBE +public: + + /** \name Input parameters */ + //@{ + + /** + * \brief Gets next input parameter identifier given the previous input parameter + * \param previousID [in] : the previous input parameter + * \return the next input parameter identifier if existing. + * \return \c OV_UndefinedIdentifier if the previous was the last input parameter identifier. + * \note Passing \c OV_UndefinedIdentifier as \c previousID will + * cause this function to return the first input parameter identifier. + */ + virtual CIdentifier getNextInputParameterIdentifier(const CIdentifier& previousID) const = 0; + /** + * \brief Gets the name of a specific input parameter + * \param id [in] : the identifier of the parameter which name should be returned + * \return The name of the specified input parameter on success + * \return En empty string on error + */ + virtual CString getInputParameterName(const CIdentifier& id) const = 0; + /** + * \brief Gets the parameter details of a specific input parameter + * \param id [in] : the identifier of the parameter which details should be returned + * \return the parameter pointer that corresponds to the provided id. + * \return \c NULL in case of error. + */ + virtual IParameter* getInputParameter(const CIdentifier& id) = 0; + + //@} + /** \name Output parameters */ + //@{ + + /** + * \brief Gets next output parameter identifier given the previous output parameter + * \param previousID [in] : the previous output parameter + * \return the next output parameter identifier if existing. + * \return \c OV_UndefinedIdentifier if the previous was the last output parameter identifier. + * \note Passing \c OV_UndefinedIdentifier as \c previousID will + * cause this function to return the first output parameter identifier. + */ + virtual CIdentifier getNextOutputParameterIdentifier(const CIdentifier& previousID) const = 0; + /** + * \brief Gets the name of a specific input parameter + * \param id [in] : the identifier of the parameter which name should be returned + * \return The name of the specified input parameter on success + * \return En empty string on error + */ + virtual CString getOutputParameterName(const CIdentifier& id) const = 0; + /** + * \brief Gets the parameter details of a specific output parameter + * \param id [in] : the identifier of the parameter which details should be returned + * \return the parameter pointer that corresponds to the provided id. + * \return \c NULL in case of error. + */ + virtual IParameter* getOutputParameter(const CIdentifier& id) = 0; + + //@} + /** \name Trigger management */ + //@{ + + /** + * \brief Gets next output trigger identifier given the previous output trigger + * \param previousID [in] : the previous output trigger + * \return the next output trigger identifier if existing. + * \return \c OV_UndefinedIdentifier if the previous was the last output trigger identifier. + * \note Passing \c OV_UndefinedIdentifier as \c previousID will + * cause this function to return the first output trigger identifier. + */ + virtual CIdentifier getNextOutputTriggerIdentifier(const CIdentifier& previousID) const = 0; + /** + * \brief Gets the name of a specific output trigger + * \param id [in] : the identifier of the trigger which name should be returned + * \return The name of the specified output trigger on success + * \return En empty string on error + */ + virtual CString getOutputTriggerName(const CIdentifier& id) const = 0; + /** + * \brief Tests whether an output trigger is activated or not. + * \param id [in] : the identifier of the output trigger which activation status should be returned + * \return \e true if the provided trigger is currently active. + * \return \e false if the provided trigger is not currently active or does not exist. + */ + virtual bool isOutputTriggerActive(const CIdentifier& id) const = 0; + + /** + * \brief Gets next input trigger identifier given the previous input trigger + * \param previousID [in] : the previous input trigger + * \return the next input trigger identifier if existing. + * \return \c OV_UndefinedIdentifier if the previous was the last input trigger identifier. + * \note Passing \c OV_UndefinedIdentifier as \c previousID will + * cause this function to return the first input trigger identifier. + */ + virtual CIdentifier getNextInputTriggerIdentifier(const CIdentifier& previousID) const = 0; + /** + * \brief Gets the name of a specific input trigger + * \param id [in] : the identifier of the trigger which name should be returned + * \return The name of the specified input trigger on success + * \return En empty string on error + */ + virtual CString getInputTriggerName(const CIdentifier& id) const = 0; + /** + * \brief Activates an input trigger before calling the processing function. + * \param id [in] : the identifier of the input to activate + * \param state [in]: the new trigger state this input trigger should take (\e true for active, \e false for inactive) + * \return \e true in case the state was correctly changed. + * \return \e false in case the state was not changed or the provided trigger id does not exist. + */ + virtual bool activateInputTrigger(const CIdentifier& id, bool state) = 0; + + //@} + /** \name Algorithm functions */ + //@{ + + /** + * \brief Initializes the algorithm + * \return \e true in case of success. + * \return \e false in case of error. + * \note The algorithm context is managed internally + * \pre The algorithm is not yet initialized + */ + virtual bool initialize() = 0; + /** + * \brief Uninitializes the algorithm + * \return \e true in case of success. + * \return \e false in case of error. + * \note The algorithm context is managed internally + * \pre The algorithm is initialized + */ + virtual bool uninitialize() = 0; + /** + * \brief Calls the processing method of the algorithm + * \return \e true in case of success. + * \return \e false in case of error. + * \note The algorithm context is managed internally + * \pre The algorithm is initialized + */ + virtual bool process() = 0; + /** + * \brief Activates an input trigger and immediatly calls the processing method + * \param id [in] : the identifier of the input trigger to activate + * \return \e true in case of success. + * \return \e false in case the trigger does not exist or the processing did not succeed. + * \note The algorithm context is managed internally + * \pre The algorithm is initialized + */ + virtual bool process(const CIdentifier& id) = 0; + + + virtual bool isAlgorithmDerivedFrom(const CIdentifier& classID) = 0; + + //@} + + _IsDerivedFromClass_(IKernelObject, OV_ClassId_Kernel_Algorithm_AlgorithmProxy) +}; +} // namespace Kernel +} // namespace OpenViBE diff --git a/openvibe/include/openvibe/kernel/configuration/ovIConfigurationKeywordExpandCallback.h b/openvibe/include/openvibe/kernel/configuration/ovIConfigurationKeywordExpandCallback.h index 9557ab7d3fbf6957c5bc8a0eda2ba86bcaed8d0c..e4b8b1922f0b356d38f70a55a1d5e54fba830a25 100644 --- a/openvibe/include/openvibe/kernel/configuration/ovIConfigurationKeywordExpandCallback.h +++ b/openvibe/include/openvibe/kernel/configuration/ovIConfigurationKeywordExpandCallback.h @@ -2,26 +2,24 @@ #include <ov_common_defines.h> -namespace OpenViBE -{ - class CString; +namespace OpenViBE { +class CString; - namespace Kernel - { - /** - * \class IConfigurationKeywordExpandCallback - * \author Jozef Legeny (Mensia Technologies) - * \date 2014-05-06 - * \brief Callback used for overriding a keyword in IConfigurationManager - * \ingroup Group_Config - * \ingroup Group_Kernel - */ - class OV_API IConfigurationKeywordExpandCallback - { - public: +namespace Kernel { +/** + * \class IConfigurationKeywordExpandCallback + * \author Jozef Legeny (Mensia Technologies) + * \date 2014-05-06 + * \brief Callback used for overriding a keyword in IConfigurationManager + * \ingroup Group_Config + * \ingroup Group_Kernel + */ +class OV_API IConfigurationKeywordExpandCallback +{ +public: - virtual ~IConfigurationKeywordExpandCallback() {} - virtual bool expand(const CString& in, CString& out) const = 0; - }; - } // namespace Kernel -} // namespace OpenViBE + virtual ~IConfigurationKeywordExpandCallback() {} + virtual bool expand(const CString& in, CString& out) const = 0; +}; +} // namespace Kernel +} // namespace OpenViBE diff --git a/openvibe/include/openvibe/kernel/configuration/ovIConfigurationManager.h b/openvibe/include/openvibe/kernel/configuration/ovIConfigurationManager.h index 30d1df5144784552a43337c47112ee59730f116d..e95a77ba9f87269bb824f652cb5f1af21d13bbe7 100644 --- a/openvibe/include/openvibe/kernel/configuration/ovIConfigurationManager.h +++ b/openvibe/include/openvibe/kernel/configuration/ovIConfigurationManager.h @@ -2,254 +2,252 @@ #include "../ovIKernelObject.h" -namespace OpenViBE +namespace OpenViBE { +namespace Kernel { +class IConfigurationKeywordExpandCallback; + +/** + * \class IConfigurationManager + * \author Yann Renard (INRIA/IRISA) + * \date 2008-11-05 + * \brief Manager for all kind of configuration + * \ingroup Group_Config + * \ingroup Group_Kernel + */ +class OV_API IConfigurationManager : public IKernelObject { - namespace Kernel - { - class IConfigurationKeywordExpandCallback; - - /** - * \class IConfigurationManager - * \author Yann Renard (INRIA/IRISA) - * \date 2008-11-05 - * \brief Manager for all kind of configuration - * \ingroup Group_Config - * \ingroup Group_Kernel - */ - class OV_API IConfigurationManager : public IKernelObject - { - public: - - /** - * \brief Clears the content of this configuration manager - */ - virtual void clear() = 0; - - /** - * \brief Parses a configuration file and adds its content as token configuration - * \param filenameWildCard [in] : a wildcard of the files to parse & add - * \return \e true in case of success - * \return \e false in case of error - * \note In case the wildcard matches several filenames, it is up to this - * configuration manager to choose the order it parses the files in. - * \sa IConfigurationManager::createConfigurationToken - */ - virtual bool addConfigurationFromFile(const CString& filenameWildCard) = 0; - - /** - * \brief Creates a new configuration token in this configuration manager - * \param name [in] : the name of the configuration token - * \param value [in] the value of the configuration token - * \return the identifier of the newly created token in case of success - * \return \c OV_UndefinedIdentifier in case of error - * \sa IConfigurationManager::releaseConfigurationToken - * \sa IConfigurationManager::createConfigurationToken - */ - virtual CIdentifier createConfigurationToken(const CString& name, const CString& value) = 0; - /** - * \brief Removes an existing configuration token - * \param id [in] : the identifier of the token to remove - * \return \e true in case of success - * \return \e false in case of error - * \sa IConfigurationManager::addConfigurationFromFile - * \sa IConfigurationManager::createConfigurationToken - */ - virtual bool releaseConfigurationToken(const CIdentifier& id) = 0; - /** - * \brief Iterates on the existing configuration tokens of this configuration manager - * \param prevConfigTokenID [in] : the identifier of the token to start the iteration from - * \return the identifier of the next configuration token in case of success - * \return \c OV_UndefinedIdentifier in case there is no more token to iterate on - * - * Typicall use of this function is : - * \code - * CIdentifier tokenID = OV_UndefinedIdentifier; // defaults to OV_UndefinedIdentifier - * while((tokenID=configManager->getNextConfigurationTokenIdentifier(tokenID)) != OV_UndefinedIdentifier) - * { - * // do some stuff with current token identified with tokenID - * } - * \endcode - */ - virtual CIdentifier getNextConfigurationTokenIdentifier(const CIdentifier& prevConfigTokenID) const = 0; - - /** - * \brief Gets a token's name from its id - * \param id [in] : the token id which name should be returned - * \return the name of the token in case of success - * \return an empty string in case of error - * \sa IConfigurationManager::getConfigurationTokenValue - */ - virtual CString getConfigurationTokenName(const CIdentifier& id) const = 0; - /** - * \brief Gets a token's value from its id - * \param id [in] : the token id which value should be returned - * \return the value (unexapanded) of the token in case of success - * \return an empty string in case of error - * \sa IConfigurationManager::getConfigurationTokenName - * \sa IConfigurationManager::expand and others - * \note the returned value is not expanded by this configuration manager ; only the - * value that was passed at creation time is returned. If you want to expand - * things, please use IConfigurationManager::expand - */ - virtual CString getConfigurationTokenValue(const CIdentifier& id) const = 0; - - /** - * \brief Changes the name of an exisiting token - * \param id [in] : the identifier of the token which name should be changed - * \param name [in] : the new name of the configuration token - * \return \e true in case of success - * \return \e false in case of error - * \note it is not valid to add a token using this function - * \sa IConfigurationManager::createConfigurationToken - * \sa IConfigurationManager::addConfigurationFromFile - * \sa IConfigurationManager::setConfigurationTokenValue - */ - virtual bool setConfigurationTokenName(const CIdentifier& id, const CString& name) = 0; - /** - * \brief Changes the value of an exisiting token - * \param id [in] : the identifier of the token which value should be changed - * \param value [in] : the new value of the configuration token - * \return \e true in case of success - * \return \e false in case of error - * \note it is not valid to add a token using this function - * \sa IConfigurationManager::createConfigurationToken - * \sa IConfigurationManager::addConfigurationFromFile - * \sa IConfigurationManager::setConfigurationTokenName - */ - virtual bool setConfigurationTokenValue(const CIdentifier& id, const CString& value) = 0; - - /** - * \brief Adds a token or replaces the value of a token. - * \param name [in] : the name of the token which value should be changed - * \param value [in] : the new value of the configuration token - * \return \e true in case of success - * \return \e false in case of error - * \note new tokens can be added with this function - * \note this call is not recursive - * \sa IConfigurationManager::createConfigurationToken - * \sa IConfigurationManager::addConfigurationFromFile - * \sa IConfigurationManager::setConfigurationTokenName - */ - virtual bool addOrReplaceConfigurationToken(const CString& name, const CString& value) = 0; - - /** - * \brief Searches the identifier of a token with a given name - * \param name [in] : the name of the token which identifier should be found - * \param recursive [in] : when set to true, asks this configuration manager to propagate - * the request to parent configuration manager (if any). - * \return the identifier of the token with the actual name in case of success - * \return \c OV_UndefinedIdentifier in case of error - * \note if \c recursive is set to \e true then the returned identifier should - * not be considered as the identifier of an existing token in this configuration manager - * as it may have been returned from a parent configuration manager. Instead, one must consider - * the returned identifier as a kind of boolean value : such token actually exists or such - * token does not exist. - */ - virtual CIdentifier lookUpConfigurationTokenIdentifier(const CString& name, bool recursive = false) const = 0; - /** - * \brief Searches the value of a token with a given name - * \param name [in] : the name of the token which value should be found - * \return the value of the token with the actual name in case of success - * \note This function differs of \c getConfigurationTokenName in the sense that it - * recursively requests a token value to parent configuration managers until it - * finds one (if any). It also differs from the \c expand function in the sense that - * it takes a token name as input but does not expand its value when it finds it. - */ - virtual CString lookUpConfigurationTokenValue(const CString& name) const = 0; - - - /** - * \brief Adds a new parser for special variables - * \param keyword [in] : keyword to overload - * \param callback [in] : handler for the keyword - * \return true in case of success - * \note This parser provides a function that will handle expanding of - * tokens like $keyword{sometext}. "sometext" will be passed to the - * callback; - */ - virtual bool registerKeywordParser(const CString& keyword, const IConfigurationKeywordExpandCallback& callback) = 0; - - /** - * \brief Removes the keyword parser for a given keyword - * \param keyword [in] : keyword of the parser to remove - * \return true in case of success - */ - virtual bool unregisterKeywordParser(const CString& keyword) = 0; - - /** - * \brief Removes the keyword parser for a given keyword - * \param callback [in] : handler for the keyword - * \return true in case of success - */ - virtual bool unregisterKeywordParser(const IConfigurationKeywordExpandCallback& callback) = 0; - - /** - * \brief Expands a string to an expanded string based on its use of configuration tokens - * \param expression [in] : the string that you want to expan - * \return the expanded string - * \sa IConfigurationManager::expandAsFloat - * \sa IConfigurationManager::expandAsInteger - * \sa IConfigurationManager::expandAsUInteger - * \sa IConfigurationManager::expandAsBoolean - * \sa IConfigurationManager::expandAsEnumerationEntryValue - * - * Typical use of this function is : - * \code - * configManager->expand("${TokenName}") - * \endcode - */ - virtual CString expand(const CString& expression) const = 0; - - _IsDerivedFromClass_(IKernelObject, OV_ClassId_Kernel_Config_ConfigManager) - - virtual CString expandOnlyKeyword(const CString& keyword, const CString& expression, bool preserveBackslashes = false) const = 0; - /** - * \brief Expands a string to a floating point value based on its use of configuration tokens - * \param in [in] : the string that you want to expand - * \param fallbackValue [in] : a fall back value to return in case the expanded - * string can not be parsed as a floating point value - * \return the expanded value - * \sa IConfigurationManager::expand - */ - virtual double expandAsFloat(const CString& in, double fallbackValue = 0) const = 0; - /** - * \brief Expands a string to an integer value based on its use of configuration tokens - * \param in [in] : the string that you want to expand - * \param fallbackValue [in] : a fall back value to return in case the expanded - * string can not be parsed as an integer value - * \return the expanded value - * \sa IConfigurationManager::expand - */ - virtual int64_t expandAsInteger(const CString& in, int64_t fallbackValue = 0) const = 0; - /** - * \brief Expands a string to an unsigned integer value based on its use of configuration tokens - * \param in [in] : the string that you want to expand - * \param fallbackValue [in] : a fall back value to return in case the expanded - * string can not be parsed as an unsigned integer value - * \return the expanded value - * \sa IConfigurationManager::expand - */ - virtual uint64_t expandAsUInteger(const CString& in, uint64_t fallbackValue = 0) const = 0; - /** - * \brief Expands a string to a boolean value based on its use of configuration tokens - * \param in [in] : the string that you want to expand - * \param fallbackValue [in] : a fall back value to return in case the expanded - * string can not be parsed as a boolean value - * \return the expanded value - * \sa IConfigurationManager::expand - */ - virtual bool expandAsBoolean(const CString& in, bool fallbackValue = true) const = 0; - /** - * \brief Expands a string to an enumeration entry value based on its use of configuration tokens - * \param in [in] : the string that you want to expand - * \param enumerationTypeID [in] : the enumeration type to use - * \param fallbackValue [in] : a fall back value to return in case the expanded - * string can not be parsed as an enumeration entry value - * \return the expanded value - * \sa IConfigurationManager::expand - * \sa ITypeManager - */ - virtual uint64_t expandAsEnumerationEntryValue(const CString& in, const CIdentifier& enumerationTypeID, uint64_t fallbackValue = 0) const = 0; - }; - } // namespace Kernel -} // namespace OpenViBE +public: + + /** + * \brief Clears the content of this configuration manager + */ + virtual void clear() = 0; + + /** + * \brief Parses a configuration file and adds its content as token configuration + * \param filenameWildCard [in] : a wildcard of the files to parse & add + * \return \e true in case of success + * \return \e false in case of error + * \note In case the wildcard matches several filenames, it is up to this + * configuration manager to choose the order it parses the files in. + * \sa IConfigurationManager::createConfigurationToken + */ + virtual bool addConfigurationFromFile(const CString& filenameWildCard) = 0; + + /** + * \brief Creates a new configuration token in this configuration manager + * \param name [in] : the name of the configuration token + * \param value [in] the value of the configuration token + * \return the identifier of the newly created token in case of success + * \return \c OV_UndefinedIdentifier in case of error + * \sa IConfigurationManager::releaseConfigurationToken + * \sa IConfigurationManager::createConfigurationToken + */ + virtual CIdentifier createConfigurationToken(const CString& name, const CString& value) = 0; + /** + * \brief Removes an existing configuration token + * \param id [in] : the identifier of the token to remove + * \return \e true in case of success + * \return \e false in case of error + * \sa IConfigurationManager::addConfigurationFromFile + * \sa IConfigurationManager::createConfigurationToken + */ + virtual bool releaseConfigurationToken(const CIdentifier& id) = 0; + /** + * \brief Iterates on the existing configuration tokens of this configuration manager + * \param prevConfigTokenID [in] : the identifier of the token to start the iteration from + * \return the identifier of the next configuration token in case of success + * \return \c OV_UndefinedIdentifier in case there is no more token to iterate on + * + * Typicall use of this function is : + * \code + * CIdentifier tokenID = OV_UndefinedIdentifier; // defaults to OV_UndefinedIdentifier + * while((tokenID=configManager->getNextConfigurationTokenIdentifier(tokenID)) != OV_UndefinedIdentifier) + * { + * // do some stuff with current token identified with tokenID + * } + * \endcode + */ + virtual CIdentifier getNextConfigurationTokenIdentifier(const CIdentifier& prevConfigTokenID) const = 0; + + /** + * \brief Gets a token's name from its id + * \param id [in] : the token id which name should be returned + * \return the name of the token in case of success + * \return an empty string in case of error + * \sa IConfigurationManager::getConfigurationTokenValue + */ + virtual CString getConfigurationTokenName(const CIdentifier& id) const = 0; + /** + * \brief Gets a token's value from its id + * \param id [in] : the token id which value should be returned + * \return the value (unexapanded) of the token in case of success + * \return an empty string in case of error + * \sa IConfigurationManager::getConfigurationTokenName + * \sa IConfigurationManager::expand and others + * \note the returned value is not expanded by this configuration manager ; only the + * value that was passed at creation time is returned. If you want to expand + * things, please use IConfigurationManager::expand + */ + virtual CString getConfigurationTokenValue(const CIdentifier& id) const = 0; + + /** + * \brief Changes the name of an exisiting token + * \param id [in] : the identifier of the token which name should be changed + * \param name [in] : the new name of the configuration token + * \return \e true in case of success + * \return \e false in case of error + * \note it is not valid to add a token using this function + * \sa IConfigurationManager::createConfigurationToken + * \sa IConfigurationManager::addConfigurationFromFile + * \sa IConfigurationManager::setConfigurationTokenValue + */ + virtual bool setConfigurationTokenName(const CIdentifier& id, const CString& name) = 0; + /** + * \brief Changes the value of an exisiting token + * \param id [in] : the identifier of the token which value should be changed + * \param value [in] : the new value of the configuration token + * \return \e true in case of success + * \return \e false in case of error + * \note it is not valid to add a token using this function + * \sa IConfigurationManager::createConfigurationToken + * \sa IConfigurationManager::addConfigurationFromFile + * \sa IConfigurationManager::setConfigurationTokenName + */ + virtual bool setConfigurationTokenValue(const CIdentifier& id, const CString& value) = 0; + + /** + * \brief Adds a token or replaces the value of a token. + * \param name [in] : the name of the token which value should be changed + * \param value [in] : the new value of the configuration token + * \return \e true in case of success + * \return \e false in case of error + * \note new tokens can be added with this function + * \note this call is not recursive + * \sa IConfigurationManager::createConfigurationToken + * \sa IConfigurationManager::addConfigurationFromFile + * \sa IConfigurationManager::setConfigurationTokenName + */ + virtual bool addOrReplaceConfigurationToken(const CString& name, const CString& value) = 0; + + /** + * \brief Searches the identifier of a token with a given name + * \param name [in] : the name of the token which identifier should be found + * \param recursive [in] : when set to true, asks this configuration manager to propagate + * the request to parent configuration manager (if any). + * \return the identifier of the token with the actual name in case of success + * \return \c OV_UndefinedIdentifier in case of error + * \note if \c recursive is set to \e true then the returned identifier should + * not be considered as the identifier of an existing token in this configuration manager + * as it may have been returned from a parent configuration manager. Instead, one must consider + * the returned identifier as a kind of boolean value : such token actually exists or such + * token does not exist. + */ + virtual CIdentifier lookUpConfigurationTokenIdentifier(const CString& name, bool recursive = false) const = 0; + /** + * \brief Searches the value of a token with a given name + * \param name [in] : the name of the token which value should be found + * \return the value of the token with the actual name in case of success + * \note This function differs of \c getConfigurationTokenName in the sense that it + * recursively requests a token value to parent configuration managers until it + * finds one (if any). It also differs from the \c expand function in the sense that + * it takes a token name as input but does not expand its value when it finds it. + */ + virtual CString lookUpConfigurationTokenValue(const CString& name) const = 0; + + + /** + * \brief Adds a new parser for special variables + * \param keyword [in] : keyword to overload + * \param callback [in] : handler for the keyword + * \return true in case of success + * \note This parser provides a function that will handle expanding of + * tokens like $keyword{sometext}. "sometext" will be passed to the + * callback; + */ + virtual bool registerKeywordParser(const CString& keyword, const IConfigurationKeywordExpandCallback& callback) = 0; + + /** + * \brief Removes the keyword parser for a given keyword + * \param keyword [in] : keyword of the parser to remove + * \return true in case of success + */ + virtual bool unregisterKeywordParser(const CString& keyword) = 0; + + /** + * \brief Removes the keyword parser for a given keyword + * \param callback [in] : handler for the keyword + * \return true in case of success + */ + virtual bool unregisterKeywordParser(const IConfigurationKeywordExpandCallback& callback) = 0; + + /** + * \brief Expands a string to an expanded string based on its use of configuration tokens + * \param expression [in] : the string that you want to expan + * \return the expanded string + * \sa IConfigurationManager::expandAsFloat + * \sa IConfigurationManager::expandAsInteger + * \sa IConfigurationManager::expandAsUInteger + * \sa IConfigurationManager::expandAsBoolean + * \sa IConfigurationManager::expandAsEnumerationEntryValue + * + * Typical use of this function is : + * \code + * configManager->expand("${TokenName}") + * \endcode + */ + virtual CString expand(const CString& expression) const = 0; + + _IsDerivedFromClass_(IKernelObject, OV_ClassId_Kernel_Config_ConfigManager) + + virtual CString expandOnlyKeyword(const CString& keyword, const CString& expression, bool preserveBackslashes = false) const = 0; + /** + * \brief Expands a string to a floating point value based on its use of configuration tokens + * \param in [in] : the string that you want to expand + * \param fallbackValue [in] : a fall back value to return in case the expanded + * string can not be parsed as a floating point value + * \return the expanded value + * \sa IConfigurationManager::expand + */ + virtual double expandAsFloat(const CString& in, double fallbackValue = 0) const = 0; + /** + * \brief Expands a string to an integer value based on its use of configuration tokens + * \param in [in] : the string that you want to expand + * \param fallbackValue [in] : a fall back value to return in case the expanded + * string can not be parsed as an integer value + * \return the expanded value + * \sa IConfigurationManager::expand + */ + virtual int64_t expandAsInteger(const CString& in, int64_t fallbackValue = 0) const = 0; + /** + * \brief Expands a string to an unsigned integer value based on its use of configuration tokens + * \param in [in] : the string that you want to expand + * \param fallbackValue [in] : a fall back value to return in case the expanded + * string can not be parsed as an unsigned integer value + * \return the expanded value + * \sa IConfigurationManager::expand + */ + virtual uint64_t expandAsUInteger(const CString& in, uint64_t fallbackValue = 0) const = 0; + /** + * \brief Expands a string to a boolean value based on its use of configuration tokens + * \param in [in] : the string that you want to expand + * \param fallbackValue [in] : a fall back value to return in case the expanded + * string can not be parsed as a boolean value + * \return the expanded value + * \sa IConfigurationManager::expand + */ + virtual bool expandAsBoolean(const CString& in, bool fallbackValue = true) const = 0; + /** + * \brief Expands a string to an enumeration entry value based on its use of configuration tokens + * \param in [in] : the string that you want to expand + * \param enumerationTypeID [in] : the enumeration type to use + * \param fallbackValue [in] : a fall back value to return in case the expanded + * string can not be parsed as an enumeration entry value + * \return the expanded value + * \sa IConfigurationManager::expand + * \sa ITypeManager + */ + virtual uint64_t expandAsEnumerationEntryValue(const CString& in, const CIdentifier& enumerationTypeID, uint64_t fallbackValue = 0) const = 0; +}; +} // namespace Kernel +} // namespace OpenViBE diff --git a/openvibe/include/openvibe/kernel/error/ovErrorType.h b/openvibe/include/openvibe/kernel/error/ovErrorType.h index 9f48c2886afa7c67c962e621600714529256e5c1..7ab355fad45a1fd06ec3c030e0f3e3eccf646e82 100644 --- a/openvibe/include/openvibe/kernel/error/ovErrorType.h +++ b/openvibe/include/openvibe/kernel/error/ovErrorType.h @@ -21,54 +21,52 @@ #pragma once -namespace OpenViBE +namespace OpenViBE { +namespace Kernel { +/** + * \class ErrorType + * \author Charles Garraud (Inria) + * \date 2016-07-13 + * \brief List of error types + * \ingroup Group_Error + * \ingroup Group_Kernel + */ +enum class ErrorType { - namespace Kernel - { - /** - * \class ErrorType - * \author Charles Garraud (Inria) - * \date 2016-07-13 - * \brief List of error types - * \ingroup Group_Error - * \ingroup Group_Kernel - */ - enum class ErrorType - { - // Misc - NoErrorFound = 0, ///< Used when no error occurs */ - Unknown = 1, ///< Unknown error */ - Internal = 2, ///< Used mainly for high-level errors generated by low-level errors */ - NotImplemented = 3, ///< Used when the body of an API call is not yet implemented */ - ExceptionCaught = 4, ///< Used to report an error related to a c++ expection caught in the system */ - BadCall = 5, ///< Used when an API call is incompatible with the current state */ - BadProcessing = 6, ///< Used when a processing/computation failed */ - BadVersion = 7, ///< Used for plugin or api version mismatch */ - // Value setting - BadValue = 10, ///< Used when an entity is given an invalid value */ - BadArgument = 11, ///< Used when a function is fed with invalid arguments */ - BadCast = 12, ///< Used when a cast failed */ - OutOfBound = 13, ///< Used for out of range value (specific case of BadValue/BadArguments) */ - Overflow = 14, ///< Used to report arithmetic overflow */ - BadParsing = 15, ///< Used to report data parsing error */ - // Alloc - BadAlloc = 20, ///< Used when an allocation failed */ - OutOfMemory = 21, ///< Used when the system is running out of memory (specific case of BadAlloc) */ - // Resource - ResourceNotFound = 30, ///< Used to report that a resource (logical or physical) was not found */ - BadResourceCreation = 31, ///< Used to report that a resource (logical or physical) could not be created */ - // IO - BadFileRead = 40, ///< Used when opening a file failed */ - BadFileWrite = 41, ///< Used when writing to a file failed */ - BadFileParsing = 42, ///< Used when reading succeeded but parsing of data within the file failed */ - BadNetworkConnection = 43, ///< Used when network connection failed */ - BadXMLSchemaValidation = 44, ///< Used when validation of xml files against xsd schema fails */ - // Config - BadConfig = 50, ///< Used when a given configuration state is erroneous */ - BadInput = 51, ///< Used when an input (box, algorithm) is missing, empty or has a wrong value */ - BadOutput = 52, ///< Used when an output (box, algorithm) is missing, empty or has a wrong value */ - BadTrigger = 53, ///< Used when an algorithm trigger has a wrong value */ - BadSetting = 54 ///< Used when a box setting has a wrong value */ - }; - } // namespace Kernel -} // namespace OpenViBE + // Misc + NoErrorFound = 0, ///< Used when no error occurs */ + Unknown = 1, ///< Unknown error */ + Internal = 2, ///< Used mainly for high-level errors generated by low-level errors */ + NotImplemented = 3, ///< Used when the body of an API call is not yet implemented */ + ExceptionCaught = 4, ///< Used to report an error related to a c++ expection caught in the system */ + BadCall = 5, ///< Used when an API call is incompatible with the current state */ + BadProcessing = 6, ///< Used when a processing/computation failed */ + BadVersion = 7, ///< Used for plugin or api version mismatch */ + // Value setting + BadValue = 10, ///< Used when an entity is given an invalid value */ + BadArgument = 11, ///< Used when a function is fed with invalid arguments */ + BadCast = 12, ///< Used when a cast failed */ + OutOfBound = 13, ///< Used for out of range value (specific case of BadValue/BadArguments) */ + Overflow = 14, ///< Used to report arithmetic overflow */ + BadParsing = 15, ///< Used to report data parsing error */ + // Alloc + BadAlloc = 20, ///< Used when an allocation failed */ + OutOfMemory = 21, ///< Used when the system is running out of memory (specific case of BadAlloc) */ + // Resource + ResourceNotFound = 30, ///< Used to report that a resource (logical or physical) was not found */ + BadResourceCreation = 31, ///< Used to report that a resource (logical or physical) could not be created */ + // IO + BadFileRead = 40, ///< Used when opening a file failed */ + BadFileWrite = 41, ///< Used when writing to a file failed */ + BadFileParsing = 42, ///< Used when reading succeeded but parsing of data within the file failed */ + BadNetworkConnection = 43, ///< Used when network connection failed */ + BadXMLSchemaValidation = 44, ///< Used when validation of xml files against xsd schema fails */ + // Config + BadConfig = 50, ///< Used when a given configuration state is erroneous */ + BadInput = 51, ///< Used when an input (box, algorithm) is missing, empty or has a wrong value */ + BadOutput = 52, ///< Used when an output (box, algorithm) is missing, empty or has a wrong value */ + BadTrigger = 53, ///< Used when an algorithm trigger has a wrong value */ + BadSetting = 54 ///< Used when a box setting has a wrong value */ +}; +} // namespace Kernel +} // namespace OpenViBE diff --git a/openvibe/include/openvibe/kernel/error/ovIError.h b/openvibe/include/openvibe/kernel/error/ovIError.h index 38e8d303b93707d306399b51c91a4c65b318da4b..762432ffe081d6a105fe5414eded54d2c5c20108 100644 --- a/openvibe/include/openvibe/kernel/error/ovIError.h +++ b/openvibe/include/openvibe/kernel/error/ovIError.h @@ -23,61 +23,59 @@ #include "../ovIKernelObject.h" -namespace OpenViBE +namespace OpenViBE { +namespace Kernel { +/** + * \class IError + * \author Charles Garraud (Inria) + * \date 2016-07-12 + * \brief Interface for Kernel error implementation + * \ingroup Group_Error + * \ingroup Group_Kernel + * + * IError interface aims at providing information about an error + * occurring in the framework. One specific concept here is the + * notion of nested errors. In a call stack, it can be + * interesting to catch a n-1 level error and enhance it instead + * of rethrowing it directy unchanged. In this case, we say + * the level n-1 error is nested into the level n error. + */ +class OV_API IError : public IKernelObject { - namespace Kernel - { - /** - * \class IError - * \author Charles Garraud (Inria) - * \date 2016-07-12 - * \brief Interface for Kernel error implementation - * \ingroup Group_Error - * \ingroup Group_Kernel - * - * IError interface aims at providing information about an error - * occurring in the framework. One specific concept here is the - * notion of nested errors. In a call stack, it can be - * interesting to catch a n-1 level error and enhance it instead - * of rethrowing it directy unchanged. In this case, we say - * the level n-1 error is nested into the level n error. - */ - class OV_API IError : public IKernelObject - { - public: +public: - IError() {} - ~IError() override {} - IError(const IError&) = delete; - IError& operator=(const IError&) = delete; + IError() {} + ~IError() override {} + IError(const IError&) = delete; + IError& operator=(const IError&) = delete; - /** - * \brief Retrieve error description - */ - virtual const char* getErrorString() const = 0; + /** + * \brief Retrieve error description + */ + virtual const char* getErrorString() const = 0; - /** - * \brief Retrieve error location - * \return the error location with file:line format - */ - virtual const char* getErrorLocation() const = 0; + /** + * \brief Retrieve error location + * \return the error location with file:line format + */ + virtual const char* getErrorLocation() const = 0; - /** - * \brief Retrieve error type - */ - virtual ErrorType getErrorType() const = 0; + /** + * \brief Retrieve error type + */ + virtual ErrorType getErrorType() const = 0; - /** - * \brief Retrieve nested error - * \return the nested error if there is one, nullptr otherwise - * - * \warning The error keeps the ownership of the nested error. - * Therefore the API consumer is not responsible for its - * life cycle/management - */ - virtual const IError* getNestedError() const = 0; + /** + * \brief Retrieve nested error + * \return the nested error if there is one, nullptr otherwise + * + * \warning The error keeps the ownership of the nested error. + * Therefore the API consumer is not responsible for its + * life cycle/management + */ + virtual const IError* getNestedError() const = 0; - _IsDerivedFromClass_(IKernelObject, OV_ClassId_Kernel_Error_Error) - }; - } // namespace Kernel -} // namespace OpenViBE + _IsDerivedFromClass_(IKernelObject, OV_ClassId_Kernel_Error_Error) +}; +} // namespace Kernel +} // namespace OpenViBE diff --git a/openvibe/include/openvibe/kernel/error/ovIErrorManager.h b/openvibe/include/openvibe/kernel/error/ovIErrorManager.h index c11562b2b321c1d7d263b9960909008ca4575e85..2422bc4f8e5ffee5bd2eddde48c1f76bd32b2975 100644 --- a/openvibe/include/openvibe/kernel/error/ovIErrorManager.h +++ b/openvibe/include/openvibe/kernel/error/ovIErrorManager.h @@ -24,94 +24,92 @@ #include "../ovIKernelObject.h" #include "ovErrorType.h" -namespace OpenViBE -{ - namespace Kernel - { - class IError; +namespace OpenViBE { +namespace Kernel { +class IError; - /** - * \class IErrorManager - * \author Charles Garraud (Inria) - * \date 2016-07-12 - * \brief Interface for Kernel error handler implementation - * \ingroup Group_Error - * \ingroup Group_Kernel - * - * This manager is reponsible for handling errors in the framework. - * Errors in the framework are considered as not acceptable behavior - * that can be detected and handled by the system. The concept of error - * is thus independant of warning or fatal crashes that must be handled - * separately. - */ - class OV_API IErrorManager : public IKernelObject - { - public: +/** + * \class IErrorManager + * \author Charles Garraud (Inria) + * \date 2016-07-12 + * \brief Interface for Kernel error handler implementation + * \ingroup Group_Error + * \ingroup Group_Kernel + * + * This manager is reponsible for handling errors in the framework. + * Errors in the framework are considered as not acceptable behavior + * that can be detected and handled by the system. The concept of error + * is thus independant of warning or fatal crashes that must be handled + * separately. + */ +class OV_API IErrorManager : public IKernelObject +{ +public: - /** - * \brief Push error to the manager - * \param type the error type - * \param description a self-explanatory description message - * - * Errors already added to the manager will be nested in the - * newly added error. - */ - virtual void pushError(ErrorType type, const char* description) = 0; + /** + * \brief Push error to the manager + * \param type the error type + * \param description a self-explanatory description message + * + * Errors already added to the manager will be nested in the + * newly added error. + */ + virtual void pushError(ErrorType type, const char* description) = 0; - /** - * \brief Push error with location information to the manager - * \param type the error type - * \param description a self-explanatory description of the error - * \param filename the source file where the error was detected - * \param line the line number where the error was detected - * - * Errors already added to the manager will be nested in the - * newly added error. - */ - virtual void pushErrorAtLocation(ErrorType type, const char* description, const char* filename, size_t line) = 0; + /** + * \brief Push error with location information to the manager + * \param type the error type + * \param description a self-explanatory description of the error + * \param filename the source file where the error was detected + * \param line the line number where the error was detected + * + * Errors already added to the manager will be nested in the + * newly added error. + */ + virtual void pushErrorAtLocation(ErrorType type, const char* description, const char* filename, size_t line) = 0; - /** - * \brief Release manager errors - * - * Release last error added to the manager and potentially - * all the nested errors recursively. - * - * \warning After this call, do not use pointers to IError retrieved - * before. It will lead to unexpected behavior mostly due - * to dangling pointers. - */ - virtual void releaseErrors() = 0; + /** + * \brief Release manager errors + * + * Release last error added to the manager and potentially + * all the nested errors recursively. + * + * \warning After this call, do not use pointers to IError retrieved + * before. It will lead to unexpected behavior mostly due + * to dangling pointers. + */ + virtual void releaseErrors() = 0; - /** - * \brief Check for existing errors in the manager - * \return true if manager contains errors, false otherwise - */ - virtual bool hasError() const = 0; + /** + * \brief Check for existing errors in the manager + * \return true if manager contains errors, false otherwise + */ + virtual bool hasError() const = 0; - /** - * \brief Get last error added to the manager - * \return the error if manager contains errors, nullptr otherwise - * - * \warning The manager keeps the ownership of IError instances. - * Therefore the API consumer is not responsible for their - * life cycle/management and must use releaseErrors to - * release them. - */ - virtual const IError* getLastError() const = 0; + /** + * \brief Get last error added to the manager + * \return the error if manager contains errors, nullptr otherwise + * + * \warning The manager keeps the ownership of IError instances. + * Therefore the API consumer is not responsible for their + * life cycle/management and must use releaseErrors to + * release them. + */ + virtual const IError* getLastError() const = 0; - /** - * \brief Get description of last error added to the manager - * \return the description if manager contains errors, empty string otherwise - */ - virtual const char* getLastErrorString() const = 0; + /** + * \brief Get description of last error added to the manager + * \return the description if manager contains errors, empty string otherwise + */ + virtual const char* getLastErrorString() const = 0; - /** - * \brief Get type of last error added to the manager - * \return the type if manager contains error, NoErrorFound otherwise - */ - virtual ErrorType getLastErrorType() const = 0; + /** + * \brief Get type of last error added to the manager + * \return the type if manager contains error, NoErrorFound otherwise + */ + virtual ErrorType getLastErrorType() const = 0; - _IsDerivedFromClass_(IKernelObject, OV_ClassId_Kernel_Error_ErrorManager) - }; - } // namespace Kernel -} // namespace OpenViBE + _IsDerivedFromClass_(IKernelObject, OV_ClassId_Kernel_Error_ErrorManager) +}; +} // namespace Kernel +} // namespace OpenViBE diff --git a/openvibe/include/openvibe/kernel/log/ovILogListener.h b/openvibe/include/openvibe/kernel/log/ovILogListener.h index dd694b03f174cbf5a156503585efe373ca5d6f8b..7f1355b665f04cd2a26317384404e35c48d6f9da 100644 --- a/openvibe/include/openvibe/kernel/log/ovILogListener.h +++ b/openvibe/include/openvibe/kernel/log/ovILogListener.h @@ -237,5 +237,5 @@ public: _IsDerivedFromClass_(IKernelObject, OV_ClassId_Kernel_Log_LogListener) }; -} // namespace Kernel -} // namespace OpenViBE +} // namespace Kernel +} // namespace OpenViBE diff --git a/openvibe/include/openvibe/kernel/log/ovILogManager.h b/openvibe/include/openvibe/kernel/log/ovILogManager.h index c7cb8a4dacdceeedac3d069eb184a02fc81b392b..ee221bb256c774055db148cffb37f51f299f899f 100644 --- a/openvibe/include/openvibe/kernel/log/ovILogManager.h +++ b/openvibe/include/openvibe/kernel/log/ovILogManager.h @@ -2,59 +2,57 @@ #include "ovILogListener.h" -namespace OpenViBE +namespace OpenViBE { +namespace Kernel { +/** + * \class ILogManager + * \brief Log manager + * \author Yann Renard (INRIA/IRISA) + * \date 2006-06-03 + * \ingroup Group_Log + * \ingroup Group_Kernel + * + * The log manager is responsible for keeping a trace of all the messages the application could send as debug output. Such information is not + * useful most of the cases but could become crucial in some cases. Thus there are different levels of activation for the log manager + * to work. The log manager forwards each log request to its registered log listeners that effectively do the log the way they want + * (be it a status window, a console, a file, whatever). See ILogListener for more details. + */ +class OV_API ILogManager : public ILogListener { - namespace Kernel - { - /** - * \class ILogManager - * \brief Log manager - * \author Yann Renard (INRIA/IRISA) - * \date 2006-06-03 - * \ingroup Group_Log - * \ingroup Group_Kernel - * - * The log manager is responsible for keeping a trace of all the messages the application could send as debug output. Such information is not - * useful most of the cases but could become crucial in some cases. Thus there are different levels of activation for the log manager - * to work. The log manager forwards each log request to its registered log listeners that effectively do the log the way they want - * (be it a status window, a console, a file, whatever). See ILogListener for more details. - */ - class OV_API ILogManager : public ILogListener - { - public: +public: - /** - * \brief Registers a new log listener - * \param listener [in] : the new listener to register - * \return \e true in case of success. \e false in case of error. - */ - virtual bool addListener(ILogListener* listener) = 0; - /** - * \brief Removes a registered listener - * \param listener [in] : the listener to unregister - * \return \e true in case of success. \e false in case of error. - */ - virtual bool removeListener(ILogListener* listener) = 0; + /** + * \brief Registers a new log listener + * \param listener [in] : the new listener to register + * \return \e true in case of success. \e false in case of error. + */ + virtual bool addListener(ILogListener* listener) = 0; + /** + * \brief Removes a registered listener + * \param listener [in] : the listener to unregister + * \return \e true in case of success. \e false in case of error. + */ + virtual bool removeListener(ILogListener* listener) = 0; - _IsDerivedFromClass_(ILogListener, OV_ClassId_Kernel_Log_LogManager) - }; + _IsDerivedFromClass_(ILogListener, OV_ClassId_Kernel_Log_LogManager) +}; - /** - * \brief Stream output operator - * \param logManager [in] : the log manager that takes the object - * \param object [in] : the object to log - * \return The log manager itself - * \sa ILogManager - * - * This function helps in logging different objects thanks to the - * stream operator. The log manager can almost be used as any std - * ostream object. - */ - template <class T> - ILogManager& operator <<(ILogManager& logManager, const T& object) - { - logManager.log(object); - return logManager; - } - } // namespace Kernel -} // namespace OpenViBE +/** + * \brief Stream output operator + * \param logManager [in] : the log manager that takes the object + * \param object [in] : the object to log + * \return The log manager itself + * \sa ILogManager + * + * This function helps in logging different objects thanks to the + * stream operator. The log manager can almost be used as any std + * ostream object. + */ +template <class T> +ILogManager& operator <<(ILogManager& logManager, const T& object) +{ + logManager.log(object); + return logManager; +} +} // namespace Kernel +} // namespace OpenViBE diff --git a/openvibe/include/openvibe/kernel/metabox/ovIMetaboxManager.h b/openvibe/include/openvibe/kernel/metabox/ovIMetaboxManager.h index 634c160d76f884b2d72cb2c70ed08498a925e66b..b3a78f109c4f8ebc808b4cd356cfe301d5e5d553 100755 --- a/openvibe/include/openvibe/kernel/metabox/ovIMetaboxManager.h +++ b/openvibe/include/openvibe/kernel/metabox/ovIMetaboxManager.h @@ -3,93 +3,91 @@ #include "../ovIKernelObject.h" #include "../../metaboxes/ovIMetaboxObjectDesc.h" -namespace OpenViBE +namespace OpenViBE { +namespace Kernel { +/** + * \class IMetaboxManager + * \brief Metabox manager + * \author Thierry Gaugry (INRIA/Mensia) + * \date 2017-04-12 + * \ingroup Group_Metabox + * \ingroup Group_Kernel + * + * The metabox manager is in charge of loading/unloading metaboxes + * modules (defined in OV_ScenarioImportContext_OnLoadMetaboxImport import context) + * containing OpenViBE metaboxes. + * It also provides functions in order to list metabox descriptors, + * create or release metabox objects... + */ +class OV_API IMetaboxManager : public IKernelObject { - namespace Kernel - { - /** - * \class IMetaboxManager - * \brief Metabox manager - * \author Thierry Gaugry (INRIA/Mensia) - * \date 2017-04-12 - * \ingroup Group_Metabox - * \ingroup Group_Kernel - * - * The metabox manager is in charge of loading/unloading metaboxes - * modules (defined in OV_ScenarioImportContext_OnLoadMetaboxImport import context) - * containing OpenViBE metaboxes. - * It also provides functions in order to list metabox descriptors, - * create or release metabox objects... - */ - class OV_API IMetaboxManager : public IKernelObject - { - public: +public: - /** \name Metabox modules/descriptors management */ - //@{ + /** \name Metabox modules/descriptors management */ + //@{ - /** - * \brief Loads new metaboxes module file(s) - * \param[in] fileNameWildCard : a wild card with the file(s) to search metaboxes in - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool addMetaboxesFromFiles(const CString& fileNameWildCard) = 0; + /** + * \brief Loads new metaboxes module file(s) + * \param[in] fileNameWildCard : a wild card with the file(s) to search metaboxes in + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool addMetaboxesFromFiles(const CString& fileNameWildCard) = 0; - /** - * \brief Gets next metabox object descriptor identifier - * \param[in] previousID : The identifier - * for the preceeding metabox object descriptor - * \return The identifier of the next metabox object descriptor in case of success. - * \retval \c OV_UndefinedIdentifier on error. - * \note Giving \c OV_UndefinedIdentifier as \c previousID - * will cause this function to return the first metabox object - * descriptor identifier. - */ - virtual CIdentifier getNextMetaboxObjectDescIdentifier(const CIdentifier& previousID) const = 0; + /** + * \brief Gets next metabox object descriptor identifier + * \param[in] previousID : The identifier + * for the preceeding metabox object descriptor + * \return The identifier of the next metabox object descriptor in case of success. + * \retval \c OV_UndefinedIdentifier on error. + * \note Giving \c OV_UndefinedIdentifier as \c previousID + * will cause this function to return the first metabox object + * descriptor identifier. + */ + virtual CIdentifier getNextMetaboxObjectDescIdentifier(const CIdentifier& previousID) const = 0; - /** - * \brief Gets details on a specific metabox object descriptor - * \param[in] id : the metabox object descriptor identifier which details should be returned - * \return the corresponding metabox object descriptor pointer. - */ - virtual const Plugins::IPluginObjectDesc* getMetaboxObjectDesc(const CIdentifier& id) const = 0; + /** + * \brief Gets details on a specific metabox object descriptor + * \param[in] id : the metabox object descriptor identifier which details should be returned + * \return the corresponding metabox object descriptor pointer. + */ + virtual const Plugins::IPluginObjectDesc* getMetaboxObjectDesc(const CIdentifier& id) const = 0; - /** - * \brief Sets details on a specific metabox object descriptor - * \param[in] id : the metabox object descriptor identifier - * \param[in] desc : the metabox object descriptor - */ - virtual void setMetaboxObjectDesc(const CIdentifier& id, Plugins::IPluginObjectDesc* desc) = 0; + /** + * \brief Sets details on a specific metabox object descriptor + * \param[in] id : the metabox object descriptor identifier + * \param[in] desc : the metabox object descriptor + */ + virtual void setMetaboxObjectDesc(const CIdentifier& id, Plugins::IPluginObjectDesc* desc) = 0; - /** - * \brief Gets the path of the scenario of a specific metabox - * \param[in] id : the metabox object descriptor identifier which path should be returned - * \return the path to the scenario file of the metabox. - */ - virtual CString getMetaboxFilePath(const CIdentifier& id) const = 0; - /** - * \brief Sets the path of the scenario of a specific metabox - * \param[in] id : the metabox object descriptor identifier - * \param[in] filePath : the metabox scenario path - */ - virtual void setMetaboxFilePath(const CIdentifier& id, const CString& filePath) = 0; + /** + * \brief Gets the path of the scenario of a specific metabox + * \param[in] id : the metabox object descriptor identifier which path should be returned + * \return the path to the scenario file of the metabox. + */ + virtual CString getMetaboxFilePath(const CIdentifier& id) const = 0; + /** + * \brief Sets the path of the scenario of a specific metabox + * \param[in] id : the metabox object descriptor identifier + * \param[in] filePath : the metabox scenario path + */ + virtual void setMetaboxFilePath(const CIdentifier& id, const CString& filePath) = 0; - /** - * \brief Gets the hash of the metabox - * \param[in] id : the metabox object descriptor identifier which hash should be returned - * \return the hash of the metabox. - */ - virtual CIdentifier getMetaboxHash(const CIdentifier& id) const = 0; - /** - * \brief Sets the hash of the metabox - * \param[in] id : the metabox object descriptor identifier - * \param[in] hash : the metabox hash - */ - virtual void setMetaboxHash(const CIdentifier& id, const CIdentifier& hash) = 0; + /** + * \brief Gets the hash of the metabox + * \param[in] id : the metabox object descriptor identifier which hash should be returned + * \return the hash of the metabox. + */ + virtual CIdentifier getMetaboxHash(const CIdentifier& id) const = 0; + /** + * \brief Sets the hash of the metabox + * \param[in] id : the metabox object descriptor identifier + * \param[in] hash : the metabox hash + */ + virtual void setMetaboxHash(const CIdentifier& id, const CIdentifier& hash) = 0; - _IsDerivedFromClass_(IKernelObject, OV_ClassId_Kernel_Metabox_MetaboxManager) - }; - } // namespace Kernel -} // namespace OpenViBE + _IsDerivedFromClass_(IKernelObject, OV_ClassId_Kernel_Metabox_MetaboxManager) +}; +} // namespace Kernel +} // namespace OpenViBE diff --git a/openvibe/include/openvibe/kernel/ovIConfigurable.h b/openvibe/include/openvibe/kernel/ovIConfigurable.h index badbdacbc95364aaf7b9048f1d967624c3f66dda..8bbae8d288eea61a1fe92c2810db3e112c3cbed6 100644 --- a/openvibe/include/openvibe/kernel/ovIConfigurable.h +++ b/openvibe/include/openvibe/kernel/ovIConfigurable.h @@ -2,114 +2,112 @@ #include "ovIKernelObject.h" -namespace OpenViBE -{ - namespace Kernel - { - class IParameter; +namespace OpenViBE { +namespace Kernel { +class IParameter; - /** - * \brief Parameter type enumeration for a configurable object - * \sa IConfigurable - * \sa IParameter - */ - enum EParameterType - { - ParameterType_None, ///< No parameter - ParameterType_Integer, ///< Integer parameter, 64bit - ParameterType_UInteger, ///< Unsigned integer parameter, 64bit - ParameterType_Enumeration, ///< Enumeration integer parameter - ParameterType_Boolean, ///< Boolean parameter - ParameterType_Float, ///< Float parameter, 64bit - ParameterType_String, ///< String parameter - ParameterType_Identifier, ///< Identifier parameter - ParameterType_Matrix, ///< Matrix pointer parameter - ParameterType_StimulationSet, ///< Stimulation set pointer parameter - ParameterType_MemoryBuffer, ///< Memory buffer pointer parameter - ParameterType_Object, ///< Object pointer parameter - ParameterType_Pointer, ///< Raw pointer parameter - }; +/** + * \brief Parameter type enumeration for a configurable object + * \sa IConfigurable + * \sa IParameter + */ +enum EParameterType +{ + ParameterType_None, ///< No parameter + ParameterType_Integer, ///< Integer parameter, 64bit + ParameterType_UInteger, ///< Unsigned integer parameter, 64bit + ParameterType_Enumeration, ///< Enumeration integer parameter + ParameterType_Boolean, ///< Boolean parameter + ParameterType_Float, ///< Float parameter, 64bit + ParameterType_String, ///< String parameter + ParameterType_Identifier, ///< Identifier parameter + ParameterType_Matrix, ///< Matrix pointer parameter + ParameterType_StimulationSet, ///< Stimulation set pointer parameter + ParameterType_MemoryBuffer, ///< Memory buffer pointer parameter + ParameterType_Object, ///< Object pointer parameter + ParameterType_Pointer, ///< Raw pointer parameter +}; - /** - * \class IConfigurable - * \brief Configurable object interface - * \author Yann Renard (INRIA/IRISA) - * \date 2007-11-21 - * \sa IParameter - * \ingroup Group_Kernel - * - * An instance of this class is able to self create several type of parameters - * in order to be used by external code. The parameter handling is very abstract - * but its use is made easier thanks to the parameter handler. See IParameter and - * TParameterHandler for more details. - */ - class OV_API IConfigurable : public IKernelObject - { - public: +/** + * \class IConfigurable + * \brief Configurable object interface + * \author Yann Renard (INRIA/IRISA) + * \date 2007-11-21 + * \sa IParameter + * \ingroup Group_Kernel + * + * An instance of this class is able to self create several type of parameters + * in order to be used by external code. The parameter handling is very abstract + * but its use is made easier thanks to the parameter handler. See IParameter and + * TParameterHandler for more details. + */ +class OV_API IConfigurable : public IKernelObject +{ +public: - /** - * \brief Enumerates parameter identifiers for this configurable. - * \param previousID [in] : the identifier which next identifier has to be returned - * \return the parameter identifier following the provided parameter identifier. - * \note if \c previousID is \e OV_UndefinedIdentifier , the first parameter identifier is returned - * \note getting \e OV_UndefinedIdentifier has result means there are no more identifier after \c previousID - * - * Sample code to iterate on parameter identifiers : - * - * \code - * IConfigurable* configurable= // ... - * CIdentifier currentID=OV_UndefinedIdentifier; - * while((currentID=configurable->getNextParameterIdentifier(currentID))!=OV_UndefinedIdentifier) - * { - * IParameter* parameter=configurable->getParameter(currentID); - * // ... - * } - * \endcode - */ - virtual CIdentifier getNextParameterIdentifier(const CIdentifier& previousID) const = 0; + /** + * \brief Enumerates parameter identifiers for this configurable. + * \param previousID [in] : the identifier which next identifier has to be returned + * \return the parameter identifier following the provided parameter identifier. + * \note if \c previousID is \e OV_UndefinedIdentifier , the first parameter identifier is returned + * \note getting \e OV_UndefinedIdentifier has result means there are no more identifier after \c previousID + * + * Sample code to iterate on parameter identifiers : + * + * \code + * IConfigurable* configurable= // ... + * CIdentifier currentID=OV_UndefinedIdentifier; + * while((currentID=configurable->getNextParameterIdentifier(currentID))!=OV_UndefinedIdentifier) + * { + * IParameter* parameter=configurable->getParameter(currentID); + * // ... + * } + * \endcode + */ + virtual CIdentifier getNextParameterIdentifier(const CIdentifier& previousID) const = 0; - /** - * \brief Gets a specific parameter given its id - * \param id [in] : the identifier of the parameter to get - * \return a pointer to the corresponding parameter in case of success. - * \return \c NULL in case of error. - */ - virtual IParameter* getParameter(const CIdentifier& id) = 0; - /** - * \brief Replaces the parameter with a client handled object - * \param id [in] : the identifier of the parameter to replace - * \param parameter [in] : the parameter object to put in place of the old parameter - * \return \e true in case of success. - * \return \e false in case of error. - * \note The parameter should have been created before and should exist. - * \note Even if a new paramter is affected to a configurable, the memory management - * of this parameter remains to the responsability of the client code. Thus - * none of \c removeParameter nor configurable destruction will release - * this parameter object. The caller should take care of this when needed. - */ - virtual bool setParameter(const CIdentifier& id, IParameter& parameter) = 0; - /** - * \brief Creates a new parameter of a specific type - * \param id [in] : the parameter id which has to be created - * \param type [in] : the type of this parameter - * \param subTypeID [in] : the optional sub type of this parameter (e.g. for enumerations) - * \sa EParameterType - * \sa IParameter - * - * This function creates a new parameter with its associated object. - */ - virtual IParameter* createParameter(const CIdentifier& id, const EParameterType type, const CIdentifier& subTypeID = OV_UndefinedIdentifier) = 0; - /** - * \brief Removes an existing parameter - * \param id [in] : the identifier of the parameter to remove - * \return \e true in case of success - * \return \e false in case of error - * \note if the parameter object is not released if it was replaced by a custom - * parameter object thanks to \c setParameter function. - */ - virtual bool removeParameter(const CIdentifier& id) = 0; + /** + * \brief Gets a specific parameter given its id + * \param id [in] : the identifier of the parameter to get + * \return a pointer to the corresponding parameter in case of success. + * \return \c NULL in case of error. + */ + virtual IParameter* getParameter(const CIdentifier& id) = 0; + /** + * \brief Replaces the parameter with a client handled object + * \param id [in] : the identifier of the parameter to replace + * \param parameter [in] : the parameter object to put in place of the old parameter + * \return \e true in case of success. + * \return \e false in case of error. + * \note The parameter should have been created before and should exist. + * \note Even if a new paramter is affected to a configurable, the memory management + * of this parameter remains to the responsability of the client code. Thus + * none of \c removeParameter nor configurable destruction will release + * this parameter object. The caller should take care of this when needed. + */ + virtual bool setParameter(const CIdentifier& id, IParameter& parameter) = 0; + /** + * \brief Creates a new parameter of a specific type + * \param id [in] : the parameter id which has to be created + * \param type [in] : the type of this parameter + * \param subTypeID [in] : the optional sub type of this parameter (e.g. for enumerations) + * \sa EParameterType + * \sa IParameter + * + * This function creates a new parameter with its associated object. + */ + virtual IParameter* createParameter(const CIdentifier& id, const EParameterType type, const CIdentifier& subTypeID = OV_UndefinedIdentifier) = 0; + /** + * \brief Removes an existing parameter + * \param id [in] : the identifier of the parameter to remove + * \return \e true in case of success + * \return \e false in case of error + * \note if the parameter object is not released if it was replaced by a custom + * parameter object thanks to \c setParameter function. + */ + virtual bool removeParameter(const CIdentifier& id) = 0; - _IsDerivedFromClass_(IKernelObject, OV_ClassId_Kernel_Configurable) - }; - } // namespace Kernel -} // namespace OpenViBE + _IsDerivedFromClass_(IKernelObject, OV_ClassId_Kernel_Configurable) +}; +} // namespace Kernel +} // namespace OpenViBE diff --git a/openvibe/include/openvibe/kernel/ovIKernelContext.h b/openvibe/include/openvibe/kernel/ovIKernelContext.h index b7913a8c05fbd13fc10f22dfe136f822893ffd73..e18c01a7f945644cf5d26030e812b9910602fc61 100755 --- a/openvibe/include/openvibe/kernel/ovIKernelContext.h +++ b/openvibe/include/openvibe/kernel/ovIKernelContext.h @@ -2,106 +2,104 @@ #include "ovIKernelObject.h" -namespace OpenViBE -{ - namespace Kernel - { - class IAlgorithmManager; - class IConfigurationManager; - class IKernelObjectFactory; - class IPlayerManager; - class IPluginManager; - class IMetaboxManager; - class IScenarioManager; - class ITypeManager; - class ILogManager; - class IErrorManager; +namespace OpenViBE { +namespace Kernel { +class IAlgorithmManager; +class IConfigurationManager; +class IKernelObjectFactory; +class IPlayerManager; +class IPluginManager; +class IMetaboxManager; +class IScenarioManager; +class ITypeManager; +class ILogManager; +class IErrorManager; - /** - * \class IKernelContext - * \brief Kernel context interface, gives access to each manager the kernel owns - * \author Yann Renard (INRIA/IRISA) - * \date 2007-10-24 - * - * This class simply provides access to each manager the kernel owns. This is the top - * level object that can be used by a custom OpenViBE application and this is the common - * object all kernel object have in order to access all the functionnalities. - * - * See each manager's own documentation for more detail on a specific manager goal and usage. - */ - class OV_API IKernelContext : public IKernelObject - { - public: +/** + * \class IKernelContext + * \brief Kernel context interface, gives access to each manager the kernel owns + * \author Yann Renard (INRIA/IRISA) + * \date 2007-10-24 + * + * This class simply provides access to each manager the kernel owns. This is the top + * level object that can be used by a custom OpenViBE application and this is the common + * object all kernel object have in order to access all the functionnalities. + * + * See each manager's own documentation for more detail on a specific manager goal and usage. + */ +class OV_API IKernelContext : public IKernelObject +{ +public: - /** - * \brief Initializes the kernel context - * \return \e true in case of success - * \return \e false in case of error - */ - virtual bool initialize(const char* const* /*tokenList*/ = nullptr, size_t /*tokenCount*/ = 0) { return true; } - /** - * \brief Uninitializes the kernel context - * \return \e true in case of success - * \return \e false in case of error - */ - virtual bool uninitialize() { return true; } + /** + * \brief Initializes the kernel context + * \return \e true in case of success + * \return \e false in case of error + */ + virtual bool initialize(const char* const* /*tokenList*/ = nullptr, size_t /*tokenCount*/ = 0) { return true; } + /** + * \brief Uninitializes the kernel context + * \return \e true in case of success + * \return \e false in case of error + */ + virtual bool uninitialize() { return true; } - /** - * \brief Gets a reference on the kernel's algorithm manager - * \return a reference on the kernel's algorithm manager - */ - virtual IAlgorithmManager& getAlgorithmManager() const = 0; - /** - * \brief Gets a reference on the kernel's configuration manager - * \return a reference on the kernel's configuration manager - */ - virtual IConfigurationManager& getConfigurationManager() const = 0; - /** - * \brief Gets a reference on the kernel's player manager - * \return a reference on the kernel's player manager - */ - virtual IPlayerManager& getPlayerManager() const = 0; - /** - * \brief Gets a reference on the kernel's plugin manager - * \return a reference on the kernel's plugin manager - */ - virtual IPluginManager& getPluginManager() const = 0; - /** - * \brief Gets a reference on the kernel's metabox manager - * \return a reference on the kernel's metabox manager - */ - virtual IMetaboxManager& getMetaboxManager() const = 0; - /** - * \brief Gets a reference on the kernel's object factory - * \return a reference on the kernel's object factory - */ - virtual IKernelObjectFactory& getKernelObjectFactory() const = 0; - /** - * \brief Gets a reference on the kernel's scenario manager - * \return a reference on the kernel's scenario manager - */ - virtual IScenarioManager& getScenarioManager() const = 0; - /** - * \brief Gets a reference on the kernel's type manager - * \return a reference on the kernel's type manager - */ - virtual ITypeManager& getTypeManager() const = 0; - /** - * \brief Gets a reference on the kernel's log manager - * \return a reference on the kernel's log manager - */ - virtual ILogManager& getLogManager() const = 0; - /** - * \brief Gets a reference on the kernel's error manager - * \return a reference on the kernel's error manager - */ - virtual IErrorManager& getErrorManager() const = 0; + /** + * \brief Gets a reference on the kernel's algorithm manager + * \return a reference on the kernel's algorithm manager + */ + virtual IAlgorithmManager& getAlgorithmManager() const = 0; + /** + * \brief Gets a reference on the kernel's configuration manager + * \return a reference on the kernel's configuration manager + */ + virtual IConfigurationManager& getConfigurationManager() const = 0; + /** + * \brief Gets a reference on the kernel's player manager + * \return a reference on the kernel's player manager + */ + virtual IPlayerManager& getPlayerManager() const = 0; + /** + * \brief Gets a reference on the kernel's plugin manager + * \return a reference on the kernel's plugin manager + */ + virtual IPluginManager& getPluginManager() const = 0; + /** + * \brief Gets a reference on the kernel's metabox manager + * \return a reference on the kernel's metabox manager + */ + virtual IMetaboxManager& getMetaboxManager() const = 0; + /** + * \brief Gets a reference on the kernel's object factory + * \return a reference on the kernel's object factory + */ + virtual IKernelObjectFactory& getKernelObjectFactory() const = 0; + /** + * \brief Gets a reference on the kernel's scenario manager + * \return a reference on the kernel's scenario manager + */ + virtual IScenarioManager& getScenarioManager() const = 0; + /** + * \brief Gets a reference on the kernel's type manager + * \return a reference on the kernel's type manager + */ + virtual ITypeManager& getTypeManager() const = 0; + /** + * \brief Gets a reference on the kernel's log manager + * \return a reference on the kernel's log manager + */ + virtual ILogManager& getLogManager() const = 0; + /** + * \brief Gets a reference on the kernel's error manager + * \return a reference on the kernel's error manager + */ + virtual IErrorManager& getErrorManager() const = 0; - // backward compatibility - virtual IKernelObjectFactory& getObjectFactory() const { return getKernelObjectFactory(); } + // backward compatibility + virtual IKernelObjectFactory& getObjectFactory() const { return getKernelObjectFactory(); } - _IsDerivedFromClass_(IKernelObject, OV_ClassId_Kernel_KernelContext) - }; - } // namespace Kernel -} // namespace OpenViBE + _IsDerivedFromClass_(IKernelObject, OV_ClassId_Kernel_KernelContext) +}; +} // namespace Kernel +} // namespace OpenViBE diff --git a/openvibe/include/openvibe/kernel/ovIKernelDesc.h b/openvibe/include/openvibe/kernel/ovIKernelDesc.h index 156ee33564d9a8d980b21031cefd34eca0fb5c42..d5e9bfe9ccf1e278a8b24c220526180eaf1fd8c9 100644 --- a/openvibe/include/openvibe/kernel/ovIKernelDesc.h +++ b/openvibe/include/openvibe/kernel/ovIKernelDesc.h @@ -2,114 +2,112 @@ #include "ovIKernelObject.h" -namespace OpenViBE -{ - namespace Kernel - { - class IKernelContext; +namespace OpenViBE { +namespace Kernel { +class IKernelContext; - /** - * \class IKernelDesc - * \brief A kernel description - * \author Yann Renard (INRIA/IRISA) - * \date 2006-09-26 - * \ingroup Group_Kernel - * - * This interface is implemented to provide information on a specific kernel - * implementation and to create instances of this specific kernel implementation. - */ - class OV_API IKernelDesc : public IKernelObject - { - public: +/** + * \class IKernelDesc + * \brief A kernel description + * \author Yann Renard (INRIA/IRISA) + * \date 2006-09-26 + * \ingroup Group_Kernel + * + * This interface is implemented to provide information on a specific kernel + * implementation and to create instances of this specific kernel implementation. + */ +class OV_API IKernelDesc : public IKernelObject +{ +public: - /** \name Creation process */ - //@{ + /** \name Creation process */ + //@{ - /** - * \brief Creates the kernel itself - * \param applicationName [in] : the name of the application requesting kernel creation - * (an configuration token will be created so the configuration - * file can be tweaked according to the targeted application) - * \param configFilename [in] : a bootstrap configuration file - * \return the created kernel. - * - * This method creates the kernel itself and returns it. - */ - virtual IKernelContext* createKernel(const CString& applicationName, const CString& configFilename) = 0; - /** - * \brief Creates the kernel itself and make it sub kernel of a master kernel - * \param masterKernel [in] : the master kernel - * \param applicationName [in] : the name of the application requesting kernel creation - * (an configuration token will be created so the configuration - * file can be tweaked according to the targeted application) - * \param configFilename [in] : a bootstrap configuration file - * \return the created kernel. - * - * This method creates the kernel itself and returns it. - */ - virtual IKernelContext* createKernel(const IKernelContext& masterKernel, const CString& applicationName, - const CString& configFilename) = 0; - /** - * \brief Releases the kernel itself - * \param kernel [in] : the kernel to release - * - * This method releases an existing kernel. - */ - virtual void releaseKernel(IKernelContext* kernel) = 0; + /** + * \brief Creates the kernel itself + * \param applicationName [in] : the name of the application requesting kernel creation + * (an configuration token will be created so the configuration + * file can be tweaked according to the targeted application) + * \param configFilename [in] : a bootstrap configuration file + * \return the created kernel. + * + * This method creates the kernel itself and returns it. + */ + virtual IKernelContext* createKernel(const CString& applicationName, const CString& configFilename) = 0; + /** + * \brief Creates the kernel itself and make it sub kernel of a master kernel + * \param masterKernel [in] : the master kernel + * \param applicationName [in] : the name of the application requesting kernel creation + * (an configuration token will be created so the configuration + * file can be tweaked according to the targeted application) + * \param configFilename [in] : a bootstrap configuration file + * \return the created kernel. + * + * This method creates the kernel itself and returns it. + */ + virtual IKernelContext* createKernel(const IKernelContext& masterKernel, const CString& applicationName, + const CString& configFilename) = 0; + /** + * \brief Releases the kernel itself + * \param kernel [in] : the kernel to release + * + * This method releases an existing kernel. + */ + virtual void releaseKernel(IKernelContext* kernel) = 0; - //@} - /** \name Textual plugin object description and information */ - //@{ + //@} + /** \name Textual plugin object description and information */ + //@{ - /** - * \brief Gets the plugin name - * \return The plugin name. - * - * Default implementation simply returns empty string. - */ - virtual CString getName() const { return CString("no name"); } - /** - * \brief Gets the author name for this plugin - * \return The author name for this plugin. - * - * Default implementation simply returns empty string. - */ - virtual CString getAuthorName() const { return CString("unknown"); } - /** - * \brief Gets the author company name for this plugin - * \return The author company name for this plugin. - * - * Default implementation simply returns empty string. - */ - virtual CString getAuthorCompanyName() const { return CString("unknown"); } - /** - * \brief Gets a short description of the plugin - * \return A short description of the plugin. - * - * Default implementation simply returns empty string. - */ - virtual CString getShortDescription() const { return CString(""); } - /** - * \brief Gets a detailed description of the plugin - * \return A detailed description of the plugin. - * - * Default implementation simply returns empty string. - * - * \note You can use std::endl to have the description - * on several lines when needed. - */ - virtual CString getDetailedDescription() const { return CString(""); } - /** - * \brief Gets the version of the plugin - * \return the version of the plugin. - * - * Default implementation simply returns empty string. - */ - virtual CString getVersion() const { return CString("unknown"); } + /** + * \brief Gets the plugin name + * \return The plugin name. + * + * Default implementation simply returns empty string. + */ + virtual CString getName() const { return CString("no name"); } + /** + * \brief Gets the author name for this plugin + * \return The author name for this plugin. + * + * Default implementation simply returns empty string. + */ + virtual CString getAuthorName() const { return CString("unknown"); } + /** + * \brief Gets the author company name for this plugin + * \return The author company name for this plugin. + * + * Default implementation simply returns empty string. + */ + virtual CString getAuthorCompanyName() const { return CString("unknown"); } + /** + * \brief Gets a short description of the plugin + * \return A short description of the plugin. + * + * Default implementation simply returns empty string. + */ + virtual CString getShortDescription() const { return CString(""); } + /** + * \brief Gets a detailed description of the plugin + * \return A detailed description of the plugin. + * + * Default implementation simply returns empty string. + * + * \note You can use std::endl to have the description + * on several lines when needed. + */ + virtual CString getDetailedDescription() const { return CString(""); } + /** + * \brief Gets the version of the plugin + * \return the version of the plugin. + * + * Default implementation simply returns empty string. + */ + virtual CString getVersion() const { return CString("unknown"); } - //@} + //@} - _IsDerivedFromClass_(IKernelObject, OV_ClassId_Kernel_KernelDesc) - }; - } // namespace Kernel -} // namespace OpenViBE + _IsDerivedFromClass_(IKernelObject, OV_ClassId_Kernel_KernelDesc) +}; +} // namespace Kernel +} // namespace OpenViBE diff --git a/openvibe/include/openvibe/kernel/ovIKernelObject.h b/openvibe/include/openvibe/kernel/ovIKernelObject.h index 70ac56709be12f9487537028f01ceff1d285b200..19c4204a1abdfe386e5264ae5822229bbe941196 100644 --- a/openvibe/include/openvibe/kernel/ovIKernelObject.h +++ b/openvibe/include/openvibe/kernel/ovIKernelObject.h @@ -2,22 +2,20 @@ #include "../ovIObject.h" -namespace OpenViBE +namespace OpenViBE { +namespace Kernel { +/** + * \class IKernelObject + * \brief Base class for all kernel objects + * \author Yann Renard (INRIA/IRISA) + * \date 2006-09-26 + * \ingroup Group_Kernel + */ +class OV_API IKernelObject : public IObject { - namespace Kernel - { - /** - * \class IKernelObject - * \brief Base class for all kernel objects - * \author Yann Renard (INRIA/IRISA) - * \date 2006-09-26 - * \ingroup Group_Kernel - */ - class OV_API IKernelObject : public IObject - { - public: +public: - _IsDerivedFromClass_(IObject, OV_ClassId_Kernel_KernelObject) - }; - } // namespace Kernel -} // namespace OpenViBE + _IsDerivedFromClass_(IObject, OV_ClassId_Kernel_KernelObject) +}; +} // namespace Kernel +} // namespace OpenViBE diff --git a/openvibe/include/openvibe/kernel/ovIKernelObjectFactory.h b/openvibe/include/openvibe/kernel/ovIKernelObjectFactory.h index dff33b0930cbb7619f6e4b7cc1b77cfcb997265d..2efa755633d2e4df738bc0118921da6f75563223 100644 --- a/openvibe/include/openvibe/kernel/ovIKernelObjectFactory.h +++ b/openvibe/include/openvibe/kernel/ovIKernelObjectFactory.h @@ -2,42 +2,40 @@ #include "ovIKernelObject.h" -namespace OpenViBE +namespace OpenViBE { +namespace Kernel { +/** + * \class IKernelObjectFactory + * \brief Kernel object factory, creates all kernel objects + * \author Yann Renard (INRIA/IRISA) + * \date 2006-09-26 + * \ingroup Group_Kernel + * + * This class allows to create kernel objects as needed. + * + * \todo should it be removed ? + */ +class OV_API IKernelObjectFactory : public IKernelObject { - namespace Kernel - { - /** - * \class IKernelObjectFactory - * \brief Kernel object factory, creates all kernel objects - * \author Yann Renard (INRIA/IRISA) - * \date 2006-09-26 - * \ingroup Group_Kernel - * - * This class allows to create kernel objects as needed. - * - * \todo should it be removed ? - */ - class OV_API IKernelObjectFactory : public IKernelObject - { - public: +public: - /** - * \brief Creates a new kernel object givent its class identifier - * \param classID [in] : the class identifier of the object to create - * \return a pointer on the created object in case of success. - * \return \c NULL in case of error. - */ - virtual IObject* createObject(const CIdentifier& classID) = 0; - /** - * \brief Releases an object created by this factory - * \param obj [in] : the object to release - * \return \e true in case of success. - * \return \e false in case of error. - * \note The factory should have created the object in order to release it. - */ - virtual bool releaseObject(IObject* obj) = 0; + /** + * \brief Creates a new kernel object givent its class identifier + * \param classID [in] : the class identifier of the object to create + * \return a pointer on the created object in case of success. + * \return \c NULL in case of error. + */ + virtual IObject* createObject(const CIdentifier& classID) = 0; + /** + * \brief Releases an object created by this factory + * \param obj [in] : the object to release + * \return \e true in case of success. + * \return \e false in case of error. + * \note The factory should have created the object in order to release it. + */ + virtual bool releaseObject(IObject* obj) = 0; - _IsDerivedFromClass_(IKernelObject, OV_ClassId_Kernel_KernelObjectFactory) - }; - } // namespace Kernel -} // namespace OpenViBE + _IsDerivedFromClass_(IKernelObject, OV_ClassId_Kernel_KernelObjectFactory) +}; +} // namespace Kernel +} // namespace OpenViBE diff --git a/openvibe/include/openvibe/kernel/ovIObjectVisitorContext.h b/openvibe/include/openvibe/kernel/ovIObjectVisitorContext.h index 73c7856bff4fcf62d0e6bff43ef7bec28d3d81f4..db62e168ce0b59a77f505b5799a9e59ee51bdff8 100644 --- a/openvibe/include/openvibe/kernel/ovIObjectVisitorContext.h +++ b/openvibe/include/openvibe/kernel/ovIObjectVisitorContext.h @@ -2,48 +2,46 @@ #include "ovIKernelObject.h" -namespace OpenViBE +namespace OpenViBE { +namespace Kernel { +/** + * \class IObjectVisitorContext + * \author Yann Renard (INRIA/IRISA) + * \date 2008-02-01 + * \brief Exectution context for visitor objects + * \ingroup Group_Kernel + */ +class OV_API IObjectVisitorContext : public IKernelObject { - namespace Kernel - { - /** - * \class IObjectVisitorContext - * \author Yann Renard (INRIA/IRISA) - * \date 2008-02-01 - * \brief Exectution context for visitor objects - * \ingroup Group_Kernel - */ - class OV_API IObjectVisitorContext : public IKernelObject - { - public: +public: - /** - * \brief Gets a reference on the current algorithm manager - * \return a reference on the current algorithm manager - */ - virtual IAlgorithmManager& getAlgorithmManager() const = 0; - /** - * \brief Gets a reference on the current configuration manager - * \return a reference on the current configuration manager - */ - virtual IConfigurationManager& getConfigurationManager() const = 0; - /** - * \brief Gets a reference on the current type manager - * \return a reference on the current type manager - */ - virtual ITypeManager& getTypeManager() const = 0; - /** - * \brief Gets a reference on the current log manager - * \return a reference on the current log manager - */ - virtual ILogManager& getLogManager() const = 0; - /** - * \brief Gets a reference on the current error manager - * \return a reference on the current error manager - */ - virtual IErrorManager& getErrorManager() const = 0; + /** + * \brief Gets a reference on the current algorithm manager + * \return a reference on the current algorithm manager + */ + virtual IAlgorithmManager& getAlgorithmManager() const = 0; + /** + * \brief Gets a reference on the current configuration manager + * \return a reference on the current configuration manager + */ + virtual IConfigurationManager& getConfigurationManager() const = 0; + /** + * \brief Gets a reference on the current type manager + * \return a reference on the current type manager + */ + virtual ITypeManager& getTypeManager() const = 0; + /** + * \brief Gets a reference on the current log manager + * \return a reference on the current log manager + */ + virtual ILogManager& getLogManager() const = 0; + /** + * \brief Gets a reference on the current error manager + * \return a reference on the current error manager + */ + virtual IErrorManager& getErrorManager() const = 0; - _IsDerivedFromClass_(IKernelObject, OV_ClassId_Kernel_ObjectVisitorContext) - }; - } // namespace Kernel -} // namespace OpenViBE + _IsDerivedFromClass_(IKernelObject, OV_ClassId_Kernel_ObjectVisitorContext) +}; +} // namespace Kernel +} // namespace OpenViBE diff --git a/openvibe/include/openvibe/kernel/ovIParameter.h b/openvibe/include/openvibe/kernel/ovIParameter.h index 810f5adf73f9c26f2b7460711b0480fdc2f2c169..be959b2750a6254598ad919e771ad32a5b7b8340 100644 --- a/openvibe/include/openvibe/kernel/ovIParameter.h +++ b/openvibe/include/openvibe/kernel/ovIParameter.h @@ -3,141 +3,139 @@ #include "ovIKernelObject.h" #include "ovIConfigurable.h" -namespace OpenViBE +namespace OpenViBE { +namespace Kernel { +/** + * \class IParameter + * \brief Generic parameter handler for configurable objects + * \author Yann Renard (INRIA/IRISA) + * \date 2007-11-21 + * \ingroup Group_Kernel + * \sa IConfigurable + * \sa EParameterType + * \sa TParameterHandler + * + * Instances of this interface encapsulate a specific type of object as a + * so called "parameter". The idea behind this parameter interface is to allow + * to override the parameter content directly pointing to another parameter + * or another value. In order to be as generic as possible, this interface + * uses \c void* pointers in conjunction with data size values. It can be + * hard/tricky to understand for unexperienced developers. Thus I recommend + * the use of the TParameterHandler object which dramatically eases the use + * of the IParameter interface. + */ +class OV_API IParameter : public IKernelObject { - namespace Kernel - { - /** - * \class IParameter - * \brief Generic parameter handler for configurable objects - * \author Yann Renard (INRIA/IRISA) - * \date 2007-11-21 - * \ingroup Group_Kernel - * \sa IConfigurable - * \sa EParameterType - * \sa TParameterHandler - * - * Instances of this interface encapsulate a specific type of object as a - * so called "parameter". The idea behind this parameter interface is to allow - * to override the parameter content directly pointing to another parameter - * or another value. In order to be as generic as possible, this interface - * uses \c void* pointers in conjunction with data size values. It can be - * hard/tricky to understand for unexperienced developers. Thus I recommend - * the use of the TParameterHandler object which dramatically eases the use - * of the IParameter interface. - */ - class OV_API IParameter : public IKernelObject - { - public: +public: - /** \name information */ - //@{ + /** \name information */ + //@{ - /** - * \brief Gets the size of this parameter's content - * \return the size of this parameter's content. - */ - virtual uint64_t getParameterSize() const { return 0; } - /** - * \brief Gets the type of this parameter's content - * \return the type of this parameter's content. - */ - virtual EParameterType getType() const { return ParameterType_None; } - /** - * \brief Gets the sub type of this parameter's content (e.g. for enumeration) - * \return the sub type of this parameter's content (e.g. for enumeration). - */ - virtual CIdentifier getSubTypeIdentifier() const { return OV_UndefinedIdentifier; } + /** + * \brief Gets the size of this parameter's content + * \return the size of this parameter's content. + */ + virtual uint64_t getParameterSize() const { return 0; } + /** + * \brief Gets the type of this parameter's content + * \return the type of this parameter's content. + */ + virtual EParameterType getType() const { return ParameterType_None; } + /** + * \brief Gets the sub type of this parameter's content (e.g. for enumeration) + * \return the sub type of this parameter's content (e.g. for enumeration). + */ + virtual CIdentifier getSubTypeIdentifier() const { return OV_UndefinedIdentifier; } - //@} - /** \name Reinitialization */ - //@{ + //@} + /** \name Reinitialization */ + //@{ - /** - * \brief Clears all reference targets for this paramter - * \return \e true in case of success. - * \return \e false in case of error. - * \sa getReferenceTarget - * \sa setReferenceTarget - */ - virtual bool clearReferenceTarget() { return false; } + /** + * \brief Clears all reference targets for this paramter + * \return \e true in case of success. + * \return \e false in case of error. + * \sa getReferenceTarget + * \sa setReferenceTarget + */ + virtual bool clearReferenceTarget() { return false; } - //@} - /** \name Reference target management */ - //@{ + //@} + /** \name Reference target management */ + //@{ - /** - * \brief Gets the parameter reference target - * \param value [out] : a pointer to the reference target parameter if existing, \c NULL if not - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool getReferenceTarget(IParameter*& value) const { return false; } - /** - * \brief Sets the parameter reference target for this parameter - * \param value [in] : the new reference target to use - * \return \e true in case of success. - * \return \e false in case of error. - * \note Setting \c NULL simply removes the parameter reference target - * \warning calling this function overrives previous value reference target ! - * - * After this function has been called, any call to \c getValue or \c setValue will be - * directly redirected to the specified reference target parameter. The internal value - * handled by this parameter won't be affected anymore until the reference target is - * cleared. - */ - virtual bool setReferenceTarget(IParameter* value) { return false; } - /** - * \brief Gets the value reference target - * \param value [out] : a pointer to the value target parameter if existing, \c NULL if not - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool getReferenceTarget(void* value) const { return false; } - /** - * \brief Sets the value reference target for this parameter - * \param value [in] : the new reference target to use - * \return \e true in case of success. - * \return \e false in case of error. - * \note Setting \c NULL simply removes the value reference target - * \warning calling this function overrives previous parameter reference target ! - * - * After this function has been called, any call to \c getValue or \c setValue will be - * directly redirected to the specified value reference target. The internal value - * handled by this parameter won't be affected anymore until the reference target is - * cleared. - */ - virtual bool setReferenceTarget(const void* value) { return false; } + /** + * \brief Gets the parameter reference target + * \param value [out] : a pointer to the reference target parameter if existing, \c NULL if not + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool getReferenceTarget(IParameter*& value) const { return false; } + /** + * \brief Sets the parameter reference target for this parameter + * \param value [in] : the new reference target to use + * \return \e true in case of success. + * \return \e false in case of error. + * \note Setting \c NULL simply removes the parameter reference target + * \warning calling this function overrives previous value reference target ! + * + * After this function has been called, any call to \c getValue or \c setValue will be + * directly redirected to the specified reference target parameter. The internal value + * handled by this parameter won't be affected anymore until the reference target is + * cleared. + */ + virtual bool setReferenceTarget(IParameter* value) { return false; } + /** + * \brief Gets the value reference target + * \param value [out] : a pointer to the value target parameter if existing, \c NULL if not + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool getReferenceTarget(void* value) const { return false; } + /** + * \brief Sets the value reference target for this parameter + * \param value [in] : the new reference target to use + * \return \e true in case of success. + * \return \e false in case of error. + * \note Setting \c NULL simply removes the value reference target + * \warning calling this function overrives previous parameter reference target ! + * + * After this function has been called, any call to \c getValue or \c setValue will be + * directly redirected to the specified value reference target. The internal value + * handled by this parameter won't be affected anymore until the reference target is + * cleared. + */ + virtual bool setReferenceTarget(const void* value) { return false; } - //@} - /** \name Value access */ - //@{ + //@} + /** \name Value access */ + //@{ - /** - * \brief Gets the value for this parameter - * \param value [out] : a pointer to where the value should be copied - * \return \e true in case of success. - * \return \e false in case of error. - * \note the function assumes enough memory has been allocated in \c value to - * copy the value itself. - * \note if a parameter or value reference target has been created, then - * either this target's \c getValue is automatically called, either - * the value target is directly copied - * \sa getParameterSize - */ - virtual bool getValue(void* value) const { return false; } - /** - * \brief Sets the value for this parameter - * \param value [in] : a pointer from where the value should be copied - * \return \e true in case of success. - * \return \e false in case of error. - * \sa getParameterSize - */ - virtual bool setValue(const void* value) { return false; } + /** + * \brief Gets the value for this parameter + * \param value [out] : a pointer to where the value should be copied + * \return \e true in case of success. + * \return \e false in case of error. + * \note the function assumes enough memory has been allocated in \c value to + * copy the value itself. + * \note if a parameter or value reference target has been created, then + * either this target's \c getValue is automatically called, either + * the value target is directly copied + * \sa getParameterSize + */ + virtual bool getValue(void* value) const { return false; } + /** + * \brief Sets the value for this parameter + * \param value [in] : a pointer from where the value should be copied + * \return \e true in case of success. + * \return \e false in case of error. + * \sa getParameterSize + */ + virtual bool setValue(const void* value) { return false; } - //@} + //@} - _IsDerivedFromClass_(IKernelObject, OV_ClassId_Kernel_Parameter) - }; - } // namespace Kernel -} // namespace OpenViBE + _IsDerivedFromClass_(IKernelObject, OV_ClassId_Kernel_Parameter) +}; +} // namespace Kernel +} // namespace OpenViBE diff --git a/openvibe/include/openvibe/kernel/ovITypeManager.h b/openvibe/include/openvibe/kernel/ovITypeManager.h index 8cb0a7af7d63d1ac410233478138d47217548142..982121af25edc7b719651e61d43d1faa0c9730b8 100644 --- a/openvibe/include/openvibe/kernel/ovITypeManager.h +++ b/openvibe/include/openvibe/kernel/ovITypeManager.h @@ -3,289 +3,287 @@ #include "ovIKernelObject.h" #include <vector> -namespace OpenViBE +namespace OpenViBE { +namespace Kernel { +/** + * \class ITypeManager + * \brief Type manager, provides information on platform's handled types, parameters, streams etc... + * \author Yann Renard (INRIA/IRISA) + * \date 2007-03-14 + * + * This manager concentrates all information about types in the OpenViBE + * platform. Any non-standard type should be declared in the type identifier + * by the kernel or the plugins in order to be used. Registered types range + * from box settings to streams, eventually including inter-type auto casts. + * + * See the different functions for more details. + */ +class OV_API ITypeManager : public IKernelObject { - namespace Kernel - { - /** - * \class ITypeManager - * \brief Type manager, provides information on platform's handled types, parameters, streams etc... - * \author Yann Renard (INRIA/IRISA) - * \date 2007-03-14 - * - * This manager concentrates all information about types in the OpenViBE - * platform. Any non-standard type should be declared in the type identifier - * by the kernel or the plugins in order to be used. Registered types range - * from box settings to streams, eventually including inter-type auto casts. - * - * See the different functions for more details. - */ - class OV_API ITypeManager : public IKernelObject - { - public: +public: - /** \name Type registration */ - //@{ + /** \name Type registration */ + //@{ - /** - * \brief Gets next type identifier - * \param previousID [in] : The identifier - * for the preceeding type - * \return The identifier of the next type in case of success. - * \return \c OV_UndefinedIdentifier on error. - * \note Giving \c OV_UndefinedIdentifier as \c previousID - * will cause this function to return the first type - * identifier. - */ - virtual CIdentifier getNextTypeIdentifier(const CIdentifier& previousID) const = 0; - - /** - * \brief Get a sorted vector of pairs of registered types identifiers associated to types names, - * sorted by type name in increasing alphabetical order. - * \return the sorted vector - */ - virtual std::vector<std::pair<CIdentifier, CString>> getSortedTypes() const = 0; - - /** - * \brief Registers a new simple type of data - * \param typeID [in] : the identifier for this type - * \param name [in] : the name for this type - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool registerType(const CIdentifier& typeID, const CString& name) = 0; - /** - * \brief Registers a new communication stream type - * \param typeID [in] : the identifier for this type - * \param name [in] : the name for this type - * \param parentTypeID [in] : the parent stream type identifier - * \return \e true in case of success. - * \return \e false in case of error. - * - * Stream types are organized as a hierarchy, meaning that any - * derived stream should at least contain the parent stream content, - * plus other informations. This will be used by applications in order - * to determine what stream is compatible with what other stream and - * to allow box connections or not. - */ - virtual bool registerStreamType(const CIdentifier& typeID, const CString& name, const CIdentifier& parentTypeID) = 0; - /** - * \brief Registers a new enumeration type - * \param typeID [in] : the type identifier for this type - * \param name [in] : the name for this type - * \return \e true in case of success. - * \return \e false in case of error. - * \sa registerEnumerationEntry - * - * An enumeration should have several possible values. - * This values have to be created thanks to \c registerEnumerationEntry - */ - virtual bool registerEnumerationType(const CIdentifier& typeID, const CString& name) = 0; - /** - * \brief Registers a new enumeration value for a given enumeration type - * \param typeID [in] : the type identifier of the enumeration which new entry has to be registered - * \param name [in] : the name of the entry to register - * \param value [in] : the value of the entry to register - * \return \e true in case of success. - * \return \e false in case of error. - * \note the enumeration has to be registered - * \sa registerEnumerationType - */ - virtual bool registerEnumerationEntry(const CIdentifier& typeID, const CString& name, uint64_t value) = 0; + /** + * \brief Gets next type identifier + * \param previousID [in] : The identifier + * for the preceeding type + * \return The identifier of the next type in case of success. + * \return \c OV_UndefinedIdentifier on error. + * \note Giving \c OV_UndefinedIdentifier as \c previousID + * will cause this function to return the first type + * identifier. + */ + virtual CIdentifier getNextTypeIdentifier(const CIdentifier& previousID) const = 0; - /** - * \brief Registers a new bitmask type - * \param typeID [in] : the type identifier for this type - * \param name [in] : the name for this type - * \return \e true in case of success. - * \return \e false in case of error. - * \sa registerBitMaskEntry - * - * A bitmask should have several possible values. - * This values have to be created thanks to \c registerBitMaskEntry - */ - virtual bool registerBitMaskType(const CIdentifier& typeID, const CString& name) = 0; - /** - * \brief Registers a new bitmask value for a given bitmask type - * \param typeID [in] : the type identifier of the bitmask which new entry has to be registered - * \param name [in] : the name of the entry to register - * \param value [in] : the value of the entry to register - * \return \e true in case of success. - * \return \e false in case of error. - * \note the bitmask has to be registered - * \sa registerBitMaskType - */ - virtual bool registerBitMaskEntry(const CIdentifier& typeID, const CString& name, uint64_t value) = 0; + /** + * \brief Get a sorted vector of pairs of registered types identifiers associated to types names, + * sorted by type name in increasing alphabetical order. + * \return the sorted vector + */ + virtual std::vector<std::pair<CIdentifier, CString>> getSortedTypes() const = 0; - //@} - /** \name Registration verification */ - //@{ + /** + * \brief Registers a new simple type of data + * \param typeID [in] : the identifier for this type + * \param name [in] : the name for this type + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool registerType(const CIdentifier& typeID, const CString& name) = 0; + /** + * \brief Registers a new communication stream type + * \param typeID [in] : the identifier for this type + * \param name [in] : the name for this type + * \param parentTypeID [in] : the parent stream type identifier + * \return \e true in case of success. + * \return \e false in case of error. + * + * Stream types are organized as a hierarchy, meaning that any + * derived stream should at least contain the parent stream content, + * plus other informations. This will be used by applications in order + * to determine what stream is compatible with what other stream and + * to allow box connections or not. + */ + virtual bool registerStreamType(const CIdentifier& typeID, const CString& name, const CIdentifier& parentTypeID) = 0; + /** + * \brief Registers a new enumeration type + * \param typeID [in] : the type identifier for this type + * \param name [in] : the name for this type + * \return \e true in case of success. + * \return \e false in case of error. + * \sa registerEnumerationEntry + * + * An enumeration should have several possible values. + * This values have to be created thanks to \c registerEnumerationEntry + */ + virtual bool registerEnumerationType(const CIdentifier& typeID, const CString& name) = 0; + /** + * \brief Registers a new enumeration value for a given enumeration type + * \param typeID [in] : the type identifier of the enumeration which new entry has to be registered + * \param name [in] : the name of the entry to register + * \param value [in] : the value of the entry to register + * \return \e true in case of success. + * \return \e false in case of error. + * \note the enumeration has to be registered + * \sa registerEnumerationType + */ + virtual bool registerEnumerationEntry(const CIdentifier& typeID, const CString& name, uint64_t value) = 0; - /** - * \brief Tests if a specific type has been registered - * \param typeID [in] : the type identifier which registration has to be tested - * \return \e true if the specified type has been registered. - * \return \e false if the specified type has not been registered. - */ - virtual bool isRegistered(const CIdentifier& typeID) const = 0; - /** - * \brief Tests if a specific type has been registered and is a stream - * \param typeID [in] : the type identifier which registration has to be tested - * \return \e true if the specified type has been registered is a stream. - * \return \e false if the specified type has not been registered or is not a stream. - */ - virtual bool isStream(const CIdentifier& typeID) const = 0; - /** - * \brief Tests is a specific type has been registered, is a stream and is derived from another registered stream type - * \param typeID [in] : the type identifier which registration and derivation has to be tested - * \param parentTypeID [in] : the type identifier of the supposed parent stream - * \return \e true in case \c typeID is registered as a stream type and derived from \c parentTypeID - * \return \e false in case \c parentTypeID is not registered - * \return \e false in case \c parentTypeID is not a stream - * \return \e false in case \c typeID is not registered - * \return \e false in case \c typeID is not a stream - * \return \e false in case \c typeID is not derived from parentTypeID - * \note The derivation can be indirect (\c typeID can derive an - * intermediate stream type which derives \c parentTypeID) - */ - virtual bool isDerivedFromStream(const CIdentifier& typeID, const CIdentifier& parentTypeID) const = 0; - /** - * \brief Tests if a specific type has been registered and is an enumeration - * \param typeID [in] : the type identifier which registration has to be tested - * \return \e true if the specified type has been registered and is an enumeration. - * \return \e false if the specified type has not been registered or is not an enumeration. - */ - virtual bool isEnumeration(const CIdentifier& typeID) const = 0; - /** - * \brief Tests if a specific type has been registered and is a bitmask - * \param typeID [in] : the type identifier which registration has to be tested - * \return \e true if the specified type has been registered and is a bitmask. - * \return \e false if the specified type has not been registered or is not a bitmask. - */ - virtual bool isBitMask(const CIdentifier& typeID) const = 0; + /** + * \brief Registers a new bitmask type + * \param typeID [in] : the type identifier for this type + * \param name [in] : the name for this type + * \return \e true in case of success. + * \return \e false in case of error. + * \sa registerBitMaskEntry + * + * A bitmask should have several possible values. + * This values have to be created thanks to \c registerBitMaskEntry + */ + virtual bool registerBitMaskType(const CIdentifier& typeID, const CString& name) = 0; + /** + * \brief Registers a new bitmask value for a given bitmask type + * \param typeID [in] : the type identifier of the bitmask which new entry has to be registered + * \param name [in] : the name of the entry to register + * \param value [in] : the value of the entry to register + * \return \e true in case of success. + * \return \e false in case of error. + * \note the bitmask has to be registered + * \sa registerBitMaskType + */ + virtual bool registerBitMaskEntry(const CIdentifier& typeID, const CString& name, uint64_t value) = 0; - //@} - /** \name Type identification */ - //@{ + //@} + /** \name Registration verification */ + //@{ - /** - * \brief Gets the name of a specified type - * \param typeID [in] : the type identifier which name should be returned - * \return the name of the speficied type. - */ - virtual CString getTypeName(const CIdentifier& typeID) const = 0; - /** - * \brief Gets the parent stream type for a stream type - * \param typeID [in] : the stream type identifier which parent stream type be returned - * \return the parent stream type on success. - * \return \c OV_UndefinedIdentifier on error. - * \note The specified type identifier has to be a stream type. - */ - virtual CIdentifier getStreamParentType(const CIdentifier& typeID) const = 0; + /** + * \brief Tests if a specific type has been registered + * \param typeID [in] : the type identifier which registration has to be tested + * \return \e true if the specified type has been registered. + * \return \e false if the specified type has not been registered. + */ + virtual bool isRegistered(const CIdentifier& typeID) const = 0; + /** + * \brief Tests if a specific type has been registered and is a stream + * \param typeID [in] : the type identifier which registration has to be tested + * \return \e true if the specified type has been registered is a stream. + * \return \e false if the specified type has not been registered or is not a stream. + */ + virtual bool isStream(const CIdentifier& typeID) const = 0; + /** + * \brief Tests is a specific type has been registered, is a stream and is derived from another registered stream type + * \param typeID [in] : the type identifier which registration and derivation has to be tested + * \param parentTypeID [in] : the type identifier of the supposed parent stream + * \return \e true in case \c typeID is registered as a stream type and derived from \c parentTypeID + * \return \e false in case \c parentTypeID is not registered + * \return \e false in case \c parentTypeID is not a stream + * \return \e false in case \c typeID is not registered + * \return \e false in case \c typeID is not a stream + * \return \e false in case \c typeID is not derived from parentTypeID + * \note The derivation can be indirect (\c typeID can derive an + * intermediate stream type which derives \c parentTypeID) + */ + virtual bool isDerivedFromStream(const CIdentifier& typeID, const CIdentifier& parentTypeID) const = 0; + /** + * \brief Tests if a specific type has been registered and is an enumeration + * \param typeID [in] : the type identifier which registration has to be tested + * \return \e true if the specified type has been registered and is an enumeration. + * \return \e false if the specified type has not been registered or is not an enumeration. + */ + virtual bool isEnumeration(const CIdentifier& typeID) const = 0; + /** + * \brief Tests if a specific type has been registered and is a bitmask + * \param typeID [in] : the type identifier which registration has to be tested + * \return \e true if the specified type has been registered and is a bitmask. + * \return \e false if the specified type has not been registered or is not a bitmask. + */ + virtual bool isBitMask(const CIdentifier& typeID) const = 0; - //@} - /** \name Enumeration entry accessors */ - //@{ + //@} + /** \name Type identification */ + //@{ - /** - * \brief Gets the number of enumeration entry for an enumeration type - * \param typeID [in] : the enumeration type identifier - * \return the number of entry for this enumeration type. - */ - virtual size_t getEnumerationEntryCount(const CIdentifier& typeID) const = 0; - /** - * \brief Gets details for a specific enumeration type entry - * \param typeID [in] : the enumeration type identifier - * \param index [in] : the index of the entry which details should be returned - * \param name [out] : the name of the specified entry - * \param value [out] : the value of the speficied entry - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool getEnumerationEntry(const CIdentifier& typeID, uint64_t index, CString& name, uint64_t& value) const = 0; - /** - * \brief Converts an enumeration entry value to an enumeration entry name - * \param typeID [in] : the enumeration type identifier - * \param value [in] : the enumeration entry value - * \return the enumeration entry name corresponding to the specified value. - * \warning on error, an empty string is returned. - */ - virtual CString getEnumerationEntryNameFromValue(const CIdentifier& typeID, uint64_t value) const = 0; - /** - * \brief Converts an enumeration entry name to an enumeration entry value - * \param typeID [in] : the enumeration type identifier - * \param name [in] : the enumeration entry name - * \return the enumeration entry value corresponding to the specified name. - * \warning on error, \c 0xffffffffffffffffLL is returned. - */ - virtual uint64_t getEnumerationEntryValueFromName(const CIdentifier& typeID, const CString& name) const = 0; + /** + * \brief Gets the name of a specified type + * \param typeID [in] : the type identifier which name should be returned + * \return the name of the speficied type. + */ + virtual CString getTypeName(const CIdentifier& typeID) const = 0; + /** + * \brief Gets the parent stream type for a stream type + * \param typeID [in] : the stream type identifier which parent stream type be returned + * \return the parent stream type on success. + * \return \c OV_UndefinedIdentifier on error. + * \note The specified type identifier has to be a stream type. + */ + virtual CIdentifier getStreamParentType(const CIdentifier& typeID) const = 0; - //@} - /** \name Bitmask entry accessors */ - //@{ + //@} + /** \name Enumeration entry accessors */ + //@{ - /** - * \brief Gets the number of bitmask entry for a bitmask type - * \param typeID [in] : the bitmask type identifier - * \return the number of entry for this bitmask type. - */ - virtual size_t getBitMaskEntryCount(const CIdentifier& typeID) const = 0; - /** - * \brief Gets details for a specific bitmask type entry - * \param typeID [in] : the bitmask type identifier - * \param index [in] : the index of the entry which details should be returned - * \param name [out] : the name of the specified entry - * \param value [out] : the value of the speficied entry - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool getBitMaskEntry(const CIdentifier& typeID, uint64_t index, CString& name, uint64_t& value) const = 0; - /** - * \brief Converts a bitmask entry value to a bitmask entry name - * \param typeID [in] : the bitmask type identifier - * \param value [in] : the bitmask entry value - * \return the bitmask entry name corresponding to the specified value. - * \warning on error, an empty string is returned. - */ - virtual CString getBitMaskEntryNameFromValue(const CIdentifier& typeID, uint64_t value) const = 0; - /** - * \brief Converts a bitmask entry name to a bitmask entry value - * \param typeID [in] : the bitmask type identifier - * \param name [in] : the bitmask entry name - * \return the bitmask entry value corresponding to the specified name. - * \warning on error, \c 0xffffffffffffffffLL is returned. - */ - virtual uint64_t getBitMaskEntryValueFromName(const CIdentifier& typeID, const CString& name) const = 0; - /** - * \brief Computes the textual value of a composition of numerical entries - * \param typeID [in] : the bitmask type identifier - * \param value [in] : the composition of numerical entries - * \return the bitmask entry composition name. - * \warning on error, an empty string is returned. - */ - virtual CString getBitMaskEntryCompositionNameFromValue(const CIdentifier& typeID, uint64_t value) const = 0; - /** - * \brief Computes the integer value of a composition of textual entries - * \param typeID [in] : the bitmask type identifier - * \param name [in] : the composition of textual entries - * \return the bitmask entry composition value. - * \warning on error, \c 0x0000000000000000LL is returned. - */ - virtual uint64_t getBitMaskEntryCompositionValueFromName(const CIdentifier& typeID, const CString& name) const = 0; + /** + * \brief Gets the number of enumeration entry for an enumeration type + * \param typeID [in] : the enumeration type identifier + * \return the number of entry for this enumeration type. + */ + virtual size_t getEnumerationEntryCount(const CIdentifier& typeID) const = 0; + /** + * \brief Gets details for a specific enumeration type entry + * \param typeID [in] : the enumeration type identifier + * \param index [in] : the index of the entry which details should be returned + * \param name [out] : the name of the specified entry + * \param value [out] : the value of the speficied entry + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool getEnumerationEntry(const CIdentifier& typeID, uint64_t index, CString& name, uint64_t& value) const = 0; + /** + * \brief Converts an enumeration entry value to an enumeration entry name + * \param typeID [in] : the enumeration type identifier + * \param value [in] : the enumeration entry value + * \return the enumeration entry name corresponding to the specified value. + * \warning on error, an empty string is returned. + */ + virtual CString getEnumerationEntryNameFromValue(const CIdentifier& typeID, uint64_t value) const = 0; + /** + * \brief Converts an enumeration entry name to an enumeration entry value + * \param typeID [in] : the enumeration type identifier + * \param name [in] : the enumeration entry name + * \return the enumeration entry value corresponding to the specified name. + * \warning on error, \c 0xffffffffffffffffLL is returned. + */ + virtual uint64_t getEnumerationEntryValueFromName(const CIdentifier& typeID, const CString& name) const = 0; - /** - * \brief Evaluate the string arithmetic expression value - * to a numeric value as a float - * \param value [in] : arithmetic expression to evaluate - * \param result [out] : result of evaluation - * \return true if the arithmetic evaluation succeeded, - * \return false if the arithmetic expression is incorrect - */ - virtual bool evaluateSettingValue(CString value, double& result) const = 0; + //@} + /** \name Bitmask entry accessors */ + //@{ - //@} + /** + * \brief Gets the number of bitmask entry for a bitmask type + * \param typeID [in] : the bitmask type identifier + * \return the number of entry for this bitmask type. + */ + virtual size_t getBitMaskEntryCount(const CIdentifier& typeID) const = 0; + /** + * \brief Gets details for a specific bitmask type entry + * \param typeID [in] : the bitmask type identifier + * \param index [in] : the index of the entry which details should be returned + * \param name [out] : the name of the specified entry + * \param value [out] : the value of the speficied entry + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool getBitMaskEntry(const CIdentifier& typeID, uint64_t index, CString& name, uint64_t& value) const = 0; + /** + * \brief Converts a bitmask entry value to a bitmask entry name + * \param typeID [in] : the bitmask type identifier + * \param value [in] : the bitmask entry value + * \return the bitmask entry name corresponding to the specified value. + * \warning on error, an empty string is returned. + */ + virtual CString getBitMaskEntryNameFromValue(const CIdentifier& typeID, uint64_t value) const = 0; + /** + * \brief Converts a bitmask entry name to a bitmask entry value + * \param typeID [in] : the bitmask type identifier + * \param name [in] : the bitmask entry name + * \return the bitmask entry value corresponding to the specified name. + * \warning on error, \c 0xffffffffffffffffLL is returned. + */ + virtual uint64_t getBitMaskEntryValueFromName(const CIdentifier& typeID, const CString& name) const = 0; + /** + * \brief Computes the textual value of a composition of numerical entries + * \param typeID [in] : the bitmask type identifier + * \param value [in] : the composition of numerical entries + * \return the bitmask entry composition name. + * \warning on error, an empty string is returned. + */ + virtual CString getBitMaskEntryCompositionNameFromValue(const CIdentifier& typeID, uint64_t value) const = 0; + /** + * \brief Computes the integer value of a composition of textual entries + * \param typeID [in] : the bitmask type identifier + * \param name [in] : the composition of textual entries + * \return the bitmask entry composition value. + * \warning on error, \c 0x0000000000000000LL is returned. + */ + virtual uint64_t getBitMaskEntryCompositionValueFromName(const CIdentifier& typeID, const CString& name) const = 0; - _IsDerivedFromClass_(IKernelObject, OV_ClassId_Kernel_TypeManager) - }; - } // namespace Kernel -} // namespace OpenViBE + /** + * \brief Evaluate the string arithmetic expression value + * to a numeric value as a float + * \param value [in] : arithmetic expression to evaluate + * \param result [out] : result of evaluation + * \return true if the arithmetic evaluation succeeded, + * \return false if the arithmetic expression is incorrect + */ + virtual bool evaluateSettingValue(CString value, double& result) const = 0; + + //@} + + _IsDerivedFromClass_(IKernelObject, OV_ClassId_Kernel_TypeManager) +}; +} // namespace Kernel +} // namespace OpenViBE diff --git a/openvibe/include/openvibe/kernel/ovTParameterHandler.h b/openvibe/include/openvibe/kernel/ovTParameterHandler.h index f50d0553a11264071a07b414c301d7fe19966a63..5c51d9e015d173820b8c580ad1acc4d1c5846d15 100644 --- a/openvibe/include/openvibe/kernel/ovTParameterHandler.h +++ b/openvibe/include/openvibe/kernel/ovTParameterHandler.h @@ -3,215 +3,213 @@ #include "ovIParameter.h" #include "ovIConfigurable.h" -namespace OpenViBE +namespace OpenViBE { +namespace Kernel { +/** + * \class TParameterHandler + * \brief Helper class in order to manipulate IParameter and IParameter values natively + * \author Yann Renard (INRIA/IRISA) + * \date 2007-11-21 + * \ingroup Group_Kernel + * \ingroup Group_Helper + * \sa IParameter + * \sa EParameterType + * + * The purpose for this template is to help user code to manipulate + * IParameter abstract class and it's associated value. Client code + * should probably use this template better than IParameter directly. + * The template argument is the handled data type : + * - for \c ParameterType_Integer : \c int64_t + * - for \c ParameterType_UInteger : \c uint64_t + * - for \c ParameterType_Boolean : \c bool + * - for \c ParameterType_Float : \c double + * - for \c ParameterType_String : \c CString + * - for \c ParameterType_Identifier : \c CIdentifier + * - for \c ParameterType_Matrix : \c IMatrix* + * - for \c ParameterType_StimulationSet : \c IStimulationSet* + * - for \c ParameterType_MemoryBuffer : \c IMemoryBuffer* + * - for \c ParameterType_Object : \c IObject* + * - for \c ParameterType_Pointer : \c uint8_t* + * + * The idea is to connect the handler to the corresponding IParameter object + * thanks to the \c initialize function. Then the provided interface translates + * handled object native operation to generic IParameter operations automatically. + * Moreover, the handler is able to provide the handled object's interface thanks + * to an automatic cast operator. + */ +template <typename T> +class TParameterHandler { - namespace Kernel +public: + + /** \name Construction */ + //@{ + + /** + * \brief Default construction, does nothing + */ + TParameterHandler() { } + + /** + * \brief IParameter based construction + * \param parameter [in] : the parameter to use for the initialization + * + * This constructor considers the parameter handler to be + * connected to the provided parameter. This is equivalent to + * using the default constructor and call the initialize function + * with the provided IParameter pointer. + */ + TParameterHandler(IParameter* parameter) : m_parameter(parameter) { } + + //@} + /** \name Initialization */ + //@{ + + /** + * \brief Connects this parameter handler to a concrete IParameter pointer + * \param parameter [in] : the concrete parameter to connect to (it can not be \c NULL ) + * \return \e true in case of success. + * \return \e false in case of error. + * + * Future calls to this handler will be redirected to the + * concrete parameter object. + */ + bool initialize(IParameter* parameter) { - /** - * \class TParameterHandler - * \brief Helper class in order to manipulate IParameter and IParameter values natively - * \author Yann Renard (INRIA/IRISA) - * \date 2007-11-21 - * \ingroup Group_Kernel - * \ingroup Group_Helper - * \sa IParameter - * \sa EParameterType - * - * The purpose for this template is to help user code to manipulate - * IParameter abstract class and it's associated value. Client code - * should probably use this template better than IParameter directly. - * The template argument is the handled data type : - * - for \c ParameterType_Integer : \c int64_t - * - for \c ParameterType_UInteger : \c uint64_t - * - for \c ParameterType_Boolean : \c bool - * - for \c ParameterType_Float : \c double - * - for \c ParameterType_String : \c CString - * - for \c ParameterType_Identifier : \c CIdentifier - * - for \c ParameterType_Matrix : \c IMatrix* - * - for \c ParameterType_StimulationSet : \c IStimulationSet* - * - for \c ParameterType_MemoryBuffer : \c IMemoryBuffer* - * - for \c ParameterType_Object : \c IObject* - * - for \c ParameterType_Pointer : \c uint8_t* - * - * The idea is to connect the handler to the corresponding IParameter object - * thanks to the \c initialize function. Then the provided interface translates - * handled object native operation to generic IParameter operations automatically. - * Moreover, the handler is able to provide the handled object's interface thanks - * to an automatic cast operator. - */ - template <typename T> - class TParameterHandler - { - public: - - /** \name Construction */ - //@{ - - /** - * \brief Default construction, does nothing - */ - TParameterHandler() { } - - /** - * \brief IParameter based construction - * \param parameter [in] : the parameter to use for the initialization - * - * This constructor considers the parameter handler to be - * connected to the provided parameter. This is equivalent to - * using the default constructor and call the initialize function - * with the provided IParameter pointer. - */ - TParameterHandler(IParameter* parameter) : m_parameter(parameter) { } - - //@} - /** \name Initialization */ - //@{ - - /** - * \brief Connects this parameter handler to a concrete IParameter pointer - * \param parameter [in] : the concrete parameter to connect to (it can not be \c NULL ) - * \return \e true in case of success. - * \return \e false in case of error. - * - * Future calls to this handler will be redirected to the - * concrete parameter object. - */ - bool initialize(IParameter* parameter) - { - if (m_parameter || !parameter) { return false; } - - m_parameter = parameter; - return true; - } - - /** - * \brief Disconnects this parameter handler from its concrete IParameter pointer - * \return \e true in case of success. - * \return \e false in case of error. - * - * This handler won't be usable until \c initialize is called successfully again. - */ - bool uninitialize() - { - if (!m_parameter) { return false; } - m_parameter = nullptr; - return true; - } - - /** - * \brief Checks whether this handler is connected to a concrete IParameter or not - * \return \e true if this handler is connected to a concrete IParameter, \e false if not - */ - bool exists() const { return m_parameter != nullptr; } - - //@{ - /** \name Transparent operators */ - //@{ - - /** - * \brief Handled object type cast - * \return The handled object itself - * - * This cast operator allows the handler to be used as if it was the handled - * object itself. For example, an unsigned integer parameter handler is usable - * in arithmetic operations : - * - * \code - * // parameter will directly be used as if it is an unsigned integer - * TParameterHandler<uint64_t> parameter ( ... ); - * uint64_t a= ...; - * uint64_t c=a*parameter+parameter; - * \endcode - */ - operator T() const - { - if (!m_parameter) { throw; } - T t; - m_parameter->getValue(&t); - return t; - } - /** - * \brief Handled object type member access operator - * \return The handled object itself for access operation - * - * This operator allows the handler to be used as if it was the handled - * object itself. For example, a matrix parameter handler is usable - * as if it was a matrix pointer : - * - * \code - * // parameter will directly be used as if it is a matrix pointer - * TParameterHandler<IMatrix*> parameter ( ... ); - * parameter->setDimensionCount(2); - * \endcode - */ - T operator ->() const - { - if (!m_parameter) { throw; } - T t; - m_parameter->getValue(&t); - return t; - } - /** - * \brief Affectation operator - * \return This handler itself - * - * This operator allows to affect handled object type values to the - * handled object itself. For example, an unsigned integer parameter - * handler can be affected this way : - * - * \code - * // the affectation of parameter will directly go to its handled unsigned integer - * TParameterHandler<uint64_t> parameter ( ... ); - * parameter = 1; - * \endcode - */ - TParameterHandler<T>& operator=(const T& t) - { - if (!m_parameter) { throw; } - m_parameter->setValue(&t); - return *this; - } - - //@} - /** \name Reference target management */ - //@{ - - /** - * \brief Clears all reference targets - * \return \e true in case of success. - * \return \e false in case of error. - */ - bool clearReferenceTarget() const { return m_parameter ? m_parameter->clearReferenceTarget() : false; } - /** - * \brief Sets a new reference target - * \param rParameterHandler [in] : a parameter handler of the same type as this parameter handler - * \return \e true in case of success. - * \return \e false in case of error. - */ - bool setReferenceTarget(TParameterHandler<T>& rParameterHandler) - { - return m_parameter && rParameterHandler.m_parameter ? m_parameter->setReferenceTarget(rParameterHandler.m_parameter) : false; - } - /** - * \brief Sets a new reference target - * \param pParameter [in] : a parameter to use as reference target - * \return \e true in case of success. - * \return \e false in case of error. - */ - bool setReferenceTarget(IParameter* pParameter) const { return m_parameter && pParameter ? m_parameter->setReferenceTarget(pParameter) : false; } - /** - * \brief Sets a new reference target - * \param t [in] : a value to use as reference target - * \return \e true in case of success. - * \return \e false in case of error. - */ - bool setReferenceTarget(T& t) { return m_parameter ? m_parameter->setReferenceTarget(&t) : false; } - - //@} - - protected: - - IParameter* m_parameter = nullptr; ///< Handled parameter - }; - } // namespace Kernel -} // namespace OpenViBE + if (m_parameter || !parameter) { return false; } + + m_parameter = parameter; + return true; + } + + /** + * \brief Disconnects this parameter handler from its concrete IParameter pointer + * \return \e true in case of success. + * \return \e false in case of error. + * + * This handler won't be usable until \c initialize is called successfully again. + */ + bool uninitialize() + { + if (!m_parameter) { return false; } + m_parameter = nullptr; + return true; + } + + /** + * \brief Checks whether this handler is connected to a concrete IParameter or not + * \return \e true if this handler is connected to a concrete IParameter, \e false if not + */ + bool exists() const { return m_parameter != nullptr; } + + //@{ + /** \name Transparent operators */ + //@{ + + /** + * \brief Handled object type cast + * \return The handled object itself + * + * This cast operator allows the handler to be used as if it was the handled + * object itself. For example, an unsigned integer parameter handler is usable + * in arithmetic operations : + * + * \code + * // parameter will directly be used as if it is an unsigned integer + * TParameterHandler<uint64_t> parameter ( ... ); + * uint64_t a= ...; + * uint64_t c=a*parameter+parameter; + * \endcode + */ + operator T() const + { + if (!m_parameter) { throw; } + T t; + m_parameter->getValue(&t); + return t; + } + /** + * \brief Handled object type member access operator + * \return The handled object itself for access operation + * + * This operator allows the handler to be used as if it was the handled + * object itself. For example, a matrix parameter handler is usable + * as if it was a matrix pointer : + * + * \code + * // parameter will directly be used as if it is a matrix pointer + * TParameterHandler<IMatrix*> parameter ( ... ); + * parameter->setDimensionCount(2); + * \endcode + */ + T operator ->() const + { + if (!m_parameter) { throw; } + T t; + m_parameter->getValue(&t); + return t; + } + /** + * \brief Affectation operator + * \return This handler itself + * + * This operator allows to affect handled object type values to the + * handled object itself. For example, an unsigned integer parameter + * handler can be affected this way : + * + * \code + * // the affectation of parameter will directly go to its handled unsigned integer + * TParameterHandler<uint64_t> parameter ( ... ); + * parameter = 1; + * \endcode + */ + TParameterHandler<T>& operator=(const T& t) + { + if (!m_parameter) { throw; } + m_parameter->setValue(&t); + return *this; + } + + //@} + /** \name Reference target management */ + //@{ + + /** + * \brief Clears all reference targets + * \return \e true in case of success. + * \return \e false in case of error. + */ + bool clearReferenceTarget() const { return m_parameter ? m_parameter->clearReferenceTarget() : false; } + /** + * \brief Sets a new reference target + * \param rParameterHandler [in] : a parameter handler of the same type as this parameter handler + * \return \e true in case of success. + * \return \e false in case of error. + */ + bool setReferenceTarget(TParameterHandler<T>& rParameterHandler) + { + return m_parameter && rParameterHandler.m_parameter ? m_parameter->setReferenceTarget(rParameterHandler.m_parameter) : false; + } + /** + * \brief Sets a new reference target + * \param pParameter [in] : a parameter to use as reference target + * \return \e true in case of success. + * \return \e false in case of error. + */ + bool setReferenceTarget(IParameter* pParameter) const { return m_parameter && pParameter ? m_parameter->setReferenceTarget(pParameter) : false; } + /** + * \brief Sets a new reference target + * \param t [in] : a value to use as reference target + * \return \e true in case of success. + * \return \e false in case of error. + */ + bool setReferenceTarget(T& t) { return m_parameter ? m_parameter->setReferenceTarget(&t) : false; } + + //@} + +protected: + + IParameter* m_parameter = nullptr; ///< Handled parameter +}; +} // namespace Kernel +} // namespace OpenViBE diff --git a/openvibe/include/openvibe/kernel/player/CMessageClock.hpp b/openvibe/include/openvibe/kernel/player/CMessageClock.hpp new file mode 100644 index 0000000000000000000000000000000000000000..fb032491384fc68322e01e684c251f222b7fb455 --- /dev/null +++ b/openvibe/include/openvibe/kernel/player/CMessageClock.hpp @@ -0,0 +1,35 @@ +#pragma once +#include "../../ovCIdentifier.h" + +namespace OpenViBE { +namespace Kernel { +/** + * \class CMessageClock + * \author Yann Renard (INRIA/IRISA) + * \date 2006-05-30 + * \brief Clock message + * \ingroup Group_Player + * \ingroup Group_Kernel + * \todo This class can be suppress, The only time, this class is used is with processClock. In this function, only getTime() is used some times. + * We must verify if this time is the same as getPlayerContext().getCurrentTime(). If it's true we can suppress completly this class. + * remark : In this case we modify the API for plugin + */ +class OV_API CMessageClock +{ +public: + CMessageClock() = default; + + CIdentifier getIdentifier() const { return m_id; } + uint64_t getTime() const { return m_time; } + + void setIdentifier(const CIdentifier& id) { m_id = id; } + void setTime(const uint64_t time) { m_time = time; } +protected: + CIdentifier m_id = OV_UndefinedIdentifier; + uint64_t m_time = 0; +}; + +typedef Kernel::CMessageClock IMessageClock; + +} // namespace Kernel +} // namespace OpenViBE diff --git a/openvibe/include/openvibe/kernel/player/ovIBoxAlgorithmContext.h b/openvibe/include/openvibe/kernel/player/ovIBoxAlgorithmContext.h index 5950a47228efe9b161e5535feb2e768edfd53425..1f871e9305a354f22864ac034db2bd5f3b90f88f 100644 --- a/openvibe/include/openvibe/kernel/player/ovIBoxAlgorithmContext.h +++ b/openvibe/include/openvibe/kernel/player/ovIBoxAlgorithmContext.h @@ -2,87 +2,85 @@ #include "../ovIKernelObject.h" -namespace OpenViBE -{ - namespace Kernel - { - class IBox; - class IBoxIO; - class IPlayerContext; +namespace OpenViBE { +namespace Kernel { +class IBox; +class IBoxIO; +class IPlayerContext; - /** - * \class IBoxAlgorithmContext - * \author Yann Renard (INRIA/IRISA) - * \date 2006-07-07 - * \brief Specific context to use for box algorithm plugins - * \ingroup Group_Player - * \ingroup Group_Kernel - * \ingroup Group_Extend - * - * This 'context' is given by the player to an algorithm plugin - * so it has all the necessary tools to work. This algorithm - * context mainly consists in getting other contexts which - * could be defined and used more generically (such as the - * box interface or a global player interface for example). - * - * \sa IBoxAlgorithm - * \sa IPlayerContext - */ - class OV_API IBoxAlgorithmContext : public IKernelObject - { - public: +/** + * \class IBoxAlgorithmContext + * \author Yann Renard (INRIA/IRISA) + * \date 2006-07-07 + * \brief Specific context to use for box algorithm plugins + * \ingroup Group_Player + * \ingroup Group_Kernel + * \ingroup Group_Extend + * + * This 'context' is given by the player to an algorithm plugin + * so it has all the necessary tools to work. This algorithm + * context mainly consists in getting other contexts which + * could be defined and used more generically (such as the + * box interface or a global player interface for example). + * + * \sa IBoxAlgorithm + * \sa IPlayerContext + */ +class OV_API IBoxAlgorithmContext : public IKernelObject +{ +public: - /** - * \brief Gets the static context of the box corresponding to the algorithm - * \return A pointer on the corresponding context - * - * The returned context can be used by the algorithm to - * access the box' prototype. - * - * \warning The algorithm should not use this reference after it - * has finished its work, it could be deprecated. - * \sa IBoxAlgorithmContext::getDynamicBoxContext - */ - virtual const IBox* getStaticBoxContext() = 0; - /** - * \brief Gets the dynamic context of the box corresponding to the algorithm - * \return A pointer on the corresponding context - * - * The returned context can be used by the algorithm to - * access the box' inputs, outputs and settings. - * - * \warning The algorithm should not use this reference after it - * has finished its work, it could be deprecated. - * \sa IBoxAlgorithmContext::getStaticBoxContext - */ - virtual IBoxIO* getDynamicBoxContext() = 0; - /** - * \brief Gets the player context - * \return A pointer on the player context - * - * The returned context can be used by the algorithm to - * access the player functionnalities. - * - * \warning The algorithm should not use this reference after it - * has finished its work, it could be deprecated. - */ - virtual IPlayerContext* getPlayerContext() = 0; + /** + * \brief Gets the static context of the box corresponding to the algorithm + * \return A pointer on the corresponding context + * + * The returned context can be used by the algorithm to + * access the box' prototype. + * + * \warning The algorithm should not use this reference after it + * has finished its work, it could be deprecated. + * \sa IBoxAlgorithmContext::getDynamicBoxContext + */ + virtual const IBox* getStaticBoxContext() = 0; + /** + * \brief Gets the dynamic context of the box corresponding to the algorithm + * \return A pointer on the corresponding context + * + * The returned context can be used by the algorithm to + * access the box' inputs, outputs and settings. + * + * \warning The algorithm should not use this reference after it + * has finished its work, it could be deprecated. + * \sa IBoxAlgorithmContext::getStaticBoxContext + */ + virtual IBoxIO* getDynamicBoxContext() = 0; + /** + * \brief Gets the player context + * \return A pointer on the player context + * + * The returned context can be used by the algorithm to + * access the player functionnalities. + * + * \warning The algorithm should not use this reference after it + * has finished its work, it could be deprecated. + */ + virtual IPlayerContext* getPlayerContext() = 0; - /** - * \brief Marks the algorithm as 'ready to process' so its process function is called by the kernel - * \return \e true in case of success. - * \return \e false when an error occurs. - * - * This function should be called by the algorithm itself - * after receiving a message so the kernel knows it is - * ready to process some data... As soon as the kernel - * knows the algorithm is ready, the \c process function - * is called so the algorithm does its work and produces - * its outputs. - */ - virtual bool markAlgorithmAsReadyToProcess() = 0; + /** + * \brief Marks the algorithm as 'ready to process' so its process function is called by the kernel + * \return \e true in case of success. + * \return \e false when an error occurs. + * + * This function should be called by the algorithm itself + * after receiving a message so the kernel knows it is + * ready to process some data... As soon as the kernel + * knows the algorithm is ready, the \c process function + * is called so the algorithm does its work and produces + * its outputs. + */ + virtual bool markAlgorithmAsReadyToProcess() = 0; - _IsDerivedFromClass_(IKernelObject, OV_ClassId_Kernel_Player_BoxAlgorithmContext) - }; - } // namespace Kernel -} // namespace OpenViBE + _IsDerivedFromClass_(IKernelObject, OV_ClassId_Kernel_Player_BoxAlgorithmContext) +}; +} // namespace Kernel +} // namespace OpenViBE diff --git a/openvibe/include/openvibe/kernel/player/ovIMessage.h b/openvibe/include/openvibe/kernel/player/ovIMessage.h deleted file mode 100644 index 8d10b2776a30e445fc525cf1c9b736dcffc090d2..0000000000000000000000000000000000000000 --- a/openvibe/include/openvibe/kernel/player/ovIMessage.h +++ /dev/null @@ -1,49 +0,0 @@ -#pragma once - -#include "../ovIKernelObject.h" - -namespace OpenViBE -{ - namespace Kernel - { - /** - * \class IMessage - * \author Yann Renard (INRIA/IRISA) - * \date 2006-05-30 - * \brief Base message class - * \ingroup Group_Player - * \ingroup Group_Kernel - */ - class OV_API IMessage : public IKernelObject - { - public: - - /** - * \brief Gets the message identifier - * \return The identifier of the message. - */ - virtual CIdentifier getIdentifier() const = 0; - /** - * \brief Gets the timestamp of the message - * \return the timestamp of the message. - */ - virtual uint64_t getTime() const = 0; - /** - * \brief Sets the message id for this message - * \param id [in] : the new id of the message - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool setIdentifier(const CIdentifier& id) = 0; - /** - * \brief Sets the message timestamp - * \param time [in] : the new timestamp of the message - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool setTime(const uint64_t time) = 0; - - _IsDerivedFromClass_(IKernelObject, OV_ClassId_Kernel_Player_Message) - }; - } // namespace Kernel -} // namespace OpenViBE diff --git a/openvibe/include/openvibe/kernel/player/ovIMessageClock.h b/openvibe/include/openvibe/kernel/player/ovIMessageClock.h deleted file mode 100644 index d9b9a4228155987aa83fd7ba60f866d271b76800..0000000000000000000000000000000000000000 --- a/openvibe/include/openvibe/kernel/player/ovIMessageClock.h +++ /dev/null @@ -1,24 +0,0 @@ -#pragma once - -#include "ovIMessage.h" - -namespace OpenViBE -{ - namespace Kernel - { - /** - * \class IMessageClock - * \author Yann Renard (INRIA/IRISA) - * \date 2006-05-30 - * \brief Clock message - * \ingroup Group_Player - * \ingroup Group_Kernel - */ - class OV_API IMessageClock : public IMessage - { - public: - - _IsDerivedFromClass_(IMessage, OV_ClassId_Kernel_Player_MessageClock) - }; - } // namespace Kernel -} // namespace OpenViBE diff --git a/openvibe/include/openvibe/kernel/player/ovIMessageEvent.h b/openvibe/include/openvibe/kernel/player/ovIMessageEvent.h deleted file mode 100644 index e5975af3e2a649e04e76db396aeca22f20b6a21b..0000000000000000000000000000000000000000 --- a/openvibe/include/openvibe/kernel/player/ovIMessageEvent.h +++ /dev/null @@ -1,24 +0,0 @@ -#pragma once - -#include "ovIMessage.h" - -namespace OpenViBE -{ - namespace Kernel - { - /** - * \class IMessageEvent - * \author Yann Renard (INRIA/IRISA) - * \date 2006-05-30 - * \brief Event message - * \ingroup Group_Player - * \ingroup Group_Kernel - */ - class OV_API IMessageEvent : public IMessage - { - public: - - _IsDerivedFromClass_(IMessage, OV_ClassId_Kernel_Player_MessageEvent) - }; - } // namespace Kernel -} // namespace OpenViBE diff --git a/openvibe/include/openvibe/kernel/player/ovIMessageSignal.h b/openvibe/include/openvibe/kernel/player/ovIMessageSignal.h deleted file mode 100644 index 0e901270875d8a7f25179e13b72779a8ebe07fc1..0000000000000000000000000000000000000000 --- a/openvibe/include/openvibe/kernel/player/ovIMessageSignal.h +++ /dev/null @@ -1,24 +0,0 @@ -#pragma once - -#include "ovIMessage.h" - -namespace OpenViBE -{ - namespace Kernel - { - /** - * \class IMessageSignal - * \author Yann Renard (INRIA/IRISA) - * \date 2006-05-30 - * \brief Signal message - * \ingroup Group_Player - * \ingroup Group_Kernel - */ - class OV_API IMessageSignal : public IMessage - { - public: - - _IsDerivedFromClass_(IMessage, OV_ClassId_Kernel_Player_MessageSignal) - }; - } // namespace Kernel -} // namespace OpenViBE diff --git a/openvibe/include/openvibe/kernel/player/ovIPlayer.h b/openvibe/include/openvibe/kernel/player/ovIPlayer.h index 02fc3e010051fd63fef504c407b3438a21f57c84..41b6ca079193ef33b072357f1e0eb692246eff44 100644 --- a/openvibe/include/openvibe/kernel/player/ovIPlayer.h +++ b/openvibe/include/openvibe/kernel/player/ovIPlayer.h @@ -2,197 +2,195 @@ #include "../ovIKernelObject.h" -namespace OpenViBE +namespace OpenViBE { +namespace Kernel { +class IScenario; +class IConfigurationManager; + +enum class EPlayerStatus { Stop, Pause, Step, Play, Forward }; + +enum class EPlayerReturnCodes { Success, Failed, BoxInitializationFailed }; + +inline std::string toString(const EPlayerStatus status) { - namespace Kernel + switch (status) { - class IScenario; - class IConfigurationManager; - - enum class EPlayerStatus { Stop, Pause, Step, Play, Forward }; - - enum class EPlayerReturnCodes { Success, Failed, BoxInitializationFailed }; - - inline std::string toString(const EPlayerStatus status) - { - switch (status) - { - case EPlayerStatus::Stop: return "Stop"; - case EPlayerStatus::Pause: return "Pause"; - case EPlayerStatus::Step: return "Step"; - case EPlayerStatus::Play: return "Play"; - case EPlayerStatus::Forward: return "Forward"; - default: return "Invalid Status"; - } - } - - inline std::string toString(const EPlayerReturnCodes code) - { - switch (code) - { - case EPlayerReturnCodes::Success: return "Success"; - case EPlayerReturnCodes::Failed: return "Failed"; - case EPlayerReturnCodes::BoxInitializationFailed: return "Box Initialization Failed"; - default: return "Invalid Code"; - } - } - - /** - * \class IPlayer - * \author Yann Renard (INRIA/IRISA) - * \date 2006-09-26 - * \brief The main player class - * \ingroup Group_Player - * \ingroup Group_Kernel - * - * A player is responsible for the playback of a specific scenario. - * This player scenario is provided at initialisation stage and should - * not be changed until the player terminates. The player idea of calling - * a "play" function forces the use of threads in order to avoid CPU locking. - * Thus we prefer the idea of having a "short-time" function that is to be - * called repeatedly until the player terminates. This is the role of the - * \c IPlayer::loop function, that should be called repeatedly by the outside - * application. - * - * \todo Refactor this base class to propose an interface - * more OpenViBE compliant (use IDs, intialize/unitialize - * pairs etc...) - */ - class OV_API IPlayer : public IKernelObject - { - public: - - /** - * \brief Attaches a scenario to this player - * \param id [in] : the scenario identifier to attach to this player. The scenario itself is found from the scenario manager. - * \param localConfigTokens [in] : An optional map that contains configuration tokens to add. - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool setScenario(const CIdentifier& id, const CNameValuePairList* localConfigTokens = nullptr) = 0; - - /** - * \brief returns a reference to the runtime configuration manager - * \return a reference to the runtime configuration manager - * - * When initialized, a player creates a runtime configuration manager - * which will be used for scenario and runtime related specific configuration. - * The use of this features includes the loading of a delayed configuration file - * for instance. The reference should be valid up to the duration of the player itself. - * - * \sa IConfigurationManager - */ - virtual IConfigurationManager& getRuntimeConfigurationManager() const = 0; - - /** - * \brief returns a reference to the runtime scenario manager - * \return a reference to the runtime scenario manager - * - * When a scenario is loaded, a copy is made and stored in the - * runtime scenario manager. This function allows getting the - * runtime scenario manager that contains the current executed scenario. - * - * \sa IScenarioManager - */ - virtual IScenarioManager& getRuntimeScenarioManager() const = 0; - - /** - * \brief returns the cidentifier of the associated runtime scenario - * \return the cidentifier of the associated runtime scenario - * - * When initialized, a player copy the scenario in the runtime configuration manager - * this method allows getting the identifier of said copied scenario - * - * \sa CIdentifier - */ - virtual CIdentifier getRuntimeScenarioIdentifier() const = 0; - - /** - * \brief Initializes this player - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual EPlayerReturnCodes initialize() = 0; - /** - * \brief Uninitializes this player - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool uninitialize() = 0; - - /** - * \brief Stops player execution - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool stop() = 0; - /** - * \brief Pauses player execution - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool pause() = 0; - /** - * \brief Executes one more step and pauses - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool step() = 0; - /** - * \brief Makes player run normal speed - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool play() = 0; - /** - * \brief Makes player run as fast as possible - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool forward() = 0; - /** - * \brief Gets current player status - * \return current player status - */ - virtual EPlayerStatus getStatus() const = 0; - - /** - * \brief Sets maximum fast forward factor coefficient - * \param factor : the maximum speed multiplier to be applied when playing in EPlayerStatus::Forward mode - * \return \e true in case of success. - * \return \e false in case of error. - * \note If a negative value is passed, it is turned back to 0 - * \note It the fast forward factor is 0, it tells the player to go as fast as possible - */ - virtual bool setFastForwardMaximumFactor(double factor) = 0; - /** - * \brief Gets the maximum fast forward factor coefficient - * \return The maximum fast forward factor coefficient. - */ - virtual double getFastForwardMaximumFactor() const = 0; - - /** - * \brief Gets an estimate of the actual time ratio spent in the player's loop - * \return the amount of time spent in the player's loop (given in percentage) - */ - virtual double getCPUUsage() const = 0; - - /** - * \brief "short time" function to be called repeatedly by the outstide application - * \param elapsedTime [in] : real elapsed time given in seconds 32:32 - * \param maximumTimeToReach [in] : maximum time to reach given in seconds 32:32 - * \return \e true if the execution went successfully. - * \return \e false in case their was a problem or the execution terminated. - * - * The \e maximumTimeToReach parameter guarantees that the player does not - * run beyond the specified time when ran in fast forward mode. It defaults - * to \c uint64_t(-1) which represents the largest OpenViBE time. - */ - virtual bool loop(uint64_t elapsedTime, uint64_t maximumTimeToReach = uint64_t(-1)) = 0; - - virtual uint64_t getCurrentSimulatedTime() const = 0; - - _IsDerivedFromClass_(IKernelObject, OV_ClassId_Kernel_Player_Player) - }; - } // namespace Kernel -} // namespace OpenViBE + case EPlayerStatus::Stop: return "Stop"; + case EPlayerStatus::Pause: return "Pause"; + case EPlayerStatus::Step: return "Step"; + case EPlayerStatus::Play: return "Play"; + case EPlayerStatus::Forward: return "Forward"; + default: return "Invalid Status"; + } +} + +inline std::string toString(const EPlayerReturnCodes code) +{ + switch (code) + { + case EPlayerReturnCodes::Success: return "Success"; + case EPlayerReturnCodes::Failed: return "Failed"; + case EPlayerReturnCodes::BoxInitializationFailed: return "Box Initialization Failed"; + default: return "Invalid Code"; + } +} + +/** + * \class IPlayer + * \author Yann Renard (INRIA/IRISA) + * \date 2006-09-26 + * \brief The main player class + * \ingroup Group_Player + * \ingroup Group_Kernel + * + * A player is responsible for the playback of a specific scenario. + * This player scenario is provided at initialisation stage and should + * not be changed until the player terminates. The player idea of calling + * a "play" function forces the use of threads in order to avoid CPU locking. + * Thus we prefer the idea of having a "short-time" function that is to be + * called repeatedly until the player terminates. This is the role of the + * \c IPlayer::loop function, that should be called repeatedly by the outside + * application. + * + * \todo Refactor this base class to propose an interface + * more OpenViBE compliant (use IDs, intialize/unitialize + * pairs etc...) + */ +class OV_API IPlayer : public IKernelObject +{ +public: + + /** + * \brief Attaches a scenario to this player + * \param id [in] : the scenario identifier to attach to this player. The scenario itself is found from the scenario manager. + * \param localConfigTokens [in] : An optional map that contains configuration tokens to add. + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool setScenario(const CIdentifier& id, const CNameValuePairList* localConfigTokens = nullptr) = 0; + + /** + * \brief returns a reference to the runtime configuration manager + * \return a reference to the runtime configuration manager + * + * When initialized, a player creates a runtime configuration manager + * which will be used for scenario and runtime related specific configuration. + * The use of this features includes the loading of a delayed configuration file + * for instance. The reference should be valid up to the duration of the player itself. + * + * \sa IConfigurationManager + */ + virtual IConfigurationManager& getRuntimeConfigurationManager() const = 0; + + /** + * \brief returns a reference to the runtime scenario manager + * \return a reference to the runtime scenario manager + * + * When a scenario is loaded, a copy is made and stored in the + * runtime scenario manager. This function allows getting the + * runtime scenario manager that contains the current executed scenario. + * + * \sa IScenarioManager + */ + virtual IScenarioManager& getRuntimeScenarioManager() const = 0; + + /** + * \brief returns the cidentifier of the associated runtime scenario + * \return the cidentifier of the associated runtime scenario + * + * When initialized, a player copy the scenario in the runtime configuration manager + * this method allows getting the identifier of said copied scenario + * + * \sa CIdentifier + */ + virtual CIdentifier getRuntimeScenarioIdentifier() const = 0; + + /** + * \brief Initializes this player + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual EPlayerReturnCodes initialize() = 0; + /** + * \brief Uninitializes this player + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool uninitialize() = 0; + + /** + * \brief Stops player execution + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool stop() = 0; + /** + * \brief Pauses player execution + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool pause() = 0; + /** + * \brief Executes one more step and pauses + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool step() = 0; + /** + * \brief Makes player run normal speed + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool play() = 0; + /** + * \brief Makes player run as fast as possible + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool forward() = 0; + /** + * \brief Gets current player status + * \return current player status + */ + virtual EPlayerStatus getStatus() const = 0; + + /** + * \brief Sets maximum fast forward factor coefficient + * \param factor : the maximum speed multiplier to be applied when playing in EPlayerStatus::Forward mode + * \return \e true in case of success. + * \return \e false in case of error. + * \note If a negative value is passed, it is turned back to 0 + * \note It the fast forward factor is 0, it tells the player to go as fast as possible + */ + virtual bool setFastForwardMaximumFactor(double factor) = 0; + /** + * \brief Gets the maximum fast forward factor coefficient + * \return The maximum fast forward factor coefficient. + */ + virtual double getFastForwardMaximumFactor() const = 0; + + /** + * \brief Gets an estimate of the actual time ratio spent in the player's loop + * \return the amount of time spent in the player's loop (given in percentage) + */ + virtual double getCPUUsage() const = 0; + + /** + * \brief "short time" function to be called repeatedly by the outstide application + * \param elapsedTime [in] : real elapsed time given in seconds 32:32 + * \param maximumTimeToReach [in] : maximum time to reach given in seconds 32:32 + * \return \e true if the execution went successfully. + * \return \e false in case their was a problem or the execution terminated. + * + * The \e maximumTimeToReach parameter guarantees that the player does not + * run beyond the specified time when ran in fast forward mode. It defaults + * to \c uint64_t(-1) which represents the largest OpenViBE time. + */ + virtual bool loop(uint64_t elapsedTime, uint64_t maximumTimeToReach = uint64_t(-1)) = 0; + + virtual uint64_t getCurrentSimulatedTime() const = 0; + + _IsDerivedFromClass_(IKernelObject, OV_ClassId_Kernel_Player_Player) +}; +} // namespace Kernel +} // namespace OpenViBE diff --git a/openvibe/include/openvibe/kernel/player/ovIPlayerContext.h b/openvibe/include/openvibe/kernel/player/ovIPlayerContext.h index 42dfd4d57c643ddb4725139c16a921e927ae76b6..8e5a7cafdd1620b6de9a3e70b969935ab36b5b68 100644 --- a/openvibe/include/openvibe/kernel/player/ovIPlayerContext.h +++ b/openvibe/include/openvibe/kernel/player/ovIPlayerContext.h @@ -2,189 +2,154 @@ #include "../ovIKernelObject.h" -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +class IPluginObject; +} // namespace Plugins + +namespace Kernel { +class IConfigurationManager; +class ILogManager; +class IScenarioManager; + +/** + * \class IPlayerContext + * \author Yann Renard (INRIA/IRISA) + * \date 2006-07-07 + * \brief Player interface for plugin objects + * \ingroup Group_Player + * \ingroup Group_Kernel + * + * Instances of this class are given to plugin object + * so they can communicate with the platform kernel, + * providing services such as message sending etc... + */ +class OV_API IPlayerContext : public IKernelObject { - namespace Plugins - { - class IPluginObject; - } // namespace Plugins - - namespace Kernel - { - class IConfigurationManager; - class ILogManager; - class IMessageClock; - class IMessageEvent; - class IMessageSignal; - class IScenarioManager; - - /** - * \class IPlayerContext - * \author Yann Renard (INRIA/IRISA) - * \date 2006-07-07 - * \brief Player interface for plugin objects - * \ingroup Group_Player - * \ingroup Group_Kernel - * - * Instances of this class are given to plugin object - * so they can communicate with the platform kernel, - * providing services such as message sending etc... - */ - class OV_API IPlayerContext : public IKernelObject - { - public: - - /** \name Messages sending */ - //@{ - - /** - * \brief Sends signal to the kernel - * \param messageSignal [in] : the signal message to send - * \return \e true in case of success, \e false in other cases. - */ - virtual bool sendSignal(const IMessageSignal& messageSignal) = 0; - /** - * \brief Sends a message to another box - * \param messageEvent [in] : the message to send to the other box - * \param dstID [in] : the identifier of the other box - * \return \e true in case of success, \e false in other cases. - */ - virtual bool sendMessage(const IMessageEvent& messageEvent, const CIdentifier& dstID) = 0; - /** - * \brief Broadcasts a message to several other boxes - * \param messageEvent [in] : the message to send - * \param dstID [in] : a pointer containing all - * the targets which should receive the sent message. - * \param nDstID [in] : the number of - * targets contained in the \c dstID array. - * \return \e true in case of success, \e false in other cases. - */ - virtual bool sendMessage(const IMessageEvent& messageEvent, const CIdentifier* dstID, const size_t nDstID) = 0; - - //}@ - - /** \name Time management */ - //@{ - - /** - * \brief Gets the current player time - * \return the current player time. - * \note The time value is fixed point 32:32 representated in seconds - */ - virtual uint64_t getCurrentTime() const = 0; - /** - * \brief Gets the current player lateness - * \return the current player lateness - * \note The lateness is fixed point 32:32 representated in seconds - */ - virtual uint64_t getCurrentLateness() const = 0; - /** - * \brief Gets the current CPU use for the running processing unit - * \return the current CPU use - */ - virtual double getCurrentCPUUsage() const = 0; - /** - * \brief Gets the current fast forward factor to be used when the getStatus states the player runs in fast forward mode - * \return the current fast forward factor - */ - virtual double getCurrentFastForwardMaximumFactor() const = 0; - - //@} - /** \name Player control */ - //@{ - - /** - * \brief Stops player execution - * \return \e true in case of success. - * \return \e false in case of error. - * \warning Once the player is stopped, there's no way to restart it - */ - virtual bool stop() = 0; - /** - * \brief Pauses player execution - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool pause() = 0; - /** - * \brief Makes player run normal speed - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool play() = 0; - /** - * \brief Makes player run as fast as possible - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool forward() = 0; - /** - * \brief Gets current player status - * \return current player status - */ - virtual EPlayerStatus getStatus() const = 0; - - //@} - /** \name Give access to some managers */ - //@{ - - /** - * \brief Gets the current player's configuration manager - * \return The current player's configuration manager - * - * \warning The plugin object should not use this reference after it - * has finished its work, it could be deprecated. - */ - virtual IConfigurationManager& getConfigurationManager() const = 0; - /** - * \brief Gets the current player's algorithm manager - * \return The current player's algorithm manager - * - * \warning The plugin object should not use this reference after it - * has finished its work, it could be deprecated. - */ - virtual IAlgorithmManager& getAlgorithmManager() const = 0; - /** - * \brief Gets the current player's log manager - * \return The current player's log manager - * - * \warning The plugin object should not use this reference after it - * has finished its work, it could be deprecated. - */ - virtual ILogManager& getLogManager() const = 0; - /** - * \brief Gets the current player's error manager - * \return The current player's error manager - * - * \warning The plugin object should not use this reference after it - * has finished its work, it could be deprecated. - */ - virtual IErrorManager& getErrorManager() const = 0; - - /** - * \brief Gets the current player's scenario manager - * \return The current player's scenario manager - * - * \warning The plugin object should not use this reference after it - * has finished its work, it could be deprecated. - */ - virtual IScenarioManager& getScenarioManager() const = 0; - /** - * \brief Gets the current player's type manager - * \return The current player's type manager - * - * \warning The plugin object should not use this reference after it - * has finished its work, it could be deprecated. - */ - virtual ITypeManager& getTypeManager() const = 0; - - virtual bool canCreatePluginObject(const CIdentifier& pluginID) const = 0; - virtual Plugins::IPluginObject* createPluginObject(const CIdentifier& pluginID) const = 0; - virtual bool releasePluginObject(Plugins::IPluginObject* pluginObject) const = 0; - - //@} - - _IsDerivedFromClass_(IKernelObject, OV_ClassId_Kernel_Player_PlayerContext) - }; - } // namespace Kernel +public: + + /** \name Time management */ + //@{ + + /** + * \brief Gets the current player time + * \return the current player time. + * \note The time value is fixed point 32:32 representated in seconds + */ + virtual uint64_t getCurrentTime() const = 0; + /** + * \brief Gets the current player lateness + * \return the current player lateness + * \note The lateness is fixed point 32:32 representated in seconds + */ + virtual uint64_t getCurrentLateness() const = 0; + /** + * \brief Gets the current CPU use for the running processing unit + * \return the current CPU use + */ + virtual double getCurrentCPUUsage() const = 0; + /** + * \brief Gets the current fast forward factor to be used when the getStatus states the player runs in fast forward mode + * \return the current fast forward factor + */ + virtual double getCurrentFastForwardMaximumFactor() const = 0; + + //@} + /** \name Player control */ + //@{ + + /** + * \brief Stops player execution + * \return \e true in case of success. + * \return \e false in case of error. + * \warning Once the player is stopped, there's no way to restart it + */ + virtual bool stop() = 0; + /** + * \brief Pauses player execution + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool pause() = 0; + /** + * \brief Makes player run normal speed + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool play() = 0; + /** + * \brief Makes player run as fast as possible + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool forward() = 0; + /** + * \brief Gets current player status + * \return current player status + */ + virtual EPlayerStatus getStatus() const = 0; + + //@} + /** \name Give access to some managers */ + //@{ + + /** + * \brief Gets the current player's configuration manager + * \return The current player's configuration manager + * + * \warning The plugin object should not use this reference after it + * has finished its work, it could be deprecated. + */ + virtual IConfigurationManager& getConfigurationManager() const = 0; + /** + * \brief Gets the current player's algorithm manager + * \return The current player's algorithm manager + * + * \warning The plugin object should not use this reference after it + * has finished its work, it could be deprecated. + */ + virtual IAlgorithmManager& getAlgorithmManager() const = 0; + /** + * \brief Gets the current player's log manager + * \return The current player's log manager + * + * \warning The plugin object should not use this reference after it + * has finished its work, it could be deprecated. + */ + virtual ILogManager& getLogManager() const = 0; + /** + * \brief Gets the current player's error manager + * \return The current player's error manager + * + * \warning The plugin object should not use this reference after it + * has finished its work, it could be deprecated. + */ + virtual IErrorManager& getErrorManager() const = 0; + + /** + * \brief Gets the current player's scenario manager + * \return The current player's scenario manager + * + * \warning The plugin object should not use this reference after it + * has finished its work, it could be deprecated. + */ + virtual IScenarioManager& getScenarioManager() const = 0; + /** + * \brief Gets the current player's type manager + * \return The current player's type manager + * + * \warning The plugin object should not use this reference after it + * has finished its work, it could be deprecated. + */ + virtual ITypeManager& getTypeManager() const = 0; + + virtual bool canCreatePluginObject(const CIdentifier& pluginID) const = 0; + virtual Plugins::IPluginObject* createPluginObject(const CIdentifier& pluginID) const = 0; + virtual bool releasePluginObject(Plugins::IPluginObject* pluginObject) const = 0; + + //@} + + _IsDerivedFromClass_(IKernelObject, OV_ClassId_Kernel_Player_PlayerContext) +}; +} // namespace Kernel } // namespace OpenViBE diff --git a/openvibe/include/openvibe/kernel/player/ovIPlayerManager.h b/openvibe/include/openvibe/kernel/player/ovIPlayerManager.h index ed44183f670d2c70323307ebd216ac7fb6eea4be..5136550afe108349fff926d812337e95eb831ac7 100644 --- a/openvibe/include/openvibe/kernel/player/ovIPlayerManager.h +++ b/openvibe/include/openvibe/kernel/player/ovIPlayerManager.h @@ -2,66 +2,64 @@ #include "../ovIKernelObject.h" -namespace OpenViBE -{ - namespace Kernel - { - class IPlayer; +namespace OpenViBE { +namespace Kernel { +class IPlayer; - /** - * \class IPlayerManager - * \author Yann Renard (INRIA/IRISA) - * \date 2006-07-21 - * \brief The manager responsible for scenario playback - * \ingroup Group_Player - * \ingroup Group_Kernel - * - * The player manager is responsible for creating the different player - * instances. Each player is responsible for the playback of a specific - * scenario. - */ - class OV_API IPlayerManager : public IKernelObject - { - public: +/** + * \class IPlayerManager + * \author Yann Renard (INRIA/IRISA) + * \date 2006-07-21 + * \brief The manager responsible for scenario playback + * \ingroup Group_Player + * \ingroup Group_Kernel + * + * The player manager is responsible for creating the different player + * instances. Each player is responsible for the playback of a specific + * scenario. + */ +class OV_API IPlayerManager : public IKernelObject +{ +public: - /** - * \brief Creates a new player - * \param id [out] : the identifier of the created player - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool createPlayer(CIdentifier& id) = 0; - /** - * \brief Releases a specific player - * \param id [in] : the identifier of the player to release - * \return \e true in case of success. - * \return \e false in case of error. - * - * Releasing a player means the player instance won't be used any more, - * thus the player manager can release any allocated resource / memory - * for this player. - */ - virtual bool releasePlayer(const CIdentifier& id) = 0; - /** - * \brief Gets a specific player instance, provided its identifier - * \param id [in] : the identifier of the player instance to return - * \return A reference on the player instance - * \warning Using a non player identifier will cause a crash - */ - virtual IPlayer& getPlayer(const CIdentifier& id) = 0; - /** - * \brief Gets next player identifier - * \param previousID [in] : The identifier - * for the preceeding player - * \return The identifier of the next player in case of success. - * \return \c OV_UndefinedIdentifier on error. - * \note Giving \c OV_UndefinedIdentifier as \c previousID - * will cause this function to return the first player - * identifier. - */ - virtual CIdentifier getNextPlayerIdentifier(const CIdentifier& previousID) const = 0; + /** + * \brief Creates a new player + * \param id [out] : the identifier of the created player + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool createPlayer(CIdentifier& id) = 0; + /** + * \brief Releases a specific player + * \param id [in] : the identifier of the player to release + * \return \e true in case of success. + * \return \e false in case of error. + * + * Releasing a player means the player instance won't be used any more, + * thus the player manager can release any allocated resource / memory + * for this player. + */ + virtual bool releasePlayer(const CIdentifier& id) = 0; + /** + * \brief Gets a specific player instance, provided its identifier + * \param id [in] : the identifier of the player instance to return + * \return A reference on the player instance + * \warning Using a non player identifier will cause a crash + */ + virtual IPlayer& getPlayer(const CIdentifier& id) = 0; + /** + * \brief Gets next player identifier + * \param previousID [in] : The identifier + * for the preceeding player + * \return The identifier of the next player in case of success. + * \return \c OV_UndefinedIdentifier on error. + * \note Giving \c OV_UndefinedIdentifier as \c previousID + * will cause this function to return the first player + * identifier. + */ + virtual CIdentifier getNextPlayerIdentifier(const CIdentifier& previousID) const = 0; - _IsDerivedFromClass_(IKernelObject, OV_ClassId_Kernel_Player_PlayerManager) - }; - } // namespace Kernel -} // namespace OpenViBE + _IsDerivedFromClass_(IKernelObject, OV_ClassId_Kernel_Player_PlayerManager) +}; +} // namespace Kernel +} // namespace OpenViBE diff --git a/openvibe/include/openvibe/kernel/plugins/ovIPluginManager.h b/openvibe/include/openvibe/kernel/plugins/ovIPluginManager.h index 9f0619072aaeb33fc954217d5ba4c527fe4ec0b2..3a9385f7668a3e93ea8ec84b3e6e16f193a06422 100755 --- a/openvibe/include/openvibe/kernel/plugins/ovIPluginManager.h +++ b/openvibe/include/openvibe/kernel/plugins/ovIPluginManager.h @@ -2,199 +2,196 @@ #include "../ovIKernelObject.h" -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +class IPluginObject; +class IPluginObjectDesc; + +class IBoxAlgorithm; +class IBoxAlgorithmDesc; + +class IAlgorithm; +class IAlgorithmDesc; +} // namespace Plugins + +namespace Kernel { +// class IPluginModule; + +/** + * \class IPluginManager + * \brief Log manager + * \author Yann Renard (INRIA/IRISA) + * \date 2006-09-26 + * \ingroup Group_Plugins + * \ingroup Group_Kernel + * + * The plugin manager is in charge of loading/unloading plugin + * modules (ie DLL/so files) containing OpenViBE plugins. + * It also provides functions in order to list plugin descriptors, + * create or release plugin objects... + */ +class OV_API IPluginManager : public IKernelObject { - namespace Plugins - { - class IPluginObject; - class IPluginObjectDesc; - - class IBoxAlgorithm; - class IBoxAlgorithmDesc; - - class IAlgorithm; - class IAlgorithmDesc; - } // namespace Plugins - - namespace Kernel - { - // class IPluginModule; - - /** - * \class IPluginManager - * \brief Log manager - * \author Yann Renard (INRIA/IRISA) - * \date 2006-09-26 - * \ingroup Group_Plugins - * \ingroup Group_Kernel - * - * The plugin manager is in charge of loading/unloading plugin - * modules (ie DLL/so files) containing OpenViBE plugins. - * It also provides functions in order to list plugin descriptors, - * create or release plugin objects... - */ - class OV_API IPluginManager : public IKernelObject - { - public: - - /** \name Plugin modules/descriptors management */ - //@{ - - /** - * \brief Loads new DLL/so plugin module file(s) - * \param fileNameWildCard [in] : a wild card with the file(s) to search plugins in - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool addPluginsFromFiles(const CString& fileNameWildCard) = 0; - /** - * \brief Registers a plugin object descriptor - * \param desc [in] : the actual plugin object descriptor to register - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool registerPluginDesc(const Plugins::IPluginObjectDesc& desc) = 0; - /** - * \brief Gets next plugin object descriptor identifier - * \param previousID [in] : The identifier - * for the preceeding plugin object descriptor - * \return The identifier of the next plugin object descriptor in case of success. - * \return \c OV_UndefinedIdentifier on error. - * \note Giving \c OV_UndefinedIdentifier as \c previousID - * will cause this function to return the first plugin object - * descriptor identifier. - */ - virtual CIdentifier getNextPluginObjectDescIdentifier(const CIdentifier& previousID) const = 0; - /** - * \brief Gets next plugin object descriptor identifier given a base class identifier - * \param previousID [in] : The identifier - * for the preceeding plugin object descriptor - * \param baseClassID [in] : the class the plugin object descriptor should derive from - * \return The identifier of the next plugin object descriptor in case of success. - * \return \c OV_UndefinedIdentifier on error. - * \note Giving \c OV_UndefinedIdentifier as \c previousID - * will cause this function to return the first plugin object - * descriptor identifier. - */ - virtual CIdentifier getNextPluginObjectDescIdentifier(const CIdentifier& previousID, const CIdentifier& baseClassID) const = 0; - /** - * \brief Checks if a plugin object can be created or not - * \param classID [in] : the class identifier a descriptor should be able to create - * \return \e true in case this manager is able to create a plugin object with the provided class identifier. - * \return \e false in other case. - */ - virtual bool canCreatePluginObject(const CIdentifier& classID) = 0; - /** - * \brief Gets details on a specific plugin object descriptor - * \param id [in] : the plugin object descriptor id which details should be returned - * \return the corresponding plugin object descriptor pointer. - * \sa getNextPluginObjectDescIdentifier - */ - virtual const Plugins::IPluginObjectDesc* getPluginObjectDesc(const CIdentifier& id) const = 0; - /** - * \brief Gets details on a specific plugin object descriptor given the class identifier it should create - * \param classID [in] : the plugin object class identifier of the descriptor which details should be returned - * \return the corresponding plugin object descriptor pointer. - * \sa canCreatePluginObject - */ - virtual const Plugins::IPluginObjectDesc* getPluginObjectDescCreating(const CIdentifier& classID) const = 0; - - //@} - /** \name Plugin lifetime management */ - //@{ - - /** - * \brief Gets a hash value for a given plugin - * \param classID [in] : the class identifier of the plugin which hash value - * has to be returned - * \return a hash code for the corresponding plugin object - * - * This function can be used to compute a has code of the described plugin object - * If this hash code differs from session to session, it means that the plugin - * descriptor changed in some way. - * - * \note The method used to compute the hash code is specific to the class - * of plugin that is considered (for example, for box algorithms, the - * hash code is based on what IBoxProto receives at - * description stage) - */ - virtual CIdentifier getPluginObjectHashValue(const CIdentifier& classID) const = 0; - - virtual CIdentifier getPluginObjectHashValue(const Plugins::IBoxAlgorithmDesc& boxAlgorithmDesc) const = 0; - /** - * \brief Gets a hint whether a plugin is deprecated or not - * \param classID [in] : the class identifier of the plugin which deprecation should be returned - * \return \e true in case the plugin is deprecated - * \return \e false in case the plugin is not deprecated - * - * If this function returns \e true, this means that the considered - * plugin is still valid and functionnal but that it will - * be removed soon or later. Code relying on this plugin - * should consider any alternative available to avoid future problems. - */ - virtual bool isPluginObjectFlaggedAsDeprecated(const CIdentifier& classID) const = 0; - - //@} - /** \name Plugin creation and destruction */ - //@{ - - /** - * \brief Creates a new plugin object given its class identifier - * \param classID [in] : the class identifier of the plugin object to create - * \return a pointer on the newly created plugin object. - * \return \c NULL in case of error. - * \sa releasePluginObject - */ - virtual Plugins::IPluginObject* createPluginObject(const CIdentifier& classID) = 0; - /** - * \brief Tells the plugin manager a plugin object won't be ever used - * \param pluginObject [in] : the plugin object to release - * \return \e true in case of success. - * \return \e false in case of error. - * - * The client code should not call any function of the plugin object after this - * call has been made. However, the plugin manager is free to release allocated memory - * and resources for this plugin object. - */ - virtual bool releasePluginObject(Plugins::IPluginObject* pluginObject) = 0; - - //@{ - /**\name Helpers */ - //@{ - - /** - * \brief Creates a new algorithm given its class identifier and eventually returns the associated descriptor - * \param classID [in] : the class identifier of the algorithm to create - * \param desc [out] : a pointer where to store the descriptor information - * \return The newly created algorithm in case of success. - * \return \c NULL in case of error. - * - * This function is a helper for the use of \c createPluginObject and co. - */ - virtual Plugins::IAlgorithm* createAlgorithm(const CIdentifier& classID, const Plugins::IAlgorithmDesc** desc) = 0; - /** - * \brief Creates a new algorithm given a descriptor - * \param desc [in] : the class descriptor of the algorithm to create - * \return The newly created algorithm in case of success. - * \return \c NULL in case of error. - * - * This function is a helper for the use of \c createPluginObject and co. - */ - virtual Plugins::IAlgorithm* createAlgorithm(const Plugins::IAlgorithmDesc& desc) = 0; - /** - * \brief Creates a new box algorithm given its class identifier and eventually returns the associated descriptor - * \param classID [in] : the class identifier of the box algorithm to create - * \param desc [out] : a pointer where to store the descriptor information - * \return The newly created box algorithm in case of success. - * \return \c NULL in case of error. - * - * This function is a helper for the use of \c createPluginObject and co. - */ - virtual Plugins::IBoxAlgorithm* createBoxAlgorithm(const CIdentifier& classID, const Plugins::IBoxAlgorithmDesc** desc) = 0; - - //@} - - _IsDerivedFromClass_(IKernelObject, OV_ClassId_Kernel_Plugins_PluginManager) - }; - } // namespace Kernel -} // namespace OpenViBE +public: + + /** \name Plugin modules/descriptors management */ + //@{ + + /** + * \brief Loads new DLL/so plugin module file(s) + * \param fileNameWildCard [in] : a wild card with the file(s) to search plugins in + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool addPluginsFromFiles(const CString& fileNameWildCard) = 0; + /** + * \brief Registers a plugin object descriptor + * \param desc [in] : the actual plugin object descriptor to register + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool registerPluginDesc(const Plugins::IPluginObjectDesc& desc) = 0; + /** + * \brief Gets next plugin object descriptor identifier + * \param previousID [in] : The identifier + * for the preceeding plugin object descriptor + * \return The identifier of the next plugin object descriptor in case of success. + * \return \c OV_UndefinedIdentifier on error. + * \note Giving \c OV_UndefinedIdentifier as \c previousID + * will cause this function to return the first plugin object + * descriptor identifier. + */ + virtual CIdentifier getNextPluginObjectDescIdentifier(const CIdentifier& previousID) const = 0; + /** + * \brief Gets next plugin object descriptor identifier given a base class identifier + * \param previousID [in] : The identifier + * for the preceeding plugin object descriptor + * \param baseClassID [in] : the class the plugin object descriptor should derive from + * \return The identifier of the next plugin object descriptor in case of success. + * \return \c OV_UndefinedIdentifier on error. + * \note Giving \c OV_UndefinedIdentifier as \c previousID + * will cause this function to return the first plugin object + * descriptor identifier. + */ + virtual CIdentifier getNextPluginObjectDescIdentifier(const CIdentifier& previousID, const CIdentifier& baseClassID) const = 0; + /** + * \brief Checks if a plugin object can be created or not + * \param classID [in] : the class identifier a descriptor should be able to create + * \return \e true in case this manager is able to create a plugin object with the provided class identifier. + * \return \e false in other case. + */ + virtual bool canCreatePluginObject(const CIdentifier& classID) = 0; + /** + * \brief Gets details on a specific plugin object descriptor + * \param id [in] : the plugin object descriptor id which details should be returned + * \return the corresponding plugin object descriptor pointer. + * \sa getNextPluginObjectDescIdentifier + */ + virtual const Plugins::IPluginObjectDesc* getPluginObjectDesc(const CIdentifier& id) const = 0; + /** + * \brief Gets details on a specific plugin object descriptor given the class identifier it should create + * \param classID [in] : the plugin object class identifier of the descriptor which details should be returned + * \return the corresponding plugin object descriptor pointer. + * \sa canCreatePluginObject + */ + virtual const Plugins::IPluginObjectDesc* getPluginObjectDescCreating(const CIdentifier& classID) const = 0; + + //@} + /** \name Plugin lifetime management */ + //@{ + + /** + * \brief Gets a hash value for a given plugin + * \param classID [in] : the class identifier of the plugin which hash value + * has to be returned + * \return a hash code for the corresponding plugin object + * + * This function can be used to compute a has code of the described plugin object + * If this hash code differs from session to session, it means that the plugin + * descriptor changed in some way. + * + * \note The method used to compute the hash code is specific to the class + * of plugin that is considered (for example, for box algorithms, the + * hash code is based on what IBoxProto receives at + * description stage) + */ + virtual CIdentifier getPluginObjectHashValue(const CIdentifier& classID) const = 0; + + virtual CIdentifier getPluginObjectHashValue(const Plugins::IBoxAlgorithmDesc& boxAlgorithmDesc) const = 0; + /** + * \brief Gets a hint whether a plugin is deprecated or not + * \param classID [in] : the class identifier of the plugin which deprecation should be returned + * \return \e true in case the plugin is deprecated + * \return \e false in case the plugin is not deprecated + * + * If this function returns \e true, this means that the considered + * plugin is still valid and functionnal but that it will + * be removed soon or later. Code relying on this plugin + * should consider any alternative available to avoid future problems. + */ + virtual bool isPluginObjectFlaggedAsDeprecated(const CIdentifier& classID) const = 0; + + //@} + /** \name Plugin creation and destruction */ + //@{ + + /** + * \brief Creates a new plugin object given its class identifier + * \param classID [in] : the class identifier of the plugin object to create + * \return a pointer on the newly created plugin object. + * \return \c NULL in case of error. + * \sa releasePluginObject + */ + virtual Plugins::IPluginObject* createPluginObject(const CIdentifier& classID) = 0; + /** + * \brief Tells the plugin manager a plugin object won't be ever used + * \param pluginObject [in] : the plugin object to release + * \return \e true in case of success. + * \return \e false in case of error. + * + * The client code should not call any function of the plugin object after this + * call has been made. However, the plugin manager is free to release allocated memory + * and resources for this plugin object. + */ + virtual bool releasePluginObject(Plugins::IPluginObject* pluginObject) = 0; + + //@{ + /**\name Helpers */ + //@{ + + /** + * \brief Creates a new algorithm given its class identifier and eventually returns the associated descriptor + * \param classID [in] : the class identifier of the algorithm to create + * \param desc [out] : a pointer where to store the descriptor information + * \return The newly created algorithm in case of success. + * \return \c NULL in case of error. + * + * This function is a helper for the use of \c createPluginObject and co. + */ + virtual Plugins::IAlgorithm* createAlgorithm(const CIdentifier& classID, const Plugins::IAlgorithmDesc** desc) = 0; + /** + * \brief Creates a new algorithm given a descriptor + * \param desc [in] : the class descriptor of the algorithm to create + * \return The newly created algorithm in case of success. + * \return \c NULL in case of error. + * + * This function is a helper for the use of \c createPluginObject and co. + */ + virtual Plugins::IAlgorithm* createAlgorithm(const Plugins::IAlgorithmDesc& desc) = 0; + /** + * \brief Creates a new box algorithm given its class identifier and eventually returns the associated descriptor + * \param classID [in] : the class identifier of the box algorithm to create + * \param desc [out] : a pointer where to store the descriptor information + * \return The newly created box algorithm in case of success. + * \return \c NULL in case of error. + * + * This function is a helper for the use of \c createPluginObject and co. + */ + virtual Plugins::IBoxAlgorithm* createBoxAlgorithm(const CIdentifier& classID, const Plugins::IBoxAlgorithmDesc** desc) = 0; + + //@} + + _IsDerivedFromClass_(IKernelObject, OV_ClassId_Kernel_Plugins_PluginManager) +}; +} // namespace Kernel +} // namespace OpenViBE diff --git a/openvibe/include/openvibe/kernel/plugins/ovIPluginModule.h b/openvibe/include/openvibe/kernel/plugins/ovIPluginModule.h index 8e91ab26ea0295853920d79455ade77e3e05475c..6b10b559e12276d85fc8e8baac86de33560c0536 100644 --- a/openvibe/include/openvibe/kernel/plugins/ovIPluginModule.h +++ b/openvibe/include/openvibe/kernel/plugins/ovIPluginModule.h @@ -2,91 +2,88 @@ #include "../ovIKernelObject.h" -namespace OpenViBE -{ - namespace Plugins - { - class IPluginObjectDesc; - } // namespace Plugins +namespace OpenViBE { +namespace Plugins { +class IPluginObjectDesc; +} // namespace Plugins - namespace Kernel - { - /** - * \class IPluginModule - * \brief Plugin module - * \author Yann Renard (INRIA/IRISA) - * \date 2006-09-26 - * \ingroup Group_Plugins - * \ingroup Group_Kernel - * - * Each plugin module is exactly responsible for one module - * (ie DLL/so file) containing OpenViBE plugins. It is - * able to load/unload this file and to enumerate each of - * its plugin object descriptor. - */ - class OV_API IPluginModule : public IKernelObject - { - public: +namespace Kernel { +/** + * \class IPluginModule + * \brief Plugin module + * \author Yann Renard (INRIA/IRISA) + * \date 2006-09-26 + * \ingroup Group_Plugins + * \ingroup Group_Kernel + * + * Each plugin module is exactly responsible for one module + * (ie DLL/so file) containing OpenViBE plugins. It is + * able to load/unload this file and to enumerate each of + * its plugin object descriptor. + */ +class OV_API IPluginModule : public IKernelObject +{ +public: - /** - * \brief Tries to load a file as an OpenViBE module - * \param name [in] : the name of the file to try to load - * \param error [out] : an optional output string containing the error on load failure - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool load(const CString& name, CString* error = nullptr) = 0; - /** - * \brief Tries to unload the loaded OpenViBE module - * \param error [out] : an optional output string containing the error on unload failure - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool unload(CString* error = nullptr) = 0; - /** - * \brief Gets the current filename associated with this plugin module - * \param fileName [out] : the filename of this plugin module - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool getFileName(CString& fileName) const = 0; - /** - * \brief Initializes this plugin module - * \return \e true in case of success. - * \return \e false in case of error. - * - * This function calls the onInitialize main function of the plugin module. - */ - virtual bool initialize() = 0; - /** - * \brief Gets a specific plugin object descriptor - * \param index [in] : the index of the plugin object descriptor to get - * \param desc [out] : a pointer on the associated plugin object descriptor - * \return \e true in case of success. - * \return \e false in case of error. - * - * This function should be called with \c index ranging from 0 to - * the number of plugin object descriptor - 1. The number of plugin object - * descriptor is known as soon as this function returns \e false meaning - * there are no more descriptors to return. - * - * This function calls the onGetPluginObjectDescription main function of the plugin module. - * - * \note \c desc can be \c NULL even if the function returned \e true - * \note \c desc IS \c NULL if the function returned \e false - * \note It is ok to call this function several times for a same index. - */ - virtual bool getPluginObjectDescription(size_t index, Plugins::IPluginObjectDesc*& desc) = 0; - /** - * \brief Uninitializes this plugin module - * \return \e true in case of success. - * \return \e false in case of error. - * - * This function calls the onUninitialize main function of the plugin module. - */ - virtual bool uninitialize() = 0; + /** + * \brief Tries to load a file as an OpenViBE module + * \param name [in] : the name of the file to try to load + * \param error [out] : an optional output string containing the error on load failure + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool load(const CString& name, CString* error = nullptr) = 0; + /** + * \brief Tries to unload the loaded OpenViBE module + * \param error [out] : an optional output string containing the error on unload failure + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool unload(CString* error = nullptr) = 0; + /** + * \brief Gets the current filename associated with this plugin module + * \param fileName [out] : the filename of this plugin module + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool getFileName(CString& fileName) const = 0; + /** + * \brief Initializes this plugin module + * \return \e true in case of success. + * \return \e false in case of error. + * + * This function calls the onInitialize main function of the plugin module. + */ + virtual bool initialize() = 0; + /** + * \brief Gets a specific plugin object descriptor + * \param index [in] : the index of the plugin object descriptor to get + * \param desc [out] : a pointer on the associated plugin object descriptor + * \return \e true in case of success. + * \return \e false in case of error. + * + * This function should be called with \c index ranging from 0 to + * the number of plugin object descriptor - 1. The number of plugin object + * descriptor is known as soon as this function returns \e false meaning + * there are no more descriptors to return. + * + * This function calls the onGetPluginObjectDescription main function of the plugin module. + * + * \note \c desc can be \c NULL even if the function returned \e true + * \note \c desc IS \c NULL if the function returned \e false + * \note It is ok to call this function several times for a same index. + */ + virtual bool getPluginObjectDescription(size_t index, Plugins::IPluginObjectDesc*& desc) = 0; + /** + * \brief Uninitializes this plugin module + * \return \e true in case of success. + * \return \e false in case of error. + * + * This function calls the onUninitialize main function of the plugin module. + */ + virtual bool uninitialize() = 0; - _IsDerivedFromClass_(IKernelObject, OV_ClassId_Kernel_Plugins_PluginModule) - }; - } // namespace Kernel + _IsDerivedFromClass_(IKernelObject, OV_ClassId_Kernel_Plugins_PluginModule) +}; +} // namespace Kernel } // namespace OpenViBE diff --git a/openvibe/include/openvibe/kernel/plugins/ovIPluginModuleContext.h b/openvibe/include/openvibe/kernel/plugins/ovIPluginModuleContext.h index a3b3dbe84779d6b274d8d5ea1b93b58b42193b11..eab1d6d3b8a257b684e493af46ae8eb981aed50d 100644 --- a/openvibe/include/openvibe/kernel/plugins/ovIPluginModuleContext.h +++ b/openvibe/include/openvibe/kernel/plugins/ovIPluginModuleContext.h @@ -2,56 +2,54 @@ #include "../ovIKernelObject.h" -namespace OpenViBE -{ - namespace Kernel - { - class ILogManager; - class ITypeManager; - class IScenarioManager; - class IErrorManager; - class IConfigurationManager; +namespace OpenViBE { +namespace Kernel { +class ILogManager; +class ITypeManager; +class IScenarioManager; +class IErrorManager; +class IConfigurationManager; - /** - * \class IPluginModuleContext - * \brief Plugin context - * \author Yann Renard (INRIA/IRISA) - * \date 2007-06-20 - * \ingroup Group_Plugins - * \ingroup Group_Kernel - * \ingroup Group_Extend - */ - class OV_API IPluginModuleContext : public IKernelObject - { - public: +/** + * \class IPluginModuleContext + * \brief Plugin context + * \author Yann Renard (INRIA/IRISA) + * \date 2007-06-20 + * \ingroup Group_Plugins + * \ingroup Group_Kernel + * \ingroup Group_Extend + */ +class OV_API IPluginModuleContext : public IKernelObject +{ +public: - /** - * \brief Gets the current scenario manager - * \return a reference on the current scenario manager - */ - virtual IScenarioManager& getScenarioManager() const = 0; - /** - * \brief Gets the current type manager - * \return a reference on the current type manager - */ - virtual ITypeManager& getTypeManager() const = 0; - /** - * \brief Gets the current log manager - * \return a reference on the current log manager - */ - virtual ILogManager& getLogManager() const = 0; - /** - * \brief Gets the current error manager - * \return a reference on the current error manager - */ - virtual IErrorManager& getErrorManager() const = 0; - /** - * \brief Gets the current configuration manager - * \return a reference on the current configuration manager - */ - virtual IConfigurationManager& getConfigurationManager() const = 0; + /** + * \brief Gets the current scenario manager + * \return a reference on the current scenario manager + */ + virtual IScenarioManager& getScenarioManager() const = 0; + /** + * \brief Gets the current type manager + * \return a reference on the current type manager + */ + virtual ITypeManager& getTypeManager() const = 0; + /** + * \brief Gets the current log manager + * \return a reference on the current log manager + */ + virtual ILogManager& getLogManager() const = 0; + /** + * \brief Gets the current error manager + * \return a reference on the current error manager + */ + virtual IErrorManager& getErrorManager() const = 0; + /** + * \brief Gets the current configuration manager + * \return a reference on the current configuration manager + */ + virtual IConfigurationManager& getConfigurationManager() const = 0; - _IsDerivedFromClass_(IKernelObject, OV_ClassId_Kernel_Plugins_PluginModuleContext) - }; - } // namespace Kernel -} // namespace OpenViBE + _IsDerivedFromClass_(IKernelObject, OV_ClassId_Kernel_Plugins_PluginModuleContext) +}; +} // namespace Kernel +} // namespace OpenViBE diff --git a/openvibe/include/openvibe/kernel/scenario/ovIAlgorithmScenarioExporter.h b/openvibe/include/openvibe/kernel/scenario/ovIAlgorithmScenarioExporter.h index 6abe515059b0ac490f78169b7709c97c0d775ed5..2dfaf0c6b9a67e6871ead5322f1037c9d2bef9de 100644 --- a/openvibe/include/openvibe/kernel/scenario/ovIAlgorithmScenarioExporter.h +++ b/openvibe/include/openvibe/kernel/scenario/ovIAlgorithmScenarioExporter.h @@ -8,33 +8,31 @@ #define OV_Algorithm_ScenarioExporter_InputParameterId_Scenario OpenViBE::CIdentifier(0x5B9C0D54, 0x04BA2957) #define OV_Algorithm_ScenarioExporter_OutputParameterId_MemoryBuffer OpenViBE::CIdentifier(0x64030633, 0x419E3A33) -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +class OV_API IAlgorithmScenarioExporter : public IAlgorithm { - namespace Plugins - { - class OV_API IAlgorithmScenarioExporter : public IAlgorithm - { - public: - virtual bool exportStart(IMemoryBuffer& buffer, const CIdentifier& id) = 0; - virtual bool exportIdentifier(IMemoryBuffer& buffer, const CIdentifier& id, const CIdentifier& value) = 0; - virtual bool exportString(IMemoryBuffer& buffer, const CIdentifier& id, const CString& value) = 0; - virtual bool exportUInteger(IMemoryBuffer& buffer, const CIdentifier& id, uint64_t value) = 0; - virtual bool exportStop(IMemoryBuffer& buffer) = 0; +public: + virtual bool exportStart(IMemoryBuffer& buffer, const CIdentifier& id) = 0; + virtual bool exportIdentifier(IMemoryBuffer& buffer, const CIdentifier& id, const CIdentifier& value) = 0; + virtual bool exportString(IMemoryBuffer& buffer, const CIdentifier& id, const CString& value) = 0; + virtual bool exportUInteger(IMemoryBuffer& buffer, const CIdentifier& id, uint64_t value) = 0; + virtual bool exportStop(IMemoryBuffer& buffer) = 0; - _IsDerivedFromClass_(IAlgorithm, OV_UndefinedIdentifier) - }; + _IsDerivedFromClass_(IAlgorithm, OV_UndefinedIdentifier) +}; - class OV_API IAlgorithmScenarioExporterDesc : public IAlgorithmDesc - { - public: - bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override - { - prototype.addInputParameter(OV_Algorithm_ScenarioExporter_InputParameterId_Scenario, "Scenario", Kernel::ParameterType_Object); - prototype.addOutputParameter(OV_Algorithm_ScenarioExporter_OutputParameterId_MemoryBuffer, "Memory buffer", Kernel::ParameterType_MemoryBuffer); - return true; - } +class OV_API IAlgorithmScenarioExporterDesc : public IAlgorithmDesc +{ +public: + bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override + { + prototype.addInputParameter(OV_Algorithm_ScenarioExporter_InputParameterId_Scenario, "Scenario", Kernel::ParameterType_Object); + prototype.addOutputParameter(OV_Algorithm_ScenarioExporter_OutputParameterId_MemoryBuffer, "Memory buffer", Kernel::ParameterType_MemoryBuffer); + return true; + } - _IsDerivedFromClass_(IAlgorithmDesc, OV_UndefinedIdentifier) - }; - } // namespace Plugins -} // namespace OpenViBE + _IsDerivedFromClass_(IAlgorithmDesc, OV_UndefinedIdentifier) +}; +} // namespace Plugins +} // namespace OpenViBE diff --git a/openvibe/include/openvibe/kernel/scenario/ovIAlgorithmScenarioImporter.h b/openvibe/include/openvibe/kernel/scenario/ovIAlgorithmScenarioImporter.h index e8945b26baa82564cc23bb7c9a3c161b46b91970..6bfca491d4ade954a5af45f8a163d36d21e426fa 100644 --- a/openvibe/include/openvibe/kernel/scenario/ovIAlgorithmScenarioImporter.h +++ b/openvibe/include/openvibe/kernel/scenario/ovIAlgorithmScenarioImporter.h @@ -8,38 +8,36 @@ #define OV_Algorithm_ScenarioImporter_OutputParameterId_Scenario OpenViBE::CIdentifier(0x29574C87, 0x7BA77780) #define OV_Algorithm_ScenarioImporter_InputParameterId_MemoryBuffer OpenViBE::CIdentifier(0x600463A3, 0x474B7F66) -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +class OV_API IAlgorithmScenarioImporterContext : public IObject { - namespace Plugins +public: + + virtual bool processStart(const CIdentifier& id) = 0; + virtual bool processIdentifier(const CIdentifier& id, const CIdentifier& value) = 0; + virtual bool processString(const CIdentifier& id, const CString& value) = 0; + virtual bool processUInteger(const CIdentifier& id, uint64_t value) = 0; + virtual bool processStop() = 0; + + _IsDerivedFromClass_(IObject, OV_UndefinedIdentifier) +}; + +class OV_API IAlgorithmScenarioImporter : public IAlgorithm +{ +public: + virtual bool import(IAlgorithmScenarioImporterContext& ctx, const IMemoryBuffer& buffer) = 0; +}; + + +class OV_API IAlgorithmScenarioImporterDesc : public IAlgorithmDesc +{ + bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override { - class OV_API IAlgorithmScenarioImporterContext : public IObject - { - public: - - virtual bool processStart(const CIdentifier& id) = 0; - virtual bool processIdentifier(const CIdentifier& id, const CIdentifier& value) = 0; - virtual bool processString(const CIdentifier& id, const CString& value) = 0; - virtual bool processUInteger(const CIdentifier& id, uint64_t value) = 0; - virtual bool processStop() = 0; - - _IsDerivedFromClass_(IObject, OV_UndefinedIdentifier) - }; - - class OV_API IAlgorithmScenarioImporter : public IAlgorithm - { - public: - virtual bool import(IAlgorithmScenarioImporterContext& ctx, const IMemoryBuffer& buffer) = 0; - }; - - - class OV_API IAlgorithmScenarioImporterDesc : public IAlgorithmDesc - { - bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override - { - prototype.addOutputParameter(OV_Algorithm_ScenarioImporter_OutputParameterId_Scenario, "Scenario", Kernel::ParameterType_Object); - prototype.addInputParameter(OV_Algorithm_ScenarioImporter_InputParameterId_MemoryBuffer, "Memory buffer", Kernel::ParameterType_MemoryBuffer); - return true; - } - }; - } // namespace Plugins -} // namespace OpenViBE + prototype.addOutputParameter(OV_Algorithm_ScenarioImporter_OutputParameterId_Scenario, "Scenario", Kernel::ParameterType_Object); + prototype.addInputParameter(OV_Algorithm_ScenarioImporter_InputParameterId_MemoryBuffer, "Memory buffer", Kernel::ParameterType_MemoryBuffer); + return true; + } +}; +} // namespace Plugins +} // namespace OpenViBE diff --git a/openvibe/include/openvibe/kernel/scenario/ovIAttributable.h b/openvibe/include/openvibe/kernel/scenario/ovIAttributable.h index ff8e858ff7e4aa1eee4806f78399f032c4c4503e..a7041f91c072bfb06802ac5673eff3f8f6a96d20 100644 --- a/openvibe/include/openvibe/kernel/scenario/ovIAttributable.h +++ b/openvibe/include/openvibe/kernel/scenario/ovIAttributable.h @@ -2,35 +2,33 @@ #include "../ovIKernelObject.h" -namespace OpenViBE +namespace OpenViBE { +namespace Kernel { +/** + * \class IAttributable + * \author Yann Renard (IRISA/INRIA) + * \date 2006-12-07 + * \brief + * \ingroup Group_Scenario + * \ingroup Group_Kernel + */ +class OV_API IAttributable : public IKernelObject { - namespace Kernel - { - /** - * \class IAttributable - * \author Yann Renard (IRISA/INRIA) - * \date 2006-12-07 - * \brief - * \ingroup Group_Scenario - * \ingroup Group_Kernel - */ - class OV_API IAttributable : public IKernelObject - { - public: +public: - virtual bool addAttribute(const CIdentifier& id, const CString& value) = 0; - virtual bool removeAttribute(const CIdentifier& id) = 0; - virtual bool removeAllAttributes() = 0; + virtual bool addAttribute(const CIdentifier& id, const CString& value) = 0; + virtual bool removeAttribute(const CIdentifier& id) = 0; + virtual bool removeAllAttributes() = 0; - virtual CString getAttributeValue(const CIdentifier& id) const = 0; - virtual bool setAttributeValue(const CIdentifier& id, const CString& value) = 0; + virtual CString getAttributeValue(const CIdentifier& id) const = 0; + virtual bool setAttributeValue(const CIdentifier& id, const CString& value) = 0; - virtual bool hasAttribute(const CIdentifier& id) const = 0; - virtual bool hasAttributes() const = 0; + virtual bool hasAttribute(const CIdentifier& id) const = 0; + virtual bool hasAttributes() const = 0; - virtual CIdentifier getNextAttributeIdentifier(const CIdentifier& previousID) const = 0; + virtual CIdentifier getNextAttributeIdentifier(const CIdentifier& previousID) const = 0; - _IsDerivedFromClass_(IKernelObject, OV_ClassId_Kernel_Scenario_Attributable) - }; - } // namespace Kernel -} // namespace OpenViBE + _IsDerivedFromClass_(IKernelObject, OV_ClassId_Kernel_Scenario_Attributable) +}; +} // namespace Kernel +} // namespace OpenViBE diff --git a/openvibe/include/openvibe/kernel/scenario/ovIBox.h b/openvibe/include/openvibe/kernel/scenario/ovIBox.h index 5b0b50efdb8a224af8cd2f3b383d95573cc01d37..355db330bfc55c544fc3bb636424c9f82bdd119c 100644 --- a/openvibe/include/openvibe/kernel/scenario/ovIBox.h +++ b/openvibe/include/openvibe/kernel/scenario/ovIBox.h @@ -5,682 +5,667 @@ #include <vector> -namespace OpenViBE +namespace OpenViBE { +namespace Kernel { +enum EBoxEventMessageType { SettingValueUpdate, SettingChange, SettingDelete, SettingAdd, SettingsReorder, SettingsAllChange }; + +enum EBoxInterfacorType { Setting, Input, Output }; + +class OV_API BoxEventMessage +{ +public: + EBoxEventMessageType m_Type; + int m_FirstIdx = 0; + int m_SecondIdx = 0; +}; + +/** + * \class IBox + * \author Yann Renard (IRISA/INRIA) + * \date 2006-08-16 + * \brief Complete OpenViBE box interface + * \ingroup Group_Scenario + * \ingroup Group_Kernel + * + * This interface can be used in order to fully describe an + * OpenViBE black box. It describes its identification values, + * its inputs, its outputs and its settings. + */ +class OV_API IBox : public IAttributable, public CObservable { - namespace Kernel - { - enum EBoxEventMessageType - { - SettingValueUpdate, - SettingChange, - SettingDelete, - SettingAdd, - SettingsReorder, - SettingsAllChange - }; - - enum EBoxInterfacorType - { - Setting, - Input, - Output - }; - - class OV_API BoxEventMessage - { - public: - EBoxEventMessageType m_Type; - int m_FirstIdx = 0; - int m_SecondIdx = 0; - }; - - /** - * \class IBox - * \author Yann Renard (IRISA/INRIA) - * \date 2006-08-16 - * \brief Complete OpenViBE box interface - * \ingroup Group_Scenario - * \ingroup Group_Kernel - * - * This interface can be used in order to fully describe an - * OpenViBE black box. It describes its identification values, - * its inputs, its outputs and its settings. - */ - class OV_API IBox : public IAttributable, public CObservable - { - public: - - /** \name Box naming and identification */ - //@{ - - /** - * \brief Gets the identifier of this box - * \return The identifier of this OpenViBE box. - */ - virtual CIdentifier getIdentifier() const = 0; - /** - * \brief Gets the display name of this box - * \return The name of this OpenViBE box. - */ - virtual CString getName() const = 0; - /** - * \brief Gets the algorithm class identifier - * \return This box' algorithm class identifier - */ - virtual CIdentifier getAlgorithmClassIdentifier() const = 0; - /** - * \brief Changes the identifier of this box - * \param id [in] : The new id - * this box should take. - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool setIdentifier(const CIdentifier& id) = 0; - /** - * \brief Renames this box - * \param name [in] : The name this box should take - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool setName(const CString& name) = 0; - /** - * \brief Changes the algorithm identifier of this box - * \param id [in] : The new algorithm - * identifier this box should take. - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool setAlgorithmClassIdentifier(const CIdentifier& id) = 0; - - - /** - * \brief Requests for a suggested id. If it is already used in the box or - * if it is OV_UndefinedIdentifier, a news random one is proposed uniq in the scope of settings. - * \param id [in] : the requested id - * \return the proposed id - */ - virtual CIdentifier getUnusedSettingIdentifier(const CIdentifier& id = OV_UndefinedIdentifier) const = 0; - - /** - * \brief Requests for a suggested id. If it is already used in the box or - * if it is OV_UndefinedIdentifier, a news random one is proposed uniq in the scope of the inputs - * of the given map object. - * \param id [in] : the requested id - * \return the proposed id - */ - virtual CIdentifier getUnusedInputIdentifier(const CIdentifier& id = OV_UndefinedIdentifier) const = 0; - - /** - * \brief Requests for a suggested id. If it is already used in the box or - * if it is OV_UndefinedIdentifier, a news random one is proposed uniq in the scope of the outputs - * of the given map object. - * \param id [in] : the requested id - * \return the proposed id - */ - virtual CIdentifier getUnusedOutputIdentifier(const CIdentifier& id = OV_UndefinedIdentifier) const = 0; - - //@} - /** \name Initialisation from prototypes etc... */ - //@{ - - /** - * \brief Initializes the box from box algorithm descriptor - * \param id [in] : The new algorithm - * identifier this box should take. - * \return \e true in case of success. - * \return \e false in case of error. - * - * Resets the box and initializes its input/output/settings - * according to the box algorithm descriptor - */ - virtual bool initializeFromAlgorithmClassIdentifier(const CIdentifier& id) = 0; - /** - * \brief Initializes the box from an already existing box - * \param existingBox [in] : The existing box. - * \return \e true in case of success. - * \return \e false in case of error. - * - * Resets the box and initializes its input/output/settings - * according to the existing box. - */ - virtual bool initializeFromExistingBox(const IBox& existingBox) = 0; - - - virtual bool addInterfacor(const EBoxInterfacorType type, const CString& name, const CIdentifier& typeID, const CIdentifier& id, - const bool notify = true) = 0; - virtual bool removeInterfacor(const EBoxInterfacorType type, const size_t index, const bool notify = true) = 0; - - virtual size_t getInterfacorCount(const EBoxInterfacorType type) const = 0; - virtual size_t getInterfacorCountIncludingDeprecated(const EBoxInterfacorType type) const = 0; - - virtual bool getInterfacorIdentifier(const EBoxInterfacorType type, const size_t index, CIdentifier& id) const = 0; - - virtual bool getInterfacorIndex(const EBoxInterfacorType type, const CIdentifier& id, size_t& index) const = 0; - virtual bool getInterfacorIndex(const EBoxInterfacorType type, const CString& name, size_t& index) const = 0; - - virtual bool getInterfacorType(const EBoxInterfacorType type, const size_t index, CIdentifier& typeID) const = 0; - virtual bool getInterfacorType(const EBoxInterfacorType type, const CIdentifier& id, CIdentifier& typeID) const = 0; - virtual bool getInterfacorType(const EBoxInterfacorType type, const CString& name, CIdentifier& typeID) const = 0; - - virtual bool getInterfacorName(const EBoxInterfacorType type, const size_t index, CString& name) const = 0; - virtual bool getInterfacorName(const EBoxInterfacorType type, const CIdentifier& id, CString& name) const = 0; - - virtual bool getInterfacorDeprecatedStatus(const EBoxInterfacorType type, const size_t index, bool& value) const = 0; - virtual bool getInterfacorDeprecatedStatus(const EBoxInterfacorType type, const CIdentifier& id, bool& value) const = 0; - - virtual bool hasInterfacorWithIdentifier(const EBoxInterfacorType type, const CIdentifier& id) const = 0; - virtual bool hasInterfacorWithType(const EBoxInterfacorType type, const size_t index, const CIdentifier& typeID) const = 0; - virtual bool hasInterfacorWithNameAndType(const EBoxInterfacorType type, const CString& name, const CIdentifier& typeID) const = 0; - - virtual bool setInterfacorType(const EBoxInterfacorType type, const size_t index, const CIdentifier& typeID) = 0; - virtual bool setInterfacorType(const EBoxInterfacorType type, const CIdentifier& id, const CIdentifier& typeID) = 0; - virtual bool setInterfacorType(const EBoxInterfacorType type, const CString& name, const CIdentifier& typeID) = 0; - - virtual bool setInterfacorName(const EBoxInterfacorType type, const size_t index, const CString& name) = 0; - virtual bool setInterfacorName(const EBoxInterfacorType type, const CIdentifier& id, const CString& name) = 0; - - virtual bool setInterfacorDeprecatedStatus(const EBoxInterfacorType type, const size_t index, const bool value) = 0; - virtual bool setInterfacorDeprecatedStatus(const EBoxInterfacorType type, const CIdentifier& id, const bool value) = 0; - - virtual bool updateInterfacorIdentifier(const EBoxInterfacorType type, const size_t index, const CIdentifier& id) = 0; - - virtual bool addInterfacorTypeSupport(const EBoxInterfacorType type, const CIdentifier& typeID) = 0; - virtual bool hasInterfacorTypeSupport(const EBoxInterfacorType type, const CIdentifier& typeID) const = 0; - //@} - /** \name Input management */ - //@{ - - /** - * \brief Adds an input to this box - * \param name [in] : The input name - * \param typeID [in] : The - * input type id - * \param id [in] : The input id - * \param notify: if true, activate notification callback (true by default) - * \return \e true in case of success. - * \return \e false in case of error. - * - * The input is always added after the last - * already existing input. - */ - virtual bool addInput(const CString& name, const CIdentifier& typeID, const CIdentifier& id = OV_UndefinedIdentifier, const bool notify = true) = 0; - - /** - * \brief Removes an input for this box - * \param index [in] : The index - * of the input to be removed - * \param notify manage notify. Is enabled by default - * \return \e true in case of success. - * \return \e false in case of error. - * - * Inputs coming after the removed input - * have their indices changing after this, - * they all decrease by 1. - */ - virtual bool removeInput(const size_t index, const bool notify = true) = 0; - - /** - * \brief Gets the number of inputs for this box - * \return The number of inputs for this box. - */ - virtual size_t getInputCount() const = 0; - - /** - * \brief Gets an input type identifier by index - * \param index [in] : The input index - * \param typeID [out] : The type identifier - * \return \e true in case of success. - * \return \e false in case of error. In such case, - * \c typeID remains unchanged. - */ - virtual bool getInputType(const size_t index, CIdentifier& typeID) const = 0; - - /** - * \brief Gets an input name by index - * \param index [in] : The input index - * \param name [out] : The name of this input - * \return \e true in case of success. - * \return \e false in case of error. In such case, - * \c name remains unchanged. - */ - virtual bool getInputName(const size_t index, CString& name) const = 0; - - /** - * \brief Sets an input type identifier by index - * \param index [in] : The input index - * \param typeID [in] : The type identifier - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool setInputType(const size_t index, const CIdentifier& typeID) = 0; - - /** - * \brief Sets an input name by index - * \param index [in] : The input index - * \param name [in] : The name of this input - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool setInputName(const size_t index, const CString& name) = 0; - - //@} - /** \name Output management */ - //@{ - - /** - * \brief Adds an output to this box - * \param name [in] : The output name - * \param typeID [in] : The - * output type idenfitier - * \param id [in] : The output id - * \param notify: if true, activate notification callback (true by default) - * \return \e true in case of success. - * \return \e false in case of error. - * - * The output is always added after the last - * already existing output. - */ - virtual bool addOutput(const CString& name, const CIdentifier& typeID, const CIdentifier& id = OV_UndefinedIdentifier, - const bool notify = true) = 0; - - /** - * \brief Removes an output for this box - * \param index [in] : The index - * of the output to remove - * \param notify manage notify. Is enabled by default - * \return \e true in case of success. - * \return \e false in case of error. - * - * Outputs coming after the removed output - * have their indices changing after this, - * they all decrease by 1. - */ - virtual bool removeOutput(const size_t index, const bool notify = true) = 0; - /** - * \brief Gets the number of outputs for this box - * \return The number of outputs for this box. - */ - virtual size_t getOutputCount() const = 0; - - /** - * \brief Gets an output type identifier by index - * \param index [in] : The output index - * \param typeID [out] : The type identifier - * \return \e true in case of success. - * \return \e false in case of error. In such case, - * \c typeID remains unchanged. - */ - virtual bool getOutputType(const size_t index, CIdentifier& typeID) const = 0; - - /** - * \brief Gets an output name by index - * \param index [in] : The output index - * \param name [out] : The name of this output - * \return \e true in case of success. - * \return \e false in case of error. In such case, - * \c name remains unchanged. - */ - virtual bool getOutputName(const size_t index, CString& name) const = 0; - - /** - * \brief Sets an output type identifier by index - * \param index [in] : The output index - * \param typeID [in] : The type identifier - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool setOutputType(const size_t index, const CIdentifier& typeID) = 0; - - /** - * \brief Sets an output name by index - * \param index [in] : The output index - * \param name [in] : The name of this output - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool setOutputName(const size_t index, const CString& name) = 0; - - //@} - /** \name Setting management */ - //@{ - - /** - * \brief Adds a setting to this box - * \param name [in] : The setting name - * \param typeID [in] : The - * setting type id - * \param value [in] : The default - * value for this setting - * \param index [in] : The index where to - * add the setting - * \param modifiability [in] : true if modifiable setting - * \param id [in] : The setting id - * \param notify: if true, activate notification callback (true by default) - * - * \return \e true in case of success. - * \return \e false in case of error. - * - * The setting is added to the index required. - * The default value -1 means that the setting - * will be add to the end. - */ - virtual bool addSetting(const CString& name, const CIdentifier& typeID, const CString& value, const size_t index = size_t(-1), - const bool modifiability = false, - const CIdentifier& id = OV_UndefinedIdentifier, const bool notify = true) = 0; - - /** - * \brief Removes a setting for this box - * \param index [in] : The index - * of the setting to remove - * \param notify manage notify. Is enabled by default - * \return \e true in case of success. - * \return \e false in case of error. - * - * Settings coming after the removed setting - * have their indices changing after this, - * they all decrease by 1. - */ - virtual bool removeSetting(const size_t index, const bool notify = true) = 0; - /** - * \brief Gets the number of settings for this box - * \return The number of settings for this box. - */ - virtual size_t getSettingCount() const = 0; - - /** - * \brief checks if a setting with a given name is present - * \param name [in] : Name of the setting - * \return true if setting is present, false otherwise - */ - virtual bool hasSettingWithName(const CString& name) const = 0; - - /** - * \brief Gets a setting type by index - * \param index [in] : The setting index - * \param typeID [out] : The type identifier - * \return \e true in case of success. - * \return \e false in case of error. In such case, \c typeID remains unchanged. - */ - virtual bool getSettingType(const size_t index, CIdentifier& typeID) const = 0; - - /** - * \brief Gets a setting name by index - * \param index [in] : The setting index - * \param name [out] : The name of this setting - * \return \e true in case of success. - * \return \e false in case of error. In such case, \c name remains unchanged. - */ - virtual bool getSettingName(const size_t index, CString& name) const = 0; - - /** - * \brief Gets the default setting value by index - * \param index [in] : The setting index - * \param value [out] : The default value - * \return \e true in case of success. - * \return \e false in case of error. In such case, \c value remains unchanged. - */ - virtual bool getSettingDefaultValue(const size_t index, CString& value) const = 0; - - /** - * \brief Gets the default setting value by id - * \param id [in] : The setting id - * \param value [out] : The default value - * \return \e true in case of success. - * \return \e false in case of error. In such case, \c value remains unchanged. - */ - virtual bool getSettingDefaultValue(const CIdentifier& id, CString& value) const = 0; - - /** - * \brief Gets the default setting value by name - * \param name [in] : The setting name - * \param defaultValue [out] : The default value - * \return \e true in case of success. - * \return \e false in case of error. In such case, \c defaultValue remains unchanged. - */ - virtual bool getSettingDefaultValue(const CString& name, CString& defaultValue) const = 0; - - /** - * \brief Gets the setting value by index - * \param index [in] : The setting index - * \param value [out] : The value - * \return \e true in case of success. - * \return \e false in case of error. In such case, \c value remains unchanged. - */ - virtual bool getSettingValue(const size_t index, CString& value) const = 0; - - /** - * \brief Gets the setting value by id - * \param id [in] : The setting id - * \param value [out] : The value - * \return \e true in case of success. - * \return \e false in case of error. In such case, \c value remains unchanged. - */ - virtual bool getSettingValue(const CIdentifier& id, CString& value) const = 0; - - /** - * \brief Gets the setting value by name - * \param name [in] : The setting name - * \param value [out] : The value - * \return \e true in case of success. - * \return \e false in case of error. In such case, - * \c value remains unchanged. - */ - virtual bool getSettingValue(const CString& name, CString& value) const = 0; - - /** - * \brief Sets a setting type identifier by index - * \param index [in] : The setting index - * \param typeID [in] : The type identifier - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool setSettingType(const size_t index, const CIdentifier& typeID) = 0; - - /** - * \brief Sets a setting name by index - * \param index [in] : The setting index - * \param name [in] : The name of this setting - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool setSettingName(const size_t index, const CString& name) = 0; - - /** - * \brief Sets the default setting value by index - * \param index [in] : The setting index - * \param value [in] : The default value - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool setSettingDefaultValue(const size_t index, const CString& value) = 0; - - /** - * \brief Sets the default setting value by id - * \param id [in] : The setting id - * \param value [in] : The default value - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool setSettingDefaultValue(const CIdentifier& id, const CString& value) = 0; - - /** - * \brief Sets the default setting value by name - * \param name [in] : The setting name - * \param value [in] : The default value - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool setSettingDefaultValue(const CString& name, const CString& value) = 0; - - /** - * \brief Sets the setting value by index - * \param index [in] : The setting index - * \param value [in] : The value - * \param notify : allow notification - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool setSettingValue(const size_t index, const CString& value, const bool notify = true) = 0; - - /** - * \brief Sets the setting value by id - * \param id [in] : The setting id - * \param value [in] : The value - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool setSettingValue(const CIdentifier& id, const CString& value) = 0; - - /** - * \brief Sets the setting value by name - * \param name [in] : The setting name - * \param value [in] : The value - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool setSettingValue(const CString& name, const CString& value) = 0; - - /** - * \brief Gets the setting modifiability by index - * \param index [in] : The setting index - * \param value [out] : The value - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool getSettingMod(const size_t index, bool& value) const = 0; - - /** - * \brief Gets the setting modifiability by id - * \param id [in] : The setting id - * \param value [out] : The value - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool getSettingMod(const CIdentifier& id, bool& value) const = 0; - - /** - * \brief Gets the setting modifiability by name - * \param name [in] : The setting name - * \param value [out] : The value - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool getSettingMod(const CString& name, bool& value) const = 0; - - /** - * \brief Sets the setting modifiability by index - * \param index [in] : The setting index - * \param value [in] : The value - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool setSettingMod(const size_t index, const bool value) = 0; - - /** - * \brief Sets the setting modifiability by id - * \param id [in] : The setting id - * \param value [in] : The value - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool setSettingMod(const CIdentifier& id, const bool value) = 0; - - /** - * \brief Sets the setting modifiability by name - * \param name [in] : The setting name - * \param value [in] : The value - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool setSettingMod(const CString& name, const bool value) = 0; - - virtual bool swapSettings(const size_t indexA, const size_t indexB) = 0; - virtual bool swapInputs(const size_t indexA, const size_t indexB) = 0; - virtual bool swapOutputs(const size_t indexA, const size_t indexB) = 0; - /** - * \brief Inform if the box possess a modifiable interface - * \return \e true if it does. - * \return \e false otherwise. - */ - virtual bool hasModifiableSettings() const = 0; - - - virtual size_t* getModifiableSettings(size_t& count) const = 0; - - - //@} - - - /** \name Input/Output management */ - //@{ - /** - * \brief Marks this type as supported by inputs - * \param typeID [in] : The type identifier - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool addInputSupport(const CIdentifier& typeID) = 0; - - /** - * \brief Indicates if a type is support by inputs - * \param typeID [in] : The type identifier - * \return \e true if type is support. - * \return \e false if type isn't support. - */ - virtual bool hasInputSupport(const CIdentifier& typeID) const = 0; - - /** - * \brief Marks this type as supported by outputs - * \param typeID [in] : The type identifier - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool addOutputSupport(const CIdentifier& typeID) = 0; - - /** - * \brief Indicates if a type is support by outputs - * \param typeID [in] : The type identifier - * \return \e true if type is support. - * \return \e false if type isn't support. - */ - virtual bool hasOutputSupport(const CIdentifier& typeID) const = 0; - //@} - - /** - * \brief Set the supported stream type for input and output according - * to the restriction of the algorithm whose identifier is given in parameter. - * \param typeID [in] : identifier of the algorithm - * \return \e true in case of success. - * \return \e false in case of error. - * \note The supported stream list is not reset. - */ - virtual bool setSupportTypeFromAlgorithmIdentifier(const CIdentifier& typeID) = 0; - - /** - * \brief Get a vector of input supported types - * \return the vector of input supported types - */ - virtual std::vector<CIdentifier> getInputSupportTypes() const = 0; - - /** - * \brief Get a vector of output supported types - * \return the vector of output supported types - */ - virtual std::vector<CIdentifier> getOutputSupportTypes() const = 0; - - /** - * \brief clear output supported types list - */ - virtual void clearOutputSupportTypes() = 0; - - /** - * \brief clear input supported types list - */ - virtual void clearInputSupportTypes() = 0; - - _IsDerivedFromClass_(IAttributable, OV_ClassId_Kernel_Scenario_Box) - }; - - typedef IBox IStaticBoxContext; - } // namespace Kernel -} // namespace OpenViBE +public: + + /** \name Box naming and identification */ + //@{ + + /** + * \brief Gets the identifier of this box + * \return The identifier of this OpenViBE box. + */ + virtual CIdentifier getIdentifier() const = 0; + /** + * \brief Gets the display name of this box + * \return The name of this OpenViBE box. + */ + virtual CString getName() const = 0; + /** + * \brief Gets the algorithm class identifier + * \return This box' algorithm class identifier + */ + virtual CIdentifier getAlgorithmClassIdentifier() const = 0; + /** + * \brief Changes the identifier of this box + * \param id [in] : The new id + * this box should take. + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool setIdentifier(const CIdentifier& id) = 0; + /** + * \brief Renames this box + * \param name [in] : The name this box should take + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool setName(const CString& name) = 0; + /** + * \brief Changes the algorithm identifier of this box + * \param id [in] : The new algorithm + * identifier this box should take. + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool setAlgorithmClassIdentifier(const CIdentifier& id) = 0; + + + /** + * \brief Requests for a suggested id. If it is already used in the box or + * if it is OV_UndefinedIdentifier, a news random one is proposed uniq in the scope of settings. + * \param id [in] : the requested id + * \return the proposed id + */ + virtual CIdentifier getUnusedSettingIdentifier(const CIdentifier& id = OV_UndefinedIdentifier) const = 0; + + /** + * \brief Requests for a suggested id. If it is already used in the box or + * if it is OV_UndefinedIdentifier, a news random one is proposed uniq in the scope of the inputs + * of the given map object. + * \param id [in] : the requested id + * \return the proposed id + */ + virtual CIdentifier getUnusedInputIdentifier(const CIdentifier& id = OV_UndefinedIdentifier) const = 0; + + /** + * \brief Requests for a suggested id. If it is already used in the box or + * if it is OV_UndefinedIdentifier, a news random one is proposed uniq in the scope of the outputs + * of the given map object. + * \param id [in] : the requested id + * \return the proposed id + */ + virtual CIdentifier getUnusedOutputIdentifier(const CIdentifier& id = OV_UndefinedIdentifier) const = 0; + + //@} + /** \name Initialisation from prototypes etc... */ + //@{ + + /** + * \brief Initializes the box from box algorithm descriptor + * \param id [in] : The new algorithm + * identifier this box should take. + * \return \e true in case of success. + * \return \e false in case of error. + * + * Resets the box and initializes its input/output/settings + * according to the box algorithm descriptor + */ + virtual bool initializeFromAlgorithmClassIdentifier(const CIdentifier& id) = 0; + /** + * \brief Initializes the box from an already existing box + * \param existingBox [in] : The existing box. + * \return \e true in case of success. + * \return \e false in case of error. + * + * Resets the box and initializes its input/output/settings + * according to the existing box. + */ + virtual bool initializeFromExistingBox(const IBox& existingBox) = 0; + + + virtual bool addInterfacor(const EBoxInterfacorType type, const CString& name, const CIdentifier& typeID, const CIdentifier& id, + const bool notify = true) = 0; + virtual bool removeInterfacor(const EBoxInterfacorType type, const size_t index, const bool notify = true) = 0; + + virtual size_t getInterfacorCount(const EBoxInterfacorType type) const = 0; + virtual size_t getInterfacorCountIncludingDeprecated(const EBoxInterfacorType type) const = 0; + + virtual bool getInterfacorIdentifier(const EBoxInterfacorType type, const size_t index, CIdentifier& id) const = 0; + + virtual bool getInterfacorIndex(const EBoxInterfacorType type, const CIdentifier& id, size_t& index) const = 0; + virtual bool getInterfacorIndex(const EBoxInterfacorType type, const CString& name, size_t& index) const = 0; + + virtual bool getInterfacorType(const EBoxInterfacorType type, const size_t index, CIdentifier& typeID) const = 0; + virtual bool getInterfacorType(const EBoxInterfacorType type, const CIdentifier& id, CIdentifier& typeID) const = 0; + virtual bool getInterfacorType(const EBoxInterfacorType type, const CString& name, CIdentifier& typeID) const = 0; + + virtual bool getInterfacorName(const EBoxInterfacorType type, const size_t index, CString& name) const = 0; + virtual bool getInterfacorName(const EBoxInterfacorType type, const CIdentifier& id, CString& name) const = 0; + + virtual bool getInterfacorDeprecatedStatus(const EBoxInterfacorType type, const size_t index, bool& value) const = 0; + virtual bool getInterfacorDeprecatedStatus(const EBoxInterfacorType type, const CIdentifier& id, bool& value) const = 0; + + virtual bool hasInterfacorWithIdentifier(const EBoxInterfacorType type, const CIdentifier& id) const = 0; + virtual bool hasInterfacorWithType(const EBoxInterfacorType type, const size_t index, const CIdentifier& typeID) const = 0; + virtual bool hasInterfacorWithNameAndType(const EBoxInterfacorType type, const CString& name, const CIdentifier& typeID) const = 0; + + virtual bool setInterfacorType(const EBoxInterfacorType type, const size_t index, const CIdentifier& typeID) = 0; + virtual bool setInterfacorType(const EBoxInterfacorType type, const CIdentifier& id, const CIdentifier& typeID) = 0; + virtual bool setInterfacorType(const EBoxInterfacorType type, const CString& name, const CIdentifier& typeID) = 0; + + virtual bool setInterfacorName(const EBoxInterfacorType type, const size_t index, const CString& name) = 0; + virtual bool setInterfacorName(const EBoxInterfacorType type, const CIdentifier& id, const CString& name) = 0; + + virtual bool setInterfacorDeprecatedStatus(const EBoxInterfacorType type, const size_t index, const bool value) = 0; + virtual bool setInterfacorDeprecatedStatus(const EBoxInterfacorType type, const CIdentifier& id, const bool value) = 0; + + virtual bool updateInterfacorIdentifier(const EBoxInterfacorType type, const size_t index, const CIdentifier& id) = 0; + + virtual bool addInterfacorTypeSupport(const EBoxInterfacorType type, const CIdentifier& typeID) = 0; + virtual bool hasInterfacorTypeSupport(const EBoxInterfacorType type, const CIdentifier& typeID) const = 0; + //@} + /** \name Input management */ + //@{ + + /** + * \brief Adds an input to this box + * \param name [in] : The input name + * \param typeID [in] : The + * input type id + * \param id [in] : The input id + * \param notify: if true, activate notification callback (true by default) + * \return \e true in case of success. + * \return \e false in case of error. + * + * The input is always added after the last + * already existing input. + */ + virtual bool addInput(const CString& name, const CIdentifier& typeID, const CIdentifier& id = OV_UndefinedIdentifier, const bool notify = true) = 0; + + /** + * \brief Removes an input for this box + * \param index [in] : The index + * of the input to be removed + * \param notify manage notify. Is enabled by default + * \return \e true in case of success. + * \return \e false in case of error. + * + * Inputs coming after the removed input + * have their indices changing after this, + * they all decrease by 1. + */ + virtual bool removeInput(const size_t index, const bool notify = true) = 0; + + /** + * \brief Gets the number of inputs for this box + * \return The number of inputs for this box. + */ + virtual size_t getInputCount() const = 0; + + /** + * \brief Gets an input type identifier by index + * \param index [in] : The input index + * \param typeID [out] : The type identifier + * \return \e true in case of success. + * \return \e false in case of error. In such case, + * \c typeID remains unchanged. + */ + virtual bool getInputType(const size_t index, CIdentifier& typeID) const = 0; + + /** + * \brief Gets an input name by index + * \param index [in] : The input index + * \param name [out] : The name of this input + * \return \e true in case of success. + * \return \e false in case of error. In such case, + * \c name remains unchanged. + */ + virtual bool getInputName(const size_t index, CString& name) const = 0; + + /** + * \brief Sets an input type identifier by index + * \param index [in] : The input index + * \param typeID [in] : The type identifier + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool setInputType(const size_t index, const CIdentifier& typeID) = 0; + + /** + * \brief Sets an input name by index + * \param index [in] : The input index + * \param name [in] : The name of this input + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool setInputName(const size_t index, const CString& name) = 0; + + //@} + /** \name Output management */ + //@{ + + /** + * \brief Adds an output to this box + * \param name [in] : The output name + * \param typeID [in] : The + * output type idenfitier + * \param id [in] : The output id + * \param notify: if true, activate notification callback (true by default) + * \return \e true in case of success. + * \return \e false in case of error. + * + * The output is always added after the last + * already existing output. + */ + virtual bool addOutput(const CString& name, const CIdentifier& typeID, const CIdentifier& id = OV_UndefinedIdentifier, + const bool notify = true) = 0; + + /** + * \brief Removes an output for this box + * \param index [in] : The index + * of the output to remove + * \param notify manage notify. Is enabled by default + * \return \e true in case of success. + * \return \e false in case of error. + * + * Outputs coming after the removed output + * have their indices changing after this, + * they all decrease by 1. + */ + virtual bool removeOutput(const size_t index, const bool notify = true) = 0; + /** + * \brief Gets the number of outputs for this box + * \return The number of outputs for this box. + */ + virtual size_t getOutputCount() const = 0; + + /** + * \brief Gets an output type identifier by index + * \param index [in] : The output index + * \param typeID [out] : The type identifier + * \return \e true in case of success. + * \return \e false in case of error. In such case, + * \c typeID remains unchanged. + */ + virtual bool getOutputType(const size_t index, CIdentifier& typeID) const = 0; + + /** + * \brief Gets an output name by index + * \param index [in] : The output index + * \param name [out] : The name of this output + * \return \e true in case of success. + * \return \e false in case of error. In such case, + * \c name remains unchanged. + */ + virtual bool getOutputName(const size_t index, CString& name) const = 0; + + /** + * \brief Sets an output type identifier by index + * \param index [in] : The output index + * \param typeID [in] : The type identifier + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool setOutputType(const size_t index, const CIdentifier& typeID) = 0; + + /** + * \brief Sets an output name by index + * \param index [in] : The output index + * \param name [in] : The name of this output + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool setOutputName(const size_t index, const CString& name) = 0; + + //@} + /** \name Setting management */ + //@{ + + /** + * \brief Adds a setting to this box + * \param name [in] : The setting name + * \param typeID [in] : The + * setting type id + * \param value [in] : The default + * value for this setting + * \param index [in] : The index where to + * add the setting + * \param modifiability [in] : true if modifiable setting + * \param id [in] : The setting id + * \param notify: if true, activate notification callback (true by default) + * + * \return \e true in case of success. + * \return \e false in case of error. + * + * The setting is added to the index required. + * The default value -1 means that the setting + * will be add to the end. + */ + virtual bool addSetting(const CString& name, const CIdentifier& typeID, const CString& value, const size_t index = size_t(-1), + const bool modifiability = false, + const CIdentifier& id = OV_UndefinedIdentifier, const bool notify = true) = 0; + + /** + * \brief Removes a setting for this box + * \param index [in] : The index + * of the setting to remove + * \param notify manage notify. Is enabled by default + * \return \e true in case of success. + * \return \e false in case of error. + * + * Settings coming after the removed setting + * have their indices changing after this, + * they all decrease by 1. + */ + virtual bool removeSetting(const size_t index, const bool notify = true) = 0; + /** + * \brief Gets the number of settings for this box + * \return The number of settings for this box. + */ + virtual size_t getSettingCount() const = 0; + + /** + * \brief checks if a setting with a given name is present + * \param name [in] : Name of the setting + * \return true if setting is present, false otherwise + */ + virtual bool hasSettingWithName(const CString& name) const = 0; + + /** + * \brief Gets a setting type by index + * \param index [in] : The setting index + * \param typeID [out] : The type identifier + * \return \e true in case of success. + * \return \e false in case of error. In such case, \c typeID remains unchanged. + */ + virtual bool getSettingType(const size_t index, CIdentifier& typeID) const = 0; + + /** + * \brief Gets a setting name by index + * \param index [in] : The setting index + * \param name [out] : The name of this setting + * \return \e true in case of success. + * \return \e false in case of error. In such case, \c name remains unchanged. + */ + virtual bool getSettingName(const size_t index, CString& name) const = 0; + + /** + * \brief Gets the default setting value by index + * \param index [in] : The setting index + * \param value [out] : The default value + * \return \e true in case of success. + * \return \e false in case of error. In such case, \c value remains unchanged. + */ + virtual bool getSettingDefaultValue(const size_t index, CString& value) const = 0; + + /** + * \brief Gets the default setting value by id + * \param id [in] : The setting id + * \param value [out] : The default value + * \return \e true in case of success. + * \return \e false in case of error. In such case, \c value remains unchanged. + */ + virtual bool getSettingDefaultValue(const CIdentifier& id, CString& value) const = 0; + + /** + * \brief Gets the default setting value by name + * \param name [in] : The setting name + * \param defaultValue [out] : The default value + * \return \e true in case of success. + * \return \e false in case of error. In such case, \c defaultValue remains unchanged. + */ + virtual bool getSettingDefaultValue(const CString& name, CString& defaultValue) const = 0; + + /** + * \brief Gets the setting value by index + * \param index [in] : The setting index + * \param value [out] : The value + * \return \e true in case of success. + * \return \e false in case of error. In such case, \c value remains unchanged. + */ + virtual bool getSettingValue(const size_t index, CString& value) const = 0; + + /** + * \brief Gets the setting value by id + * \param id [in] : The setting id + * \param value [out] : The value + * \return \e true in case of success. + * \return \e false in case of error. In such case, \c value remains unchanged. + */ + virtual bool getSettingValue(const CIdentifier& id, CString& value) const = 0; + + /** + * \brief Gets the setting value by name + * \param name [in] : The setting name + * \param value [out] : The value + * \return \e true in case of success. + * \return \e false in case of error. In such case, + * \c value remains unchanged. + */ + virtual bool getSettingValue(const CString& name, CString& value) const = 0; + + /** + * \brief Sets a setting type identifier by index + * \param index [in] : The setting index + * \param typeID [in] : The type identifier + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool setSettingType(const size_t index, const CIdentifier& typeID) = 0; + + /** + * \brief Sets a setting name by index + * \param index [in] : The setting index + * \param name [in] : The name of this setting + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool setSettingName(const size_t index, const CString& name) = 0; + + /** + * \brief Sets the default setting value by index + * \param index [in] : The setting index + * \param value [in] : The default value + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool setSettingDefaultValue(const size_t index, const CString& value) = 0; + + /** + * \brief Sets the default setting value by id + * \param id [in] : The setting id + * \param value [in] : The default value + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool setSettingDefaultValue(const CIdentifier& id, const CString& value) = 0; + + /** + * \brief Sets the default setting value by name + * \param name [in] : The setting name + * \param value [in] : The default value + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool setSettingDefaultValue(const CString& name, const CString& value) = 0; + + /** + * \brief Sets the setting value by index + * \param index [in] : The setting index + * \param value [in] : The value + * \param notify : allow notification + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool setSettingValue(const size_t index, const CString& value, const bool notify = true) = 0; + + /** + * \brief Sets the setting value by id + * \param id [in] : The setting id + * \param value [in] : The value + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool setSettingValue(const CIdentifier& id, const CString& value) = 0; + + /** + * \brief Sets the setting value by name + * \param name [in] : The setting name + * \param value [in] : The value + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool setSettingValue(const CString& name, const CString& value) = 0; + + /** + * \brief Gets the setting modifiability by index + * \param index [in] : The setting index + * \param value [out] : The value + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool getSettingMod(const size_t index, bool& value) const = 0; + + /** + * \brief Gets the setting modifiability by id + * \param id [in] : The setting id + * \param value [out] : The value + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool getSettingMod(const CIdentifier& id, bool& value) const = 0; + + /** + * \brief Gets the setting modifiability by name + * \param name [in] : The setting name + * \param value [out] : The value + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool getSettingMod(const CString& name, bool& value) const = 0; + + /** + * \brief Sets the setting modifiability by index + * \param index [in] : The setting index + * \param value [in] : The value + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool setSettingMod(const size_t index, const bool value) = 0; + + /** + * \brief Sets the setting modifiability by id + * \param id [in] : The setting id + * \param value [in] : The value + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool setSettingMod(const CIdentifier& id, const bool value) = 0; + + /** + * \brief Sets the setting modifiability by name + * \param name [in] : The setting name + * \param value [in] : The value + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool setSettingMod(const CString& name, const bool value) = 0; + + virtual bool swapSettings(const size_t indexA, const size_t indexB) = 0; + virtual bool swapInputs(const size_t indexA, const size_t indexB) = 0; + virtual bool swapOutputs(const size_t indexA, const size_t indexB) = 0; + /** + * \brief Inform if the box possess a modifiable interface + * \return \e true if it does. + * \return \e false otherwise. + */ + virtual bool hasModifiableSettings() const = 0; + + + virtual size_t* getModifiableSettings(size_t& count) const = 0; + + + //@} + + + /** \name Input/Output management */ + //@{ + /** + * \brief Marks this type as supported by inputs + * \param typeID [in] : The type identifier + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool addInputSupport(const CIdentifier& typeID) = 0; + + /** + * \brief Indicates if a type is support by inputs + * \param typeID [in] : The type identifier + * \return \e true if type is support. + * \return \e false if type isn't support. + */ + virtual bool hasInputSupport(const CIdentifier& typeID) const = 0; + + /** + * \brief Marks this type as supported by outputs + * \param typeID [in] : The type identifier + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool addOutputSupport(const CIdentifier& typeID) = 0; + + /** + * \brief Indicates if a type is support by outputs + * \param typeID [in] : The type identifier + * \return \e true if type is support. + * \return \e false if type isn't support. + */ + virtual bool hasOutputSupport(const CIdentifier& typeID) const = 0; + //@} + + /** + * \brief Set the supported stream type for input and output according + * to the restriction of the algorithm whose identifier is given in parameter. + * \param typeID [in] : identifier of the algorithm + * \return \e true in case of success. + * \return \e false in case of error. + * \note The supported stream list is not reset. + */ + virtual bool setSupportTypeFromAlgorithmIdentifier(const CIdentifier& typeID) = 0; + + /** + * \brief Get a vector of input supported types + * \return the vector of input supported types + */ + virtual std::vector<CIdentifier> getInputSupportTypes() const = 0; + + /** + * \brief Get a vector of output supported types + * \return the vector of output supported types + */ + virtual std::vector<CIdentifier> getOutputSupportTypes() const = 0; + + /** + * \brief clear output supported types list + */ + virtual void clearOutputSupportTypes() = 0; + + /** + * \brief clear input supported types list + */ + virtual void clearInputSupportTypes() = 0; + + _IsDerivedFromClass_(IAttributable, OV_ClassId_Kernel_Scenario_Box) +}; + +typedef IBox IStaticBoxContext; +} // namespace Kernel +} // namespace OpenViBE diff --git a/openvibe/include/openvibe/kernel/scenario/ovIBoxIO.h b/openvibe/include/openvibe/kernel/scenario/ovIBoxIO.h index bbe6b6e489edd1ef3bac76694d450a8fca4718ad..40a069d4363f34f6c36b102f0ce8ae9a75fe9f97 100644 --- a/openvibe/include/openvibe/kernel/scenario/ovIBoxIO.h +++ b/openvibe/include/openvibe/kernel/scenario/ovIBoxIO.h @@ -2,191 +2,189 @@ #include "../ovIKernelObject.h" -namespace OpenViBE +namespace OpenViBE { +namespace Kernel { +/** + * \class IBoxIO + * \author Yann Renard (INRIA/IRISA) + * \date 2006-06-21 + * \brief Main OpenViBE box interface to communicate with the kernel + * \ingroup Group_Scenario + * \ingroup Group_Kernel + * + * This context allows the object which uses it to check + * inputs states, read them, write outputs while being + * in a dynamic context (used by player). + */ +class OV_API IBoxIO : public IKernelObject { - namespace Kernel - { - /** - * \class IBoxIO - * \author Yann Renard (INRIA/IRISA) - * \date 2006-06-21 - * \brief Main OpenViBE box interface to communicate with the kernel - * \ingroup Group_Scenario - * \ingroup Group_Kernel - * - * This context allows the object which uses it to check - * inputs states, read them, write outputs while being - * in a dynamic context (used by player). - */ - class OV_API IBoxIO : public IKernelObject - { - public: +public: - /** \name Accessing the input chunks informations */ - //@{ + /** \name Accessing the input chunks informations */ + //@{ - /** - * \brief Gets the number of pending chunks for an input - * \param index [in] : the input to work on. - * \return The number of pending chunks for an input - */ - virtual size_t getInputChunkCount(const size_t index) const = 0; - /** - * \brief Gets an input chunk and its time validity. - * \param inputIdx [in] : the index of the desired input. - * \param chunkIdx [in] : the index of the desired chunk in this input. - * \param startTime [out] : the time which the chunk starts at - * \param endTime [out] : the time which the chunk ends at - * \param size [out] : the chunk buffer size in bytes - * \param buffer [out] : the chunk data itself - * \return \e true in case of success. - * \return \e false in case of error. - * \warning When returning \e false, none of the value - * \c startTime, \c endTime, \c size nor - * \c buffer are defined. - * \warning The chunks are ordered like they arrived - * to the box, this means chunk 0 arrived - * before chunk 1, that arrived before - * chunk 2 and so on... - * \note Both time value are given in fixed point 32:32 seconds - * \sa getInputChunkCount - * \sa markInputAsDeprecated - */ - virtual bool getInputChunk(const size_t inputIdx, const size_t chunkIdx, uint64_t& startTime, uint64_t& endTime, size_t& size, - const uint8_t*& buffer) const = 0; - /** - * \brief Gets an input chunk. - * \param inputIdx [in] : the index of the desired input. - * \param chunkIdx [in] : the index of the desired - * chunk in this input. - * \return The memory buffer for the specified chunk. - * \return \c NULL in case of error. - * \warning The chunks are ordered like they arrived - * to the box, this means chunk 0 arrived - * before chunk 1, that arrived before - * chunk 2 and so on... - * \sa getInputChunkCount - * \sa markInputAsDeprecated - */ - virtual const IMemoryBuffer* getInputChunk(const size_t inputIdx, const size_t chunkIdx) const = 0; - /** - * \brief Gets an input chunk start time. - * \param inputIdx [in] : the index of the desired input. - * \param chunkIdx [in] : the index of the desired - * chunk in this input. - * \return The input chunk start time. - * \return \c 0 is returned in case of error. - * \note Both time value are given in fixed point 32:32 seconds - * \sa getInputChunkCount - * \sa markInputAsDeprecated - */ - virtual uint64_t getInputChunkStartTime(const size_t inputIdx, const size_t chunkIdx) const = 0; - /** - * \brief Gets an input chunk end time. - * \param inputIdx [in] : the index of the desired input. - * \param chunkIdx [in] : the index of the desired - * chunk in this input. - * \return The input chunk end time. - * \return \c 0 is returned in case of error. - * \note Both time value are given in fixed point 32:32 seconds - * \sa getInputChunkCount - * \sa markInputAsDeprecated - */ - virtual uint64_t getInputChunkEndTime(const size_t inputIdx, const size_t chunkIdx) const = 0; - /** - * \brief Marks an input chunk as deprecated - * \param inputIdx [in] : the index of the desired input. - * \param chunkIdx [in] : the index of the chunk to mark. - * \return \e true in case of success. - * \return \e false in case of error. - * \warning The chunks are ordered like they arrived - * to the box, this means chunk 0 arrived - * before chunk 1, that arrived before - * chunk 2 and so on... - * - * This function discards a chunk when it's been read - * and processed. This allows the kernel to know a chunk - * has been treated successfully and will not be used - * any more so it can be removed from memory. - * - * \sa getInputChunkCount - * \sa releaseChunk - */ - virtual bool markInputAsDeprecated(const size_t inputIdx, const size_t chunkIdx) = 0; + /** + * \brief Gets the number of pending chunks for an input + * \param index [in] : the input to work on. + * \return The number of pending chunks for an input + */ + virtual size_t getInputChunkCount(const size_t index) const = 0; + /** + * \brief Gets an input chunk and its time validity. + * \param inputIdx [in] : the index of the desired input. + * \param chunkIdx [in] : the index of the desired chunk in this input. + * \param startTime [out] : the time which the chunk starts at + * \param endTime [out] : the time which the chunk ends at + * \param size [out] : the chunk buffer size in bytes + * \param buffer [out] : the chunk data itself + * \return \e true in case of success. + * \return \e false in case of error. + * \warning When returning \e false, none of the value + * \c startTime, \c endTime, \c size nor + * \c buffer are defined. + * \warning The chunks are ordered like they arrived + * to the box, this means chunk 0 arrived + * before chunk 1, that arrived before + * chunk 2 and so on... + * \note Both time value are given in fixed point 32:32 seconds + * \sa getInputChunkCount + * \sa markInputAsDeprecated + */ + virtual bool getInputChunk(const size_t inputIdx, const size_t chunkIdx, uint64_t& startTime, uint64_t& endTime, size_t& size, + const uint8_t*& buffer) const = 0; + /** + * \brief Gets an input chunk. + * \param inputIdx [in] : the index of the desired input. + * \param chunkIdx [in] : the index of the desired + * chunk in this input. + * \return The memory buffer for the specified chunk. + * \return \c NULL in case of error. + * \warning The chunks are ordered like they arrived + * to the box, this means chunk 0 arrived + * before chunk 1, that arrived before + * chunk 2 and so on... + * \sa getInputChunkCount + * \sa markInputAsDeprecated + */ + virtual const IMemoryBuffer* getInputChunk(const size_t inputIdx, const size_t chunkIdx) const = 0; + /** + * \brief Gets an input chunk start time. + * \param inputIdx [in] : the index of the desired input. + * \param chunkIdx [in] : the index of the desired + * chunk in this input. + * \return The input chunk start time. + * \return \c 0 is returned in case of error. + * \note Both time value are given in fixed point 32:32 seconds + * \sa getInputChunkCount + * \sa markInputAsDeprecated + */ + virtual uint64_t getInputChunkStartTime(const size_t inputIdx, const size_t chunkIdx) const = 0; + /** + * \brief Gets an input chunk end time. + * \param inputIdx [in] : the index of the desired input. + * \param chunkIdx [in] : the index of the desired + * chunk in this input. + * \return The input chunk end time. + * \return \c 0 is returned in case of error. + * \note Both time value are given in fixed point 32:32 seconds + * \sa getInputChunkCount + * \sa markInputAsDeprecated + */ + virtual uint64_t getInputChunkEndTime(const size_t inputIdx, const size_t chunkIdx) const = 0; + /** + * \brief Marks an input chunk as deprecated + * \param inputIdx [in] : the index of the desired input. + * \param chunkIdx [in] : the index of the chunk to mark. + * \return \e true in case of success. + * \return \e false in case of error. + * \warning The chunks are ordered like they arrived + * to the box, this means chunk 0 arrived + * before chunk 1, that arrived before + * chunk 2 and so on... + * + * This function discards a chunk when it's been read + * and processed. This allows the kernel to know a chunk + * has been treated successfully and will not be used + * any more so it can be removed from memory. + * + * \sa getInputChunkCount + * \sa releaseChunk + */ + virtual bool markInputAsDeprecated(const size_t inputIdx, const size_t chunkIdx) = 0; - //@} - /** \name Accessing the output chunks information */ - //@{ + //@} + /** \name Accessing the output chunks information */ + //@{ - /** - * \brief Gets the output chunk size - * \param index [in] : the index of the output to work on - * \return The output chunk size in bytes - */ - virtual size_t getOutputChunkSize(const size_t index) const = 0; - /** - * \brief Sets an output chunk size - * \param index [in] : the index of the output to work on - * \param size [in] : the new size of the output chunk - * \param discard [in] : tells if existing buffer should be discarded or not - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool setOutputChunkSize(const size_t index, const size_t size, const bool discard = true) = 0; - /** - * \brief Gets a pointer to the current output chunk buffer - * \param index [in] : the index of the output to work on - * \return A pointer to the current output chunk buffer - * \warning The returned pointer may change if the caller resizes the chunk buffer using \c setChunkSize ! - */ - virtual uint8_t* getOutputChunkBuffer(const size_t index) = 0; - /** - * \brief Appends data to the output chunk - * \param index [in] : the index of the output to work on - * \param buffer [in] : the buffer to append to the current buffer - * \param size [in] : the size of the appended buffer - * \return \e true in case of success. - * \return \e false in case of error. - * \warning This function resizes the chunk size calling \c setOutputChunkSize and then appends data doing a copy. - */ - virtual bool appendOutputChunkData(const size_t index, const uint8_t* buffer, const size_t size) = 0; - /** - * \brief Gets an output chunk. - * \param index [in] : the index of the desired output. - * \return The output chunk memory buffer for the specified output. - * \return \c NULL in case of error. - * \sa markOutputAsReadyToSend - */ - virtual IMemoryBuffer* getOutputChunk(const size_t index) = 0; - /** - * \brief Marks output buffer as 'ready to send' - * \param index [in] : the index of the output to work on - * \param startTime [in] : the start time for - * the related buffer. - * \param endTime [in] : the end time for the - * related buffer. - * \return \e true in case of success. - * \return \e false in case of error. - * - * The output chunk should first be filled. For - * that, one will have to get a reference on it - * thanks to the getChunkBuffer or the - * appendOutputChunkData methods ! The - * player will then know the buffer can be sent. - * - * When called, the function flushes the output - * chunk. Thus, after the call, the chunk size - * is turned to 0 and the output is ready for - * a new chunk when necessary... - * - * \note Both time value are given in fixed point 32:32 seconds - * \sa getChunk - */ - virtual bool markOutputAsReadyToSend(const size_t index, const uint64_t startTime, const uint64_t endTime) = 0; + /** + * \brief Gets the output chunk size + * \param index [in] : the index of the output to work on + * \return The output chunk size in bytes + */ + virtual size_t getOutputChunkSize(const size_t index) const = 0; + /** + * \brief Sets an output chunk size + * \param index [in] : the index of the output to work on + * \param size [in] : the new size of the output chunk + * \param discard [in] : tells if existing buffer should be discarded or not + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool setOutputChunkSize(const size_t index, const size_t size, const bool discard = true) = 0; + /** + * \brief Gets a pointer to the current output chunk buffer + * \param index [in] : the index of the output to work on + * \return A pointer to the current output chunk buffer + * \warning The returned pointer may change if the caller resizes the chunk buffer using \c setChunkSize ! + */ + virtual uint8_t* getOutputChunkBuffer(const size_t index) = 0; + /** + * \brief Appends data to the output chunk + * \param index [in] : the index of the output to work on + * \param buffer [in] : the buffer to append to the current buffer + * \param size [in] : the size of the appended buffer + * \return \e true in case of success. + * \return \e false in case of error. + * \warning This function resizes the chunk size calling \c setOutputChunkSize and then appends data doing a copy. + */ + virtual bool appendOutputChunkData(const size_t index, const uint8_t* buffer, const size_t size) = 0; + /** + * \brief Gets an output chunk. + * \param index [in] : the index of the desired output. + * \return The output chunk memory buffer for the specified output. + * \return \c NULL in case of error. + * \sa markOutputAsReadyToSend + */ + virtual IMemoryBuffer* getOutputChunk(const size_t index) = 0; + /** + * \brief Marks output buffer as 'ready to send' + * \param index [in] : the index of the output to work on + * \param startTime [in] : the start time for + * the related buffer. + * \param endTime [in] : the end time for the + * related buffer. + * \return \e true in case of success. + * \return \e false in case of error. + * + * The output chunk should first be filled. For + * that, one will have to get a reference on it + * thanks to the getChunkBuffer or the + * appendOutputChunkData methods ! The + * player will then know the buffer can be sent. + * + * When called, the function flushes the output + * chunk. Thus, after the call, the chunk size + * is turned to 0 and the output is ready for + * a new chunk when necessary... + * + * \note Both time value are given in fixed point 32:32 seconds + * \sa getChunk + */ + virtual bool markOutputAsReadyToSend(const size_t index, const uint64_t startTime, const uint64_t endTime) = 0; - //@} + //@} - _IsDerivedFromClass_(IKernelObject, OV_ClassId_Kernel_Scenario_BoxIO) - }; - } // namespace Kernel -} // namespace OpenViBE + _IsDerivedFromClass_(IKernelObject, OV_ClassId_Kernel_Scenario_BoxIO) +}; +} // namespace Kernel +} // namespace OpenViBE diff --git a/openvibe/include/openvibe/kernel/scenario/ovIBoxListenerContext.h b/openvibe/include/openvibe/kernel/scenario/ovIBoxListenerContext.h index 9dd9fa83ed5d9dd92c981c64492344f77b014a87..b09da79449963d6aff14e6a028333ec02eb7a84f 100755 --- a/openvibe/include/openvibe/kernel/scenario/ovIBoxListenerContext.h +++ b/openvibe/include/openvibe/kernel/scenario/ovIBoxListenerContext.h @@ -2,97 +2,95 @@ #include "../ovIKernelObject.h" -namespace OpenViBE +namespace OpenViBE { +namespace Kernel { +/** + * \class IBoxListenerContext + * \author Yann Renard (INRIA/IRISA) + * \date 2007-11-06 + * \brief Exectution context for box algorithm descriptors + * \ingroup Group_Kernel + * \ingroup Group_Extend + * \sa Plugins::IBoxAlgorithmDesc + * \sa Plugins::IBoxAlgorithm + */ +class OV_API IBoxListenerContext : public IKernelObject { - namespace Kernel - { - /** - * \class IBoxListenerContext - * \author Yann Renard (INRIA/IRISA) - * \date 2007-11-06 - * \brief Exectution context for box algorithm descriptors - * \ingroup Group_Kernel - * \ingroup Group_Extend - * \sa Plugins::IBoxAlgorithmDesc - * \sa Plugins::IBoxAlgorithm - */ - class OV_API IBoxListenerContext : public IKernelObject - { - public: +public: - /** \name Manager accessors */ - //@{ + /** \name Manager accessors */ + //@{ - /** - * \brief Gets a reference on the current algorithm manager - * \return a reference on the current algorithm manager - */ - virtual IAlgorithmManager& getAlgorithmManager() const = 0; - /** - * \brief Gets a reference on the current player manager - * \return a reference on the current player manager - */ - virtual IPlayerManager& getPlayerManager() const = 0; - /** - * \brief Gets a reference on the current plugin manager - * \return a reference on the current plugin manager - */ - virtual IPluginManager& getPluginManager() const = 0; - /** - * \brief Gets a reference on the current metabox manager - * \return a reference on the current metabox manager - */ - virtual IMetaboxManager& getMetaboxManager() const = 0; - /** - * \brief Gets a reference on the current scenario manager - * \return a reference on the current scenario manager - */ - virtual IScenarioManager& getScenarioManager() const = 0; - /** - * \brief Gets a reference on the current type manager - * \return a reference on the current type manager - */ - virtual ITypeManager& getTypeManager() const = 0; - /** - * \brief Gets a reference on the current log manager - * \return a reference on the current log manager - */ - virtual ILogManager& getLogManager() const = 0; - /** - * \brief Gets a reference on the current error manager - * \return a reference on the current error manager - */ - virtual IErrorManager& getErrorManager() const = 0; + /** + * \brief Gets a reference on the current algorithm manager + * \return a reference on the current algorithm manager + */ + virtual IAlgorithmManager& getAlgorithmManager() const = 0; + /** + * \brief Gets a reference on the current player manager + * \return a reference on the current player manager + */ + virtual IPlayerManager& getPlayerManager() const = 0; + /** + * \brief Gets a reference on the current plugin manager + * \return a reference on the current plugin manager + */ + virtual IPluginManager& getPluginManager() const = 0; + /** + * \brief Gets a reference on the current metabox manager + * \return a reference on the current metabox manager + */ + virtual IMetaboxManager& getMetaboxManager() const = 0; + /** + * \brief Gets a reference on the current scenario manager + * \return a reference on the current scenario manager + */ + virtual IScenarioManager& getScenarioManager() const = 0; + /** + * \brief Gets a reference on the current type manager + * \return a reference on the current type manager + */ + virtual ITypeManager& getTypeManager() const = 0; + /** + * \brief Gets a reference on the current log manager + * \return a reference on the current log manager + */ + virtual ILogManager& getLogManager() const = 0; + /** + * \brief Gets a reference on the current error manager + * \return a reference on the current error manager + */ + virtual IErrorManager& getErrorManager() const = 0; - /** - * \brief Gets a reference on the current configuration manager - * \return a reference on the current configuration manager - */ - virtual IConfigurationManager& getConfigurationManager() const = 0; + /** + * \brief Gets a reference on the current configuration manager + * \return a reference on the current configuration manager + */ + virtual IConfigurationManager& getConfigurationManager() const = 0; - //@} - /** \name Box specific stuffs */ + //@} + /** \name Box specific stuffs */ - /** - * \brief Gets a reference to the considered box - * \return a reference to the considered box - */ - virtual IBox& getBox() const = 0; - /** - * \brief Gets a reference to the scenario owning the considered box - * \return a reference to the scenario owning the considered box - */ - virtual IScenario& getScenario() const = 0; - /** - * \brief Gets the index of the concerned callback message - * \return the index of the concerned callback message in case it makes sense - * \return \c 0xffffffff in case it does not make any sense - */ - virtual size_t getIndex() const = 0; + /** + * \brief Gets a reference to the considered box + * \return a reference to the considered box + */ + virtual IBox& getBox() const = 0; + /** + * \brief Gets a reference to the scenario owning the considered box + * \return a reference to the scenario owning the considered box + */ + virtual IScenario& getScenario() const = 0; + /** + * \brief Gets the index of the concerned callback message + * \return the index of the concerned callback message in case it makes sense + * \return \c 0xffffffff in case it does not make any sense + */ + virtual size_t getIndex() const = 0; - //@} + //@} - _IsDerivedFromClass_(IKernelObject, OV_ClassId_Kernel_Scenario_BoxListenerContext) - }; - } // namespace Kernel -} // namespace OpenViBE + _IsDerivedFromClass_(IKernelObject, OV_ClassId_Kernel_Scenario_BoxListenerContext) +}; +} // namespace Kernel +} // namespace OpenViBE diff --git a/openvibe/include/openvibe/kernel/scenario/ovIBoxProto.h b/openvibe/include/openvibe/kernel/scenario/ovIBoxProto.h index fdd986861ac81a782ca46e3f24ba654d5ecdc33b..d60a010a007ba6ecfa2c20d14decc140ddd948c0 100755 --- a/openvibe/include/openvibe/kernel/scenario/ovIBoxProto.h +++ b/openvibe/include/openvibe/kernel/scenario/ovIBoxProto.h @@ -2,113 +2,111 @@ #include "../ovIKernelObject.h" -namespace OpenViBE +namespace OpenViBE { +namespace Kernel { +/** + * \brief This enum lists all the flags a box can be have + * \sa IBoxProto::addFlag + */ +enum EBoxFlag { - namespace Kernel - { - /** - * \brief This enum lists all the flags a box can be have - * \sa IBoxProto::addFlag - */ - enum EBoxFlag - { - BoxFlag_CanAddInput, - BoxFlag_CanModifyInput, - BoxFlag_CanAddOutput, - BoxFlag_CanModifyOutput, - BoxFlag_CanAddSetting, - BoxFlag_CanModifySetting, - BoxFlag_IsDeprecated, - BoxFlag_ManualUpdate - }; + BoxFlag_CanAddInput, + BoxFlag_CanModifyInput, + BoxFlag_CanAddOutput, + BoxFlag_CanModifyOutput, + BoxFlag_CanAddSetting, + BoxFlag_CanModifySetting, + BoxFlag_IsDeprecated, + BoxFlag_ManualUpdate +}; - /** - * \class IBoxProto - * \author Yann Renard (INRIA/IRISA) - * \date 2006-07-05 - * \brief OpenViBE box prototype - * \ingroup Group_Scenario - * \ingroup Group_Kernel - * \ingroup Group_Extend - * - * This class is used by a plugin algorithm descriptor - * to let the OpenViBE platform know what an algorithm - * box looks like. It declares several things, like - * it input types, output types and settings. - * - * \sa IBoxAlgorithmDesc - */ - class OV_API IBoxProto : public IKernelObject - { - public: +/** + * \class IBoxProto + * \author Yann Renard (INRIA/IRISA) + * \date 2006-07-05 + * \brief OpenViBE box prototype + * \ingroup Group_Scenario + * \ingroup Group_Kernel + * \ingroup Group_Extend + * + * This class is used by a plugin algorithm descriptor + * to let the OpenViBE platform know what an algorithm + * box looks like. It declares several things, like + * it input types, output types and settings. + * + * \sa IBoxAlgorithmDesc + */ +class OV_API IBoxProto : public IKernelObject +{ +public: + + /** + * \brief Adds an input to the box + * \param name [in] : the name of the input to add + * \param typeID [in] : the type of the input + * \param id [in] : The input id + * \param notify [in]: if true, activate notification callback (true by default) + * \return true if successful + */ + virtual bool addInput(const CString& name, const CIdentifier& typeID, const CIdentifier& id = OV_UndefinedIdentifier, const bool notify = true) = 0; - /** - * \brief Adds an input to the box - * \param name [in] : the name of the input to add - * \param typeID [in] : the type of the input - * \param id [in] : The input id - * \param notify [in]: if true, activate notification callback (true by default) - * \return true if successful - */ - virtual bool addInput(const CString& name, const CIdentifier& typeID, const CIdentifier& id = OV_UndefinedIdentifier, const bool notify = true) = 0; + /** + * \brief Adds an output to the box + * \param name [in] : the name of the output to add + * \param typeID [in] : the type of the output + * \param id [in] : The output id + * \param notify [in]: if true, activate notification callback (true by default) + * \return true if successful + */ + virtual bool addOutput(const CString& name, const CIdentifier& typeID, const CIdentifier& id = OV_UndefinedIdentifier, + const bool notify = true) = 0; - /** - * \brief Adds an output to the box - * \param name [in] : the name of the output to add - * \param typeID [in] : the type of the output - * \param id [in] : The output id - * \param notify [in]: if true, activate notification callback (true by default) - * \return true if successful - */ - virtual bool addOutput(const CString& name, const CIdentifier& typeID, const CIdentifier& id = OV_UndefinedIdentifier, - const bool notify = true) = 0; - - /** - * \brief Add an setting to the box - * \param name [in] : the name of the setting to add - * \param typeID [in] : the type of the setting - * \param value [in] : the default value of this - * setting (used to initialize the box itself) - * \param modifiable [in] : true if modifiable setting - * \param id [in] : The setting id - * \param notify [in]: if true, activate notification callback (true by default) - * \return true if successful - */ - virtual bool addSetting(const CString& name, const CIdentifier& typeID, const CString& value, const bool modifiable = false, - const CIdentifier& id = OV_UndefinedIdentifier, - const bool notify = true) = 0; - /** - * \brief Adds a flag to the box - * \param flag [in] : the flag to add to the box - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool addFlag(const EBoxFlag flag) = 0; + /** + * \brief Add an setting to the box + * \param name [in] : the name of the setting to add + * \param typeID [in] : the type of the setting + * \param value [in] : the default value of this + * setting (used to initialize the box itself) + * \param modifiable [in] : true if modifiable setting + * \param id [in] : The setting id + * \param notify [in]: if true, activate notification callback (true by default) + * \return true if successful + */ + virtual bool addSetting(const CString& name, const CIdentifier& typeID, const CString& value, const bool modifiable = false, + const CIdentifier& id = OV_UndefinedIdentifier, + const bool notify = true) = 0; + /** + * \brief Adds a flag to the box + * \param flag [in] : the flag to add to the box + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool addFlag(const EBoxFlag flag) = 0; - /** - * \brief Adds a flag to the box - * \param flagID [in] : the flag to add to the box - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool addFlag(const CIdentifier& flagID) = 0; + /** + * \brief Adds a flag to the box + * \param flagID [in] : the flag to add to the box + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool addFlag(const CIdentifier& flagID) = 0; - /** - * \brief Adds a new type supported by inputs of the box - * \param typeID [in] : The type identifier - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool addInputSupport(const CIdentifier& typeID) = 0; - /** - * \brief Adds a new type supported by outputs of the box - * \param typeID [in] : The type identifier - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool addOutputSupport(const CIdentifier& typeID) = 0; + /** + * \brief Adds a new type supported by inputs of the box + * \param typeID [in] : The type identifier + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool addInputSupport(const CIdentifier& typeID) = 0; + /** + * \brief Adds a new type supported by outputs of the box + * \param typeID [in] : The type identifier + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool addOutputSupport(const CIdentifier& typeID) = 0; - _IsDerivedFromClass_(IKernelObject, OV_ClassId_Kernel_Scenario_BoxProto) - }; - } // namespace Kernel -} // namespace OpenViBE + _IsDerivedFromClass_(IKernelObject, OV_ClassId_Kernel_Scenario_BoxProto) +}; +} // namespace Kernel +} // namespace OpenViBE diff --git a/openvibe/include/openvibe/kernel/scenario/ovIComment.h b/openvibe/include/openvibe/kernel/scenario/ovIComment.h index e6a94dd4b3e4d58d6a878e83e59d476daa2b5a9f..054c5eda73b374372cd293ccaa699944c9eefc11 100644 --- a/openvibe/include/openvibe/kernel/scenario/ovIComment.h +++ b/openvibe/include/openvibe/kernel/scenario/ovIComment.h @@ -2,75 +2,73 @@ #include "ovIAttributable.h" -namespace OpenViBE +namespace OpenViBE { +namespace Kernel { +/** + * \class IComment + * \author Yann Renard INRIA + * \date 2010-04-27 + * \brief A comment class for scenarios + * \ingroup Group_Scenario + * \ingroup Group_Kernel + * + * This interface can be used in order to fully describe an + * OpenViBE comment in order to help the understanding of a + * given scenario. + */ +class OV_API IComment : public IAttributable { - namespace Kernel - { - /** - * \class IComment - * \author Yann Renard INRIA - * \date 2010-04-27 - * \brief A comment class for scenarios - * \ingroup Group_Scenario - * \ingroup Group_Kernel - * - * This interface can be used in order to fully describe an - * OpenViBE comment in order to help the understanding of a - * given scenario. - */ - class OV_API IComment : public IAttributable - { - public: +public: - /** \name Comment naming and identification */ - //@{ + /** \name Comment naming and identification */ + //@{ - /** - * \brief Gets the identifier of this comment - * \return The identifier of this OpenViBE comment. - */ - virtual CIdentifier getIdentifier() const = 0; - /** - * \brief Gets the display name of this comment - * \return The name of this OpenViBE comment. - */ - virtual CString getText() const = 0; - /** - * \brief Changes the identifier of this comment - * \param id [in] : The new id - * this comment should take. - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool setIdentifier(const CIdentifier& id) = 0; - /** - * \brief Changes the text of this comment - * \param text [in] : The text this comment should contain - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool setText(const CString& text) = 0; + /** + * \brief Gets the identifier of this comment + * \return The identifier of this OpenViBE comment. + */ + virtual CIdentifier getIdentifier() const = 0; + /** + * \brief Gets the display name of this comment + * \return The name of this OpenViBE comment. + */ + virtual CString getText() const = 0; + /** + * \brief Changes the identifier of this comment + * \param id [in] : The new id + * this comment should take. + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool setIdentifier(const CIdentifier& id) = 0; + /** + * \brief Changes the text of this comment + * \param text [in] : The text this comment should contain + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool setText(const CString& text) = 0; - //@} - /** \name Initialisation from prototypes etc... */ - //@{ + //@} + /** \name Initialisation from prototypes etc... */ + //@{ - /** - * \brief Initializes the comment from an already existing comment - * \param comment [in] : The existing box. - * \return \e true in case of success. - * \return \e false in case of error. - * - * Resets the comment and initializes its text/attributes - * according to the existing comment. - */ - virtual bool initializeFromExistingComment(const IComment& comment) = 0; + /** + * \brief Initializes the comment from an already existing comment + * \param comment [in] : The existing box. + * \return \e true in case of success. + * \return \e false in case of error. + * + * Resets the comment and initializes its text/attributes + * according to the existing comment. + */ + virtual bool initializeFromExistingComment(const IComment& comment) = 0; - //@} + //@} - _IsDerivedFromClass_(IAttributable, OV_ClassId_Kernel_Scenario_Comment) - }; + _IsDerivedFromClass_(IAttributable, OV_ClassId_Kernel_Scenario_Comment) +}; - typedef IComment static_comment_context_t; - } // namespace Kernel -} // namespace OpenViBE +typedef IComment static_comment_context_t; +} // namespace Kernel +} // namespace OpenViBE diff --git a/openvibe/include/openvibe/kernel/scenario/ovILink.h b/openvibe/include/openvibe/kernel/scenario/ovILink.h index 6ccbc98ac49ab9c80e95e17f973e4a62a9bea062..889d4bda4903b1c5b342d839c4ff130366f0dff7 100644 --- a/openvibe/include/openvibe/kernel/scenario/ovILink.h +++ b/openvibe/include/openvibe/kernel/scenario/ovILink.h @@ -2,122 +2,120 @@ #include "ovIAttributable.h" -namespace OpenViBE +namespace OpenViBE { +namespace Kernel { +/** + * \class ILink + * \author Yann Renard (IRISA/INRIA) + * \date 2006-08-16 + * \brief Link information between OpenViBE box + * \ingroup Group_Scenario + * \ingroup Group_Kernel + * + * This class collects informations between OpenViBE + * boxes : box identifiers and input / output indices. + */ +class OV_API ILink : public IAttributable { - namespace Kernel - { - /** - * \class ILink - * \author Yann Renard (IRISA/INRIA) - * \date 2006-08-16 - * \brief Link information between OpenViBE box - * \ingroup Group_Scenario - * \ingroup Group_Kernel - * - * This class collects informations between OpenViBE - * boxes : box identifiers and input / output indices. - */ - class OV_API ILink : public IAttributable - { - public: +public: - /** \name Identification */ - //@{ + /** \name Identification */ + //@{ - /** - * \brief Initialize link from existing link by copying members - * \param link the existing link - * @return true - */ - virtual bool initializeFromExistingLink(const ILink& link) = 0; - - /** - * \brief Changes this link's id - * \param id [in] : The new id this link should have - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool setIdentifier(const CIdentifier& id) = 0; - /** - * \brief Gets the identifier of this link - * \return The identifier of this link. - */ - virtual CIdentifier getIdentifier() const = 0; + /** + * \brief Initialize link from existing link by copying members + * \param link the existing link + * @return true + */ + virtual bool initializeFromExistingLink(const ILink& link) = 0; - //@} - /** \name Source / Target management */ - //@{ + /** + * \brief Changes this link's id + * \param id [in] : The new id this link should have + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool setIdentifier(const CIdentifier& id) = 0; + /** + * \brief Gets the identifier of this link + * \return The identifier of this link. + */ + virtual CIdentifier getIdentifier() const = 0; - /** - * \brief Sets the source of this link - * \param boxID [in] : The identifier of the source box - * \param boxOutputIdx [in] : The index of the output to use on the source box - * \param boxOutputID [in] : The identifier of the output to use on the source box - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool setSource(const CIdentifier& boxID, size_t boxOutputIdx, CIdentifier boxOutputID) = 0; - /** - * \brief Sets the target of this link - * \param boxID [in] : The identifier of the target box - * \param boxInputIdx [in] : The index of the input to use on the target box - * \param boxInputID [in] : The identifier of the input to use on the target box - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool setTarget(const CIdentifier& boxID, size_t boxInputIdx, CIdentifier boxInputID) = 0; - /** - * \brief Gets the source information for this link - * \param boxID [out] : The identifier of the source box - * \param boxOutputIdx [out] : The output index of the source box - * \param boxOutputID [out] : The output identifier of the target box - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool getSource(CIdentifier& boxID, size_t& boxOutputIdx, CIdentifier& boxOutputID) const = 0; - /** - * \brief Gets the source box identifier for this link - * \return the source box identifier for thit link - */ - virtual CIdentifier getSourceBoxIdentifier() const = 0; - /** - * \brief Gets the source box output index for this link - * \return the source box output index for this link - */ - virtual size_t getSourceBoxOutputIndex() const = 0; - /** - * \brief Gets the source box output index for this link - * \return the source box output index for this link - */ - virtual CIdentifier getSourceBoxOutputIdentifier() const = 0; - /** - * \brief Gets the target information for this link - * \param boxID [out] : The identifier of the target box - * \param boxInputIdx [out] : The input index of the target box - * \param boxInputID [out] : The input identifier of the target box - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool getTarget(CIdentifier& boxID, size_t& boxInputIdx, CIdentifier& boxInputID) const = 0; - /** - * \brief Gets the target box identifier for this link - * \return the target box identifier for this link - */ - virtual CIdentifier getTargetBoxIdentifier() const = 0; - /** - * \brief Gets the target box input index for this link - * \return the target box input index for this link - */ - virtual size_t getTargetBoxInputIndex() const = 0; - /** - * \brief Gets the target box input identifier for this link - * \return the target box input identifier for this link - */ - virtual CIdentifier getTargetBoxInputIdentifier() const = 0; + //@} + /** \name Source / Target management */ + //@{ - //@} + /** + * \brief Sets the source of this link + * \param boxID [in] : The identifier of the source box + * \param boxOutputIdx [in] : The index of the output to use on the source box + * \param boxOutputID [in] : The identifier of the output to use on the source box + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool setSource(const CIdentifier& boxID, size_t boxOutputIdx, CIdentifier boxOutputID) = 0; + /** + * \brief Sets the target of this link + * \param boxID [in] : The identifier of the target box + * \param boxInputIdx [in] : The index of the input to use on the target box + * \param boxInputID [in] : The identifier of the input to use on the target box + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool setTarget(const CIdentifier& boxID, size_t boxInputIdx, CIdentifier boxInputID) = 0; + /** + * \brief Gets the source information for this link + * \param boxID [out] : The identifier of the source box + * \param boxOutputIdx [out] : The output index of the source box + * \param boxOutputID [out] : The output identifier of the target box + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool getSource(CIdentifier& boxID, size_t& boxOutputIdx, CIdentifier& boxOutputID) const = 0; + /** + * \brief Gets the source box identifier for this link + * \return the source box identifier for thit link + */ + virtual CIdentifier getSourceBoxIdentifier() const = 0; + /** + * \brief Gets the source box output index for this link + * \return the source box output index for this link + */ + virtual size_t getSourceBoxOutputIndex() const = 0; + /** + * \brief Gets the source box output index for this link + * \return the source box output index for this link + */ + virtual CIdentifier getSourceBoxOutputIdentifier() const = 0; + /** + * \brief Gets the target information for this link + * \param boxID [out] : The identifier of the target box + * \param boxInputIdx [out] : The input index of the target box + * \param boxInputID [out] : The input identifier of the target box + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool getTarget(CIdentifier& boxID, size_t& boxInputIdx, CIdentifier& boxInputID) const = 0; + /** + * \brief Gets the target box identifier for this link + * \return the target box identifier for this link + */ + virtual CIdentifier getTargetBoxIdentifier() const = 0; + /** + * \brief Gets the target box input index for this link + * \return the target box input index for this link + */ + virtual size_t getTargetBoxInputIndex() const = 0; + /** + * \brief Gets the target box input identifier for this link + * \return the target box input identifier for this link + */ + virtual CIdentifier getTargetBoxInputIdentifier() const = 0; - _IsDerivedFromClass_(IAttributable, OV_ClassId_Kernel_Scenario_Link) - }; - } // namespace Kernel -} // namespace OpenViBE + //@} + + _IsDerivedFromClass_(IAttributable, OV_ClassId_Kernel_Scenario_Link) +}; +} // namespace Kernel +} // namespace OpenViBE diff --git a/openvibe/include/openvibe/kernel/scenario/ovIMetadata.h b/openvibe/include/openvibe/kernel/scenario/ovIMetadata.h index 3dc1929f2db6804fcc018f7c2c247c799f45d3c7..fec2aafceba766de5610f09d7eed42ce48a14281 100644 --- a/openvibe/include/openvibe/kernel/scenario/ovIMetadata.h +++ b/openvibe/include/openvibe/kernel/scenario/ovIMetadata.h @@ -2,76 +2,74 @@ #include "../ovIKernelObject.h" -namespace OpenViBE +namespace OpenViBE { +namespace Kernel { +/** + * \class IMetadata + * \author Jozef Legeny + * \date 2016-10-11 + * \brief Metadata class for scenarios + * + * Scenario can contain string metadata for the purpose of being used by applications. Each piece of metadata is identified by a (unique) Identifier + * and a (non-unique) Type. Applications can create metadata in scenarios and should not modify metadata with types they do not understand. + * + * \ingroup Group_Scenario + * \ingroup Group_Kernel + */ +class OV_API IMetadata : public IKernelObject { - namespace Kernel - { - /** - * \class IMetadata - * \author Jozef Legeny - * \date 2016-10-11 - * \brief Metadata class for scenarios - * - * Scenario can contain string metadata for the purpose of being used by applications. Each piece of metadata is identified by a (unique) Identifier - * and a (non-unique) Type. Applications can create metadata in scenarios and should not modify metadata with types they do not understand. - * - * \ingroup Group_Scenario - * \ingroup Group_Kernel - */ - class OV_API IMetadata : public IKernelObject - { - public: +public: - /** - * \return The identifier of this scenario metadata. - */ - virtual CIdentifier getIdentifier() const = 0; + /** + * \return The identifier of this scenario metadata. + */ + virtual CIdentifier getIdentifier() const = 0; - /** - * \return The type of this scenario metadata - */ - virtual CIdentifier getType() const = 0; + /** + * \return The type of this scenario metadata + */ + virtual CIdentifier getType() const = 0; - /** - * \return The enclosed metadata - */ - virtual CString getData() const = 0; + /** + * \return The enclosed metadata + */ + virtual CString getData() const = 0; - /** - * \brief Change the identifier of this metadata - * \param[in] id The new id - * \retval true in case of success. - * \retval false in case of error. - */ - virtual bool setIdentifier(const CIdentifier& id) = 0; + /** + * \brief Change the identifier of this metadata + * \param[in] id The new id + * \retval true in case of success. + * \retval false in case of error. + */ + virtual bool setIdentifier(const CIdentifier& id) = 0; - /** - * \brief Change the identifier of this metadata - * \param[in] id The new id - * \retval true in case of success. - * \retval false in case of error. - */ - virtual bool setType(const CIdentifier& id) = 0; + /** + * \brief Change the identifier of this metadata + * \param[in] id The new id + * \retval true in case of success. + * \retval false in case of error. + */ + virtual bool setType(const CIdentifier& id) = 0; - /** - * \brief Change the enclosed data - * \param[in] data The text this comment should contain - * \retval true in case of success. - * \retval false in case of error. - */ - virtual bool setData(const CString& data) = 0; + /** + * \brief Change the enclosed data + * \param[in] data The text this comment should contain + * \retval true in case of success. + * \retval false in case of error. + */ + virtual bool setData(const CString& data) = 0; - /** - * \brief Initializes the metadata from an already existing metadata - * \param[in] metadata The existing metadata - * \retval true in case of success. - * \retval false in case of error. - * - * Resets the metadata and initializes its text/attributes according to the existing object. - */ - virtual bool initializeFromExistingMetadata(const IMetadata& metadata) = 0; + /** + * \brief Initializes the metadata from an already existing metadata + * \param[in] metadata The existing metadata + * \retval true in case of success. + * \retval false in case of error. + * + * Resets the metadata and initializes its text/attributes according to the existing object. + */ + virtual bool initializeFromExistingMetadata(const IMetadata& metadata) = 0; - _IsDerivedFromClass_(IKernelObject, OV_ClassId_Kernel_Scenario_Metadata) - }; - } // namespace Kernel -} // namespace OpenViBE + _IsDerivedFromClass_(IKernelObject, OV_ClassId_Kernel_Scenario_Metadata) +}; +} // namespace Kernel +} // namespace OpenViBE diff --git a/openvibe/include/openvibe/kernel/scenario/ovIScenario.h b/openvibe/include/openvibe/kernel/scenario/ovIScenario.h index 34ddf7e495147a985c67c2c1c83d736cb8ca2cd4..4986bc836ec0e9c6ca4eb1e1c3a402d2e2ba9ba6 100644 --- a/openvibe/include/openvibe/kernel/scenario/ovIScenario.h +++ b/openvibe/include/openvibe/kernel/scenario/ovIScenario.h @@ -2,538 +2,535 @@ #include "ovIBox.h" -namespace OpenViBE +namespace OpenViBE { +class IMemoryBuffer; + +namespace Plugins { +class IBoxAlgorithmDesc; +} // namespace Plugins + +namespace Kernel { +class ILink; +class IComment; +class IMetadata; +class IConfigurationManager; + +/** + * \class IScenario + * \author Yann Renard (IRISA/INRIA) + * \date 2006-08-16 + * \brief A static OpenViBE scenario + * \ingroup Group_Scenario + * \ingroup Group_Kernel + * + * This class is a static scenario description. + * It is used to manipulate an OpenViBE + * box/connection collection... + * + * \todo Add meta information for this scenario + */ +class OV_API IScenario : public IBox { - class IMemoryBuffer; - - namespace Plugins - { - class IBoxAlgorithmDesc; - } // namespace Plugins - - namespace Kernel +public: + class IScenarioMergeCallback { - class ILink; - class IComment; - class IMetadata; - class IConfigurationManager; - - /** - * \class IScenario - * \author Yann Renard (IRISA/INRIA) - * \date 2006-08-16 - * \brief A static OpenViBE scenario - * \ingroup Group_Scenario - * \ingroup Group_Kernel - * - * This class is a static scenario description. - * It is used to manipulate an OpenViBE - * box/connection collection... - * - * \todo Add meta information for this scenario - */ - class OV_API IScenario : public IBox - { - public: - class IScenarioMergeCallback - { - public: - virtual void process(CIdentifier& originalID, CIdentifier& newID) = 0; - virtual ~IScenarioMergeCallback() = default; - }; - - /** \name General purpose functions */ - //@{ - - /** - * \brief Clears the scenario - * \retval true In case of success. - * \retval false In case of error. - */ - virtual bool clear() = 0; - - /** - * \brief Merges this scenario with an other existing scenario - * \param scenario A reference to the scenario to merge this scenario with - * \param scenarioMergeCallback A callback that will be called for each merged element and will be passed the old and new identifiers - * \param mergeSettings When true, the settings from the source scenario will also be merged - * \param preserveIDs When true, the element identifiers from the source scenario will be preserved. - * \retval true In case of success - * \retval false In case of error - * \note The \c bPreservedIdentifiers setting is only reliable when the destination scenario is empty. As an identifier can only be - * preserved when the destination scenario does not contain any elements which use it. In general, this parameter should only be set - * to true when cloning a scenario. - */ - virtual bool merge(const IScenario& scenario, IScenarioMergeCallback* scenarioMergeCallback, bool mergeSettings, bool preserveIDs) = 0; - - //@} - /** \name Box management */ - //@{ - - /** - * \brief Gets next box identifier - * \param previousID The identifier - * for the preceeding box - * \return The identifier of the next box in case of success. - * \retval OV_UndefinedIdentifier on error. - * \note Giving \c OV_UndefinedIdentifier as \c previousID - * will cause this function to return the first box - * identifier. - */ - virtual CIdentifier getNextBoxIdentifier(const CIdentifier& previousID) const = 0; - - /** - * \brief Tests whether a given identifier is a box or not - * \param boxID the identifier to test - * \retval true if the identified object is a box - * \retval false if the identified object is not a box - * \note Requesting a bad identifier returns \e false - */ - virtual bool isBox(const CIdentifier& boxID) const = 0; - - /** - * \brief Gets the details for a specific box - * \param boxID The identifier of the box which details should be sent. - * \return The box details - */ - virtual const IBox* getBoxDetails(const CIdentifier& boxID) const = 0; - - /// \copydoc getBoxDetails(const CIdentifier&)const - virtual IBox* getBoxDetails(const CIdentifier& boxID) = 0; - - /** - * \brief Adds a new box in the scenario - * \param[out] boxID The identifier of the created box - * \param suggestedBoxID A suggestion for the new box identifier. If this specific identifier is not - * yet used, this scenario might use it. If the identifier is already used or \c OV_UndefinedIdentifier is passed, - * then a random unused identifier will be used. - * \retval true In case of success. - * \retval false In case of error. In such case, \c boxID remains unchanged. - * \note This produces an empty and unconfigured box! - */ - virtual bool addBox(CIdentifier& boxID, const CIdentifier& suggestedBoxID) = 0; - /** - * \brief Adds a new box in the scenario based on an existing box - * \param[out] boxID The identifier of the created box - * \param box The box to copy in this scenario - * \param suggestedBoxID a suggestion for the new box identifier. If this specific identifier is not - * yet used, this scenario might use it. If the identifier is already used or \c OV_UndefinedIdentifier is passed, - * then a random unused identifier will be used. - * \retval true In case of success. - * \retval false In case of error. In such case, \c boxID remains unchanged. - */ - virtual bool addBox(CIdentifier& boxID, const IBox& box, const CIdentifier& suggestedBoxID) = 0; - /** - * \brief Adds a new box in the scenario - * \param[out] boxID The identifier of the created box - * \param boxAlgorithmClassID The class identifier of the algorithm for this box - * \param suggestedBoxID a suggestion for the new box identifier. If this specific identifier is not - * yet used, this scenario might use it. If the identifier is already used or \c OV_UndefinedIdentifier is passed, - * then a random unused identifier will be used. - * \retval true In case of success. - * \retval false In case of error. In such case, \c boxID remains unchanged. - * \note This function prepares the box according to its algorithm class identifier ! - */ - virtual bool addBox(CIdentifier& boxID, const CIdentifier& boxAlgorithmClassID, const CIdentifier& suggestedBoxID) = 0; - - // TODO_JL: Doc - virtual bool addBox(CIdentifier& boxID, const Plugins::IBoxAlgorithmDesc& boxAlgorithmDesc, const CIdentifier& suggestedBoxID) = 0; - - /** - * \brief Removes a box of the scenario - * \param boxID The box identifier - * \retval true In case of success. - * \retval false In case of error. - * \note Each link related to this box is also removed - */ - virtual bool removeBox(const CIdentifier& boxID) = 0; - - //@} - /** \name Connection management */ - //@{ - - /** - * \brief Gets next link identifier - * \param previousID The identifier for the preceeding link - * \return The identifier of the next link in case of success. - * \retval OV_UndefinedIdentifier on error. - * \note Giving \c OV_UndefinedIdentifier as \c previousID will cause this function to return the first link identifier. - */ - virtual CIdentifier getNextLinkIdentifier(const CIdentifier& previousID) const = 0; - - /** - * \brief Gets next link identifier from fixed box - * \param previousID The identifier for the preceeding link - * \param boxID The box identifier which the link should end to - * \return The identifier of the next link in case of success. - * \retval OV_UndefinedIdentifier on error. - * \note Giving \c OV_UndefinedIdentifier as \c previousID will cause this function to return the first link identifier. - */ - virtual CIdentifier getNextLinkIdentifierFromBox(const CIdentifier& previousID, const CIdentifier& boxID) const = 0; - - /** - * \brief Gets next link identifier from fixed box output - * \param previousID The identifier for the preceeding link - * \param boxID The box identifier which the link should end to - * \param outputIdx The input index which the link should end to - * \return The identifier of the next link in case of success. - * \retval OV_UndefinedIdentifier on error. - * \note Giving \c OV_UndefinedIdentifier as \c previousID will cause this function to return the first link identifier. - */ - virtual CIdentifier getNextLinkIdentifierFromBoxOutput(const CIdentifier& previousID, const CIdentifier& boxID, size_t outputIdx) const = 0; - - /** - * \brief Gets next link identifier from fixed box - * \param previousID The identifier for the preceeding link - * \param boxID The box identifier which the link should start from - * \return The identifier of the next link in case of success. - * \retval OV_UndefinedIdentifier on error. - * \note Giving \c OV_UndefinedIdentifier as \c previousID will cause this function to return the first link identifier. - */ - virtual CIdentifier getNextLinkIdentifierToBox(const CIdentifier& previousID, const CIdentifier& boxID) const = 0; - - /** - * \brief Gets next link identifier from fixed box input - * \param previousID The identifier for the preceeding link - * \param boxID The box identifier which the link should start from - * \param index The input index which the link should start from - * \return The identifier of the next link in case of success. - * \retval OV_UndefinedIdentifier on error. - * \note Giving \c OV_UndefinedIdentifier as \c previousID will cause this function to return the first link identifier. - */ - virtual CIdentifier getNextLinkIdentifierToBoxInput(const CIdentifier& previousID, const CIdentifier& boxID, size_t index) const = 0; - - /** - * \brief Tests whether a given id is a link or not - * \param id the id to test - * \retval true if the identified object is a link - * \retval false if the identified object is not a link - * \note Requesting a bad id returns \e false - */ - virtual bool isLink(const CIdentifier& id) const = 0; - - /** - * \brief Gets the details for a specific link - * \param id The identifier of the link which details should be sent. - * \return The link details - */ - virtual const ILink* getLinkDetails(const CIdentifier& id) const = 0; - - /// \copydoc getLinkDetails(const CIdentifier&)const - virtual ILink* getLinkDetails(const CIdentifier& id) = 0; - - /** - * \brief Creates a connection between two boxes - * \param[out] linkID The created link identifier. - * \param srcBoxID The source box identifier - * \param srcBoxOutputIdx The output index for the given source box - * \param dstBoxID The target box identifier - * \param dstBoxInputIndex The input index for the given target box - * \param suggestedLinkID a suggestion for the new link identifier. If this specific identifier is not - * yet used, this scenario might use it. If the identifier is already used or \c OV_UndefinedIdentifier is passed, - * then a random unused identifier will be used. - * \retval true In case of success. - * \retval false In case of error. In such case, \c linkID remains unchanged. - */ - virtual bool connect(CIdentifier& linkID, const CIdentifier& srcBoxID, const size_t srcBoxOutputIdx, - const CIdentifier& dstBoxID, const size_t dstBoxInputIndex, const CIdentifier& suggestedLinkID) = 0; - - /** - * \brief Creates a connection between two boxes - * \param[out] linkID The created link identifier. - * \param srcBoxID The source box identifier - * \param srcBoxOutputID The output identifier for the given source box - * \param dstBoxID The target box identifier - * \param dstBoxInputID The input identifier for the given target box - * \param suggestedLinkID a suggestion for the new link identifier. If this specific identifier is not - * yet used, this scenario might use it. If the identifier is already used or \c OV_UndefinedIdentifier is passed, - * then a random unused identifier will be used. - * \retval true In case of success. - * \retval false In case of error. In such case, \c linkID remains unchanged. - */ - virtual bool connect(CIdentifier& linkID, const CIdentifier& srcBoxID, const CIdentifier& srcBoxOutputID, - const CIdentifier& dstBoxID, const CIdentifier& dstBoxInputID, const CIdentifier& suggestedLinkID) = 0; - - /** - * \brief Deletes a connection between two boxes - * \param srcBoxID The source box identifier - * \param srcBoxOutputIdx The output index for the given source box - * \param dstBoxID The target box identifier - * \param dstBoxInputIdx The input index for the given target box - * \retval true In case of success. - * \retval false In case of error. - */ - virtual bool disconnect(const CIdentifier& srcBoxID, size_t srcBoxOutputIdx, const CIdentifier& dstBoxID, size_t dstBoxInputIdx) = 0; - - /** - * \brief Deletes a connection between two boxes - * \param srcBoxID The source box identifier - * \param srcBoxOutputID The output identifier for the given source box - * \param dstBoxID The target box identifier - * \param dstBoxInputID The input identifier for the given target box - * \retval true In case of success. - * \retval false In case of error. - */ - virtual bool disconnect(const CIdentifier& srcBoxID, const CIdentifier& srcBoxOutputID, const CIdentifier& dstBoxID, - const CIdentifier& dstBoxInputID) = 0; - - /** - * \brief Deletes a connection between two boxes - * \param[out] linkID The identifier for the link to be deleted - * \retval true In case of success. - * \retval false In case of error. - */ - virtual bool disconnect(const CIdentifier& linkID) = 0; - - /** - * \brief Get the output index of a source, for a specific box - * \param[in] srcBoxID The source box identifier - * \param[in] srcBoxOutputID The output identifier for the given source box - * \param[out] srcBoxOutputIdx The output index for the given source box - * \retval true in case of success. - */ - virtual bool getSourceBoxOutputIndex(const CIdentifier& srcBoxID, const CIdentifier& srcBoxOutputID, size_t& srcBoxOutputIdx) = 0; - - /** - * \brief Get the input index of a target, for a specific box - * \param[in] dstBoxID The target box identifier - * \param[in] dstBoxInputID The input identifier for the given target box - * \param[out] dstBoxInputIdx The input index for the given target box - * \retval true in case of success. - */ - virtual bool getTargetBoxInputIndex(const CIdentifier& dstBoxID, const CIdentifier& dstBoxInputID, size_t& dstBoxInputIdx) = 0; - - /** - * \brief Get the output identifier of a source, for a specific box - * \param srcBoxID The source box identifier - * \param srcBoxOutputIdx The output index for the given source box - * \param srcBoxOutputID The output identifier for the given source box - * \retval true in case of success. - */ - virtual bool getSourceBoxOutputIdentifier(const CIdentifier& srcBoxID, const size_t& srcBoxOutputIdx, CIdentifier& srcBoxOutputID) = 0; - - /** - * \brief Get the input identifier of a target, for a specific box - * \param dstBoxID The target box identifier - * \param dstBoxInputIdx The input index for the given target box - * \param dstBoxInputID The input identifier for the given target box - * \retval true in case of success. - */ - virtual bool getTargetBoxInputIdentifier(const CIdentifier& dstBoxID, const size_t& dstBoxInputIdx, CIdentifier& dstBoxInputID) = 0; - - //@} - /** \name Scenario Input/Output and MetaBox management */ - //@{ - - virtual bool setHasIO(bool hasIO) = 0; - virtual bool hasIO() const = 0; - - virtual bool setScenarioInputLink(size_t scenarioInputIdx, const CIdentifier& boxID, size_t boxInputIdx) = 0; - virtual bool setScenarioInputLink(size_t scenarioInputIdx, const CIdentifier& boxID, const CIdentifier& boxInputID) = 0; - virtual bool setScenarioOutputLink(size_t scenarioOutputIdx, const CIdentifier& boxID, size_t boxOutputIdx) = 0; - virtual bool setScenarioOutputLink(size_t scenarioOutputIdx, const CIdentifier& boxID, const CIdentifier& boxOutputID) = 0; - - virtual bool getScenarioInputLink(size_t scenarioInputIdx, CIdentifier& boxID, size_t& boxInputIdx) const = 0; - virtual bool getScenarioInputLink(size_t scenarioInputIdx, CIdentifier& boxID, CIdentifier& boxInputID) const = 0; - virtual bool getScenarioOutputLink(size_t scenarioOutputIdx, CIdentifier& boxID, size_t& boxOutputIdx) const = 0; - virtual bool getScenarioOutputLink(size_t scenarioOutputIdx, CIdentifier& boxID, CIdentifier& boxOutputID) const = 0; - - virtual bool removeScenarioInputLink(size_t scenarioInputIdx, const CIdentifier& boxID, size_t boxInputIdx) = 0; - virtual bool removeScenarioOutputLink(size_t scenarioOutputIdx, const CIdentifier& boxID, size_t boxOutputIdx) = 0; - - virtual bool removeScenarioInput(size_t index) = 0; - virtual bool removeScenarioOutput(size_t outputIdx) = 0; - - //@} - /** \name Comment management */ - //@{ - - /** - * \brief Gets next comment identifier - * \param previousID The identifier for the preceeding comment - * \return The identifier of the next comment in case of success. - * \retval OV_UndefinedIdentifier on error. - * \note Giving \c OV_UndefinedIdentifier as \c previousID will cause this function to return the first comment identifier. - */ - virtual CIdentifier getNextCommentIdentifier(const CIdentifier& previousID) const = 0; - - /** - * \brief Tests whether a given identifier is a comment or not - * \param commentID the identifier to test - * \retval true if the identified object is a comment - * \retval false if the identified object is not a comment - * \note Requesting a bad identifier returns \e false - */ - virtual bool isComment(const CIdentifier& commentID) const = 0; - - /** - * \brief Gets the details for a specific comment - * \param commentID The identifier of the comment which details should be sent. - * \return The comment details - */ - virtual const IComment* getCommentDetails(const CIdentifier& commentID) const = 0; - - /// \copydoc getCommentDetails(const CIdentifier&)const - virtual IComment* getCommentDetails(const CIdentifier& commentID) = 0; - - /** - * \brief Adds a new comment in the scenario - * \param[out] commentID The identifier of the created comment - * \param suggestedCommentID a suggestion for the new comment identifier. If this specific identifier is not - * yet used, this scenario might use it. If the identifier is already used or \c OV_UndefinedIdentifier is passed, - * then a random unused identifier will be used. - * \retval true In case of success. - * \retval false In case of error. In such case, \c commentID remains unchanged. - * \note This produces an empty and unconfigured comment! - */ - virtual bool addComment(CIdentifier& commentID, const CIdentifier& suggestedCommentID) = 0; - - /** - * \brief Adds a new comment in the scenario based on an existing comment - * \param[out] commentID The identifier of the created comment - * \param comment the comment to copy in this scenario - * \param suggestedCommentID a suggestion for the new comment identifier. If this specific identifier is not - * yet used, this scenario might use it. If the identifier is already used or \c OV_UndefinedIdentifier is passed, - * then a random unused identifier will be used. - * \retval true In case of success. - * \retval false In case of error. In such case, \c commentID remains unchanged. - */ - virtual bool addComment(CIdentifier& commentID, const IComment& comment, const CIdentifier& suggestedCommentID) = 0; - /** - * \brief Removes a comment of the scenario - * \param commentID The comment identifier - * \retval true In case of success. - * \retval false In case of error. - */ - virtual bool removeComment(const CIdentifier& commentID) = 0; - - //@} - /** \name Metadata management */ - //@{ - - /** - * \brief Get next metadata identifier in regards to another - * \param previousID The identifier of the metadata - * \retval OV_UndefinedIdentifier In case when metadata with the \c previousID is not present - * \retval OV_UndefinedIdentifier In case when metadata with the \c previousID is last in the scenario - * \return The identifier of the next metadata - * \note Giving \c OV_UndefinedIdentifier as \c previousID will cause this function to return the first metadata identifier. - */ - virtual CIdentifier getNextMetadataIdentifier(const CIdentifier& previousID) const = 0; - - /** - * \param metadataID The identifier to test - * \retval true If the identified object is metadata - * \retval false If the identified object is not metadata or when the identifier is not present in the scenario - */ - virtual bool isMetadata(const CIdentifier& metadataID) const = 0; - - - /** - * \param metadataID The identifier of a metadata - * \return Pointer to object containing metadata details - */ - virtual const IMetadata* getMetadataDetails(const CIdentifier& metadataID) const = 0; - - /// \copydoc getMetadataDetails(const CIdentifier&)const - virtual IMetadata* getMetadataDetails(const CIdentifier& metadataID) = 0; - - /** - * \brief Add new metadata in the scenario - * \param[out] metadataID The identifier of the newly created metadata - * \param suggestedMetadataID A suggestion for the new identifier. If the identifier is already used or \c OV_UndefinedIdentifier is passed, - * then a random unused identifier will be used. - * \retval true In case of success. - * \retval false In case of error. In this case, \c metadataID remains unchanged. - * \note This method creates an empty metadata. - */ - virtual bool addMetadata(CIdentifier& metadataID, const CIdentifier& suggestedMetadataID) = 0; - - /** - * \brief Remove metadata from the scenario - * \param metadataID The metadata identifier - * \retval true In case of success. - * \retval false In case of error. - */ - virtual bool removeMetadata(const CIdentifier& metadataID) = 0; - //@} - - /** - * \brief replaces settings of each box by its locally expanded version only expands the $var{} tokens, it leaves others as is - */ - virtual bool applyLocalSettings() = 0; - - /** - * \brief Check settings before playing scenario, if the settings are not suitable, stop scenario - * and launch a console warning. Only check numeric values in the beginning - * \param configManager: local configuration manager that can contain the definition of local scenario settings - */ - virtual bool checkSettings(IConfigurationManager* configManager) = 0; - - /** - * \brief Check if boxes in scenario need to be updated. Feed an map of updates boxes instances with the identifiers - * of outdated boxes - * \return true if at least one box needs to updated - */ - virtual bool checkOutdatedBoxes() = 0; - - /** - * \brief Gets identifier of next outdated box - * \param previousID The identifier for the preceeding outdated box - * \return The identifier of the next box that needs updates in case of success. - * \retval OV_UndefinedIdentifier on error. - * \note Giving \c OV_UndefinedIdentifier as \c previousID will cause this function to return the first processing unit identifier. - * \note Warning: You need to call at least once the function "checkOutdatedBoxes", before calling this function - */ - virtual CIdentifier getNextOutdatedBoxIdentifier(const CIdentifier& previousID) const = 0; - - /** - * \brief Indicates if at least one box in scenario need to be updated. - * \return true if at least one box needs to updated - * \note Warning: You need to call at least once the function "checkOutdatedBoxes", before calling this function - */ - virtual bool hasOutdatedBox() = 0; - - /** - * \brief Update the prototypes of the box identified by the given identifier. - * \param boxID - * \retval true in case of success - * \retval false in case of error - */ - virtual bool updateBox(const CIdentifier& boxID) = 0; - - /** - * \brief Remove deprecated interfacors from the box identified by the given identifier. - * \param boxID Id of the box to clean up - * \retval true in case of success - * \retval false if the box does not exist - */ - virtual bool removeDeprecatedInterfacorsFromBox(const CIdentifier& boxID) = 0; - - /** - * \brief Check if scenario contains a box with a deprecated interfacor due to an incomplete update - * \retval true if a box in the scenario has a deprecated interfacor - * \retval false if no box in the scenario contains a deprecated interfacor - */ - virtual bool containsBoxWithDeprecatedInterfacors() const = 0; - - /** - * \return true if the scenario is actually a metabox - */ - virtual bool isMetabox() = 0; - - virtual void getBoxIdentifierList(CIdentifier** listID, size_t* size) const = 0; - virtual void getCommentIdentifierList(CIdentifier** listID, size_t* size) const = 0; - virtual void getMetadataIdentifierList(CIdentifier** listID, size_t* size) const = 0; - virtual void getLinkIdentifierList(CIdentifier** listID, size_t* size) const = 0; - virtual void getLinkIdentifierFromBoxList(const CIdentifier& boxID, CIdentifier** listID, size_t* size) const = 0; - virtual void getLinkIdentifierFromBoxOutputList(const CIdentifier& boxID, size_t outputIdx, CIdentifier** listID, size_t* size) const = 0; - virtual void getLinkIdentifierToBoxList(const CIdentifier& boxID, CIdentifier** listID, size_t* size) const = 0; - virtual void getLinkIdentifierToBoxInputList(const CIdentifier& boxID, size_t inputIdx, CIdentifier** listID, size_t* size) const = 0; - virtual void getOutdatedBoxIdentifierList(CIdentifier** listID, size_t* size) const = 0; - virtual void releaseIdentifierList(CIdentifier* listID) const = 0; - - _IsDerivedFromClass_(IBox, OV_ClassId_Kernel_Scenario_Scenario) - }; - } // namespace Kernel -} // namespace OpenViBE + public: + virtual void process(CIdentifier& originalID, CIdentifier& newID) = 0; + virtual ~IScenarioMergeCallback() = default; + }; + + /** \name General purpose functions */ + //@{ + + /** + * \brief Clears the scenario + * \retval true In case of success. + * \retval false In case of error. + */ + virtual bool clear() = 0; + + /** + * \brief Merges this scenario with an other existing scenario + * \param scenario A reference to the scenario to merge this scenario with + * \param scenarioMergeCallback A callback that will be called for each merged element and will be passed the old and new identifiers + * \param mergeSettings When true, the settings from the source scenario will also be merged + * \param preserveIDs When true, the element identifiers from the source scenario will be preserved. + * \retval true In case of success + * \retval false In case of error + * \note The \c bPreservedIdentifiers setting is only reliable when the destination scenario is empty. As an identifier can only be + * preserved when the destination scenario does not contain any elements which use it. In general, this parameter should only be set + * to true when cloning a scenario. + */ + virtual bool merge(const IScenario& scenario, IScenarioMergeCallback* scenarioMergeCallback, bool mergeSettings, bool preserveIDs) = 0; + + //@} + /** \name Box management */ + //@{ + + /** + * \brief Gets next box identifier + * \param previousID The identifier + * for the preceeding box + * \return The identifier of the next box in case of success. + * \retval OV_UndefinedIdentifier on error. + * \note Giving \c OV_UndefinedIdentifier as \c previousID + * will cause this function to return the first box + * identifier. + */ + virtual CIdentifier getNextBoxIdentifier(const CIdentifier& previousID) const = 0; + + /** + * \brief Tests whether a given identifier is a box or not + * \param boxID the identifier to test + * \retval true if the identified object is a box + * \retval false if the identified object is not a box + * \note Requesting a bad identifier returns \e false + */ + virtual bool isBox(const CIdentifier& boxID) const = 0; + + /** + * \brief Gets the details for a specific box + * \param boxID The identifier of the box which details should be sent. + * \return The box details + */ + virtual const IBox* getBoxDetails(const CIdentifier& boxID) const = 0; + + /// \copydoc getBoxDetails(const CIdentifier&)const + virtual IBox* getBoxDetails(const CIdentifier& boxID) = 0; + + /** + * \brief Adds a new box in the scenario + * \param[out] boxID The identifier of the created box + * \param suggestedBoxID A suggestion for the new box identifier. If this specific identifier is not + * yet used, this scenario might use it. If the identifier is already used or \c OV_UndefinedIdentifier is passed, + * then a random unused identifier will be used. + * \retval true In case of success. + * \retval false In case of error. In such case, \c boxID remains unchanged. + * \note This produces an empty and unconfigured box! + */ + virtual bool addBox(CIdentifier& boxID, const CIdentifier& suggestedBoxID) = 0; + /** + * \brief Adds a new box in the scenario based on an existing box + * \param[out] boxID The identifier of the created box + * \param box The box to copy in this scenario + * \param suggestedBoxID a suggestion for the new box identifier. If this specific identifier is not + * yet used, this scenario might use it. If the identifier is already used or \c OV_UndefinedIdentifier is passed, + * then a random unused identifier will be used. + * \retval true In case of success. + * \retval false In case of error. In such case, \c boxID remains unchanged. + */ + virtual bool addBox(CIdentifier& boxID, const IBox& box, const CIdentifier& suggestedBoxID) = 0; + /** + * \brief Adds a new box in the scenario + * \param[out] boxID The identifier of the created box + * \param boxAlgorithmClassID The class identifier of the algorithm for this box + * \param suggestedBoxID a suggestion for the new box identifier. If this specific identifier is not + * yet used, this scenario might use it. If the identifier is already used or \c OV_UndefinedIdentifier is passed, + * then a random unused identifier will be used. + * \retval true In case of success. + * \retval false In case of error. In such case, \c boxID remains unchanged. + * \note This function prepares the box according to its algorithm class identifier ! + */ + virtual bool addBox(CIdentifier& boxID, const CIdentifier& boxAlgorithmClassID, const CIdentifier& suggestedBoxID) = 0; + + // TODO_JL: Doc + virtual bool addBox(CIdentifier& boxID, const Plugins::IBoxAlgorithmDesc& boxAlgorithmDesc, const CIdentifier& suggestedBoxID) = 0; + + /** + * \brief Removes a box of the scenario + * \param boxID The box identifier + * \retval true In case of success. + * \retval false In case of error. + * \note Each link related to this box is also removed + */ + virtual bool removeBox(const CIdentifier& boxID) = 0; + + //@} + /** \name Connection management */ + //@{ + + /** + * \brief Gets next link identifier + * \param previousID The identifier for the preceeding link + * \return The identifier of the next link in case of success. + * \retval OV_UndefinedIdentifier on error. + * \note Giving \c OV_UndefinedIdentifier as \c previousID will cause this function to return the first link identifier. + */ + virtual CIdentifier getNextLinkIdentifier(const CIdentifier& previousID) const = 0; + + /** + * \brief Gets next link identifier from fixed box + * \param previousID The identifier for the preceeding link + * \param boxID The box identifier which the link should end to + * \return The identifier of the next link in case of success. + * \retval OV_UndefinedIdentifier on error. + * \note Giving \c OV_UndefinedIdentifier as \c previousID will cause this function to return the first link identifier. + */ + virtual CIdentifier getNextLinkIdentifierFromBox(const CIdentifier& previousID, const CIdentifier& boxID) const = 0; + + /** + * \brief Gets next link identifier from fixed box output + * \param previousID The identifier for the preceeding link + * \param boxID The box identifier which the link should end to + * \param outputIdx The input index which the link should end to + * \return The identifier of the next link in case of success. + * \retval OV_UndefinedIdentifier on error. + * \note Giving \c OV_UndefinedIdentifier as \c previousID will cause this function to return the first link identifier. + */ + virtual CIdentifier getNextLinkIdentifierFromBoxOutput(const CIdentifier& previousID, const CIdentifier& boxID, size_t outputIdx) const = 0; + + /** + * \brief Gets next link identifier from fixed box + * \param previousID The identifier for the preceeding link + * \param boxID The box identifier which the link should start from + * \return The identifier of the next link in case of success. + * \retval OV_UndefinedIdentifier on error. + * \note Giving \c OV_UndefinedIdentifier as \c previousID will cause this function to return the first link identifier. + */ + virtual CIdentifier getNextLinkIdentifierToBox(const CIdentifier& previousID, const CIdentifier& boxID) const = 0; + + /** + * \brief Gets next link identifier from fixed box input + * \param previousID The identifier for the preceeding link + * \param boxID The box identifier which the link should start from + * \param index The input index which the link should start from + * \return The identifier of the next link in case of success. + * \retval OV_UndefinedIdentifier on error. + * \note Giving \c OV_UndefinedIdentifier as \c previousID will cause this function to return the first link identifier. + */ + virtual CIdentifier getNextLinkIdentifierToBoxInput(const CIdentifier& previousID, const CIdentifier& boxID, size_t index) const = 0; + + /** + * \brief Tests whether a given id is a link or not + * \param id the id to test + * \retval true if the identified object is a link + * \retval false if the identified object is not a link + * \note Requesting a bad id returns \e false + */ + virtual bool isLink(const CIdentifier& id) const = 0; + + /** + * \brief Gets the details for a specific link + * \param id The identifier of the link which details should be sent. + * \return The link details + */ + virtual const ILink* getLinkDetails(const CIdentifier& id) const = 0; + + /// \copydoc getLinkDetails(const CIdentifier&)const + virtual ILink* getLinkDetails(const CIdentifier& id) = 0; + + /** + * \brief Creates a connection between two boxes + * \param[out] linkID The created link identifier. + * \param srcBoxID The source box identifier + * \param srcBoxOutputIdx The output index for the given source box + * \param dstBoxID The target box identifier + * \param dstBoxInputIndex The input index for the given target box + * \param suggestedLinkID a suggestion for the new link identifier. If this specific identifier is not + * yet used, this scenario might use it. If the identifier is already used or \c OV_UndefinedIdentifier is passed, + * then a random unused identifier will be used. + * \retval true In case of success. + * \retval false In case of error. In such case, \c linkID remains unchanged. + */ + virtual bool connect(CIdentifier& linkID, const CIdentifier& srcBoxID, const size_t srcBoxOutputIdx, + const CIdentifier& dstBoxID, const size_t dstBoxInputIndex, const CIdentifier& suggestedLinkID) = 0; + + /** + * \brief Creates a connection between two boxes + * \param[out] linkID The created link identifier. + * \param srcBoxID The source box identifier + * \param srcBoxOutputID The output identifier for the given source box + * \param dstBoxID The target box identifier + * \param dstBoxInputID The input identifier for the given target box + * \param suggestedLinkID a suggestion for the new link identifier. If this specific identifier is not + * yet used, this scenario might use it. If the identifier is already used or \c OV_UndefinedIdentifier is passed, + * then a random unused identifier will be used. + * \retval true In case of success. + * \retval false In case of error. In such case, \c linkID remains unchanged. + */ + virtual bool connect(CIdentifier& linkID, const CIdentifier& srcBoxID, const CIdentifier& srcBoxOutputID, + const CIdentifier& dstBoxID, const CIdentifier& dstBoxInputID, const CIdentifier& suggestedLinkID) = 0; + + /** + * \brief Deletes a connection between two boxes + * \param srcBoxID The source box identifier + * \param srcBoxOutputIdx The output index for the given source box + * \param dstBoxID The target box identifier + * \param dstBoxInputIdx The input index for the given target box + * \retval true In case of success. + * \retval false In case of error. + */ + virtual bool disconnect(const CIdentifier& srcBoxID, size_t srcBoxOutputIdx, const CIdentifier& dstBoxID, size_t dstBoxInputIdx) = 0; + + /** + * \brief Deletes a connection between two boxes + * \param srcBoxID The source box identifier + * \param srcBoxOutputID The output identifier for the given source box + * \param dstBoxID The target box identifier + * \param dstBoxInputID The input identifier for the given target box + * \retval true In case of success. + * \retval false In case of error. + */ + virtual bool disconnect(const CIdentifier& srcBoxID, const CIdentifier& srcBoxOutputID, const CIdentifier& dstBoxID, + const CIdentifier& dstBoxInputID) = 0; + + /** + * \brief Deletes a connection between two boxes + * \param[out] linkID The identifier for the link to be deleted + * \retval true In case of success. + * \retval false In case of error. + */ + virtual bool disconnect(const CIdentifier& linkID) = 0; + + /** + * \brief Get the output index of a source, for a specific box + * \param[in] srcBoxID The source box identifier + * \param[in] srcBoxOutputID The output identifier for the given source box + * \param[out] srcBoxOutputIdx The output index for the given source box + * \retval true in case of success. + */ + virtual bool getSourceBoxOutputIndex(const CIdentifier& srcBoxID, const CIdentifier& srcBoxOutputID, size_t& srcBoxOutputIdx) = 0; + + /** + * \brief Get the input index of a target, for a specific box + * \param[in] dstBoxID The target box identifier + * \param[in] dstBoxInputID The input identifier for the given target box + * \param[out] dstBoxInputIdx The input index for the given target box + * \retval true in case of success. + */ + virtual bool getTargetBoxInputIndex(const CIdentifier& dstBoxID, const CIdentifier& dstBoxInputID, size_t& dstBoxInputIdx) = 0; + + /** + * \brief Get the output identifier of a source, for a specific box + * \param srcBoxID The source box identifier + * \param srcBoxOutputIdx The output index for the given source box + * \param srcBoxOutputID The output identifier for the given source box + * \retval true in case of success. + */ + virtual bool getSourceBoxOutputIdentifier(const CIdentifier& srcBoxID, const size_t& srcBoxOutputIdx, CIdentifier& srcBoxOutputID) = 0; + + /** + * \brief Get the input identifier of a target, for a specific box + * \param dstBoxID The target box identifier + * \param dstBoxInputIdx The input index for the given target box + * \param dstBoxInputID The input identifier for the given target box + * \retval true in case of success. + */ + virtual bool getTargetBoxInputIdentifier(const CIdentifier& dstBoxID, const size_t& dstBoxInputIdx, CIdentifier& dstBoxInputID) = 0; + + //@} + /** \name Scenario Input/Output and MetaBox management */ + //@{ + + virtual bool setHasIO(bool hasIO) = 0; + virtual bool hasIO() const = 0; + + virtual bool setScenarioInputLink(size_t scenarioInputIdx, const CIdentifier& boxID, size_t boxInputIdx) = 0; + virtual bool setScenarioInputLink(size_t scenarioInputIdx, const CIdentifier& boxID, const CIdentifier& boxInputID) = 0; + virtual bool setScenarioOutputLink(size_t scenarioOutputIdx, const CIdentifier& boxID, size_t boxOutputIdx) = 0; + virtual bool setScenarioOutputLink(size_t scenarioOutputIdx, const CIdentifier& boxID, const CIdentifier& boxOutputID) = 0; + + virtual bool getScenarioInputLink(size_t scenarioInputIdx, CIdentifier& boxID, size_t& boxInputIdx) const = 0; + virtual bool getScenarioInputLink(size_t scenarioInputIdx, CIdentifier& boxID, CIdentifier& boxInputID) const = 0; + virtual bool getScenarioOutputLink(size_t scenarioOutputIdx, CIdentifier& boxID, size_t& boxOutputIdx) const = 0; + virtual bool getScenarioOutputLink(size_t scenarioOutputIdx, CIdentifier& boxID, CIdentifier& boxOutputID) const = 0; + + virtual bool removeScenarioInputLink(size_t scenarioInputIdx, const CIdentifier& boxID, size_t boxInputIdx) = 0; + virtual bool removeScenarioOutputLink(size_t scenarioOutputIdx, const CIdentifier& boxID, size_t boxOutputIdx) = 0; + + virtual bool removeScenarioInput(size_t index) = 0; + virtual bool removeScenarioOutput(size_t outputIdx) = 0; + + //@} + /** \name Comment management */ + //@{ + + /** + * \brief Gets next comment identifier + * \param previousID The identifier for the preceeding comment + * \return The identifier of the next comment in case of success. + * \retval OV_UndefinedIdentifier on error. + * \note Giving \c OV_UndefinedIdentifier as \c previousID will cause this function to return the first comment identifier. + */ + virtual CIdentifier getNextCommentIdentifier(const CIdentifier& previousID) const = 0; + + /** + * \brief Tests whether a given identifier is a comment or not + * \param commentID the identifier to test + * \retval true if the identified object is a comment + * \retval false if the identified object is not a comment + * \note Requesting a bad identifier returns \e false + */ + virtual bool isComment(const CIdentifier& commentID) const = 0; + + /** + * \brief Gets the details for a specific comment + * \param commentID The identifier of the comment which details should be sent. + * \return The comment details + */ + virtual const IComment* getCommentDetails(const CIdentifier& commentID) const = 0; + + /// \copydoc getCommentDetails(const CIdentifier&)const + virtual IComment* getCommentDetails(const CIdentifier& commentID) = 0; + + /** + * \brief Adds a new comment in the scenario + * \param[out] commentID The identifier of the created comment + * \param suggestedCommentID a suggestion for the new comment identifier. If this specific identifier is not + * yet used, this scenario might use it. If the identifier is already used or \c OV_UndefinedIdentifier is passed, + * then a random unused identifier will be used. + * \retval true In case of success. + * \retval false In case of error. In such case, \c commentID remains unchanged. + * \note This produces an empty and unconfigured comment! + */ + virtual bool addComment(CIdentifier& commentID, const CIdentifier& suggestedCommentID) = 0; + + /** + * \brief Adds a new comment in the scenario based on an existing comment + * \param[out] commentID The identifier of the created comment + * \param comment the comment to copy in this scenario + * \param suggestedCommentID a suggestion for the new comment identifier. If this specific identifier is not + * yet used, this scenario might use it. If the identifier is already used or \c OV_UndefinedIdentifier is passed, + * then a random unused identifier will be used. + * \retval true In case of success. + * \retval false In case of error. In such case, \c commentID remains unchanged. + */ + virtual bool addComment(CIdentifier& commentID, const IComment& comment, const CIdentifier& suggestedCommentID) = 0; + /** + * \brief Removes a comment of the scenario + * \param commentID The comment identifier + * \retval true In case of success. + * \retval false In case of error. + */ + virtual bool removeComment(const CIdentifier& commentID) = 0; + + //@} + /** \name Metadata management */ + //@{ + + /** + * \brief Get next metadata identifier in regards to another + * \param previousID The identifier of the metadata + * \retval OV_UndefinedIdentifier In case when metadata with the \c previousID is not present + * \retval OV_UndefinedIdentifier In case when metadata with the \c previousID is last in the scenario + * \return The identifier of the next metadata + * \note Giving \c OV_UndefinedIdentifier as \c previousID will cause this function to return the first metadata identifier. + */ + virtual CIdentifier getNextMetadataIdentifier(const CIdentifier& previousID) const = 0; + + /** + * \param metadataID The identifier to test + * \retval true If the identified object is metadata + * \retval false If the identified object is not metadata or when the identifier is not present in the scenario + */ + virtual bool isMetadata(const CIdentifier& metadataID) const = 0; + + + /** + * \param metadataID The identifier of a metadata + * \return Pointer to object containing metadata details + */ + virtual const IMetadata* getMetadataDetails(const CIdentifier& metadataID) const = 0; + + /// \copydoc getMetadataDetails(const CIdentifier&)const + virtual IMetadata* getMetadataDetails(const CIdentifier& metadataID) = 0; + + /** + * \brief Add new metadata in the scenario + * \param[out] metadataID The identifier of the newly created metadata + * \param suggestedMetadataID A suggestion for the new identifier. If the identifier is already used or \c OV_UndefinedIdentifier is passed, + * then a random unused identifier will be used. + * \retval true In case of success. + * \retval false In case of error. In this case, \c metadataID remains unchanged. + * \note This method creates an empty metadata. + */ + virtual bool addMetadata(CIdentifier& metadataID, const CIdentifier& suggestedMetadataID) = 0; + + /** + * \brief Remove metadata from the scenario + * \param metadataID The metadata identifier + * \retval true In case of success. + * \retval false In case of error. + */ + virtual bool removeMetadata(const CIdentifier& metadataID) = 0; + //@} + + /** + * \brief replaces settings of each box by its locally expanded version only expands the $var{} tokens, it leaves others as is + */ + virtual bool applyLocalSettings() = 0; + + /** + * \brief Check settings before playing scenario, if the settings are not suitable, stop scenario + * and launch a console warning. Only check numeric values in the beginning + * \param configManager: local configuration manager that can contain the definition of local scenario settings + */ + virtual bool checkSettings(IConfigurationManager* configManager) = 0; + + /** + * \brief Check if boxes in scenario need to be updated. Feed an map of updates boxes instances with the identifiers + * of outdated boxes + * \return true if at least one box needs to updated + */ + virtual bool checkOutdatedBoxes() = 0; + + /** + * \brief Gets identifier of next outdated box + * \param previousID The identifier for the preceeding outdated box + * \return The identifier of the next box that needs updates in case of success. + * \retval OV_UndefinedIdentifier on error. + * \note Giving \c OV_UndefinedIdentifier as \c previousID will cause this function to return the first processing unit identifier. + * \note Warning: You need to call at least once the function "checkOutdatedBoxes", before calling this function + */ + virtual CIdentifier getNextOutdatedBoxIdentifier(const CIdentifier& previousID) const = 0; + + /** + * \brief Indicates if at least one box in scenario need to be updated. + * \return true if at least one box needs to updated + * \note Warning: You need to call at least once the function "checkOutdatedBoxes", before calling this function + */ + virtual bool hasOutdatedBox() = 0; + + /** + * \brief Update the prototypes of the box identified by the given identifier. + * \param boxID + * \retval true in case of success + * \retval false in case of error + */ + virtual bool updateBox(const CIdentifier& boxID) = 0; + + /** + * \brief Remove deprecated interfacors from the box identified by the given identifier. + * \param boxID Id of the box to clean up + * \retval true in case of success + * \retval false if the box does not exist + */ + virtual bool removeDeprecatedInterfacorsFromBox(const CIdentifier& boxID) = 0; + + /** + * \brief Check if scenario contains a box with a deprecated interfacor due to an incomplete update + * \retval true if a box in the scenario has a deprecated interfacor + * \retval false if no box in the scenario contains a deprecated interfacor + */ + virtual bool containsBoxWithDeprecatedInterfacors() const = 0; + + /** + * \return true if the scenario is actually a metabox + */ + virtual bool isMetabox() = 0; + + virtual void getBoxIdentifierList(CIdentifier** listID, size_t* size) const = 0; + virtual void getCommentIdentifierList(CIdentifier** listID, size_t* size) const = 0; + virtual void getMetadataIdentifierList(CIdentifier** listID, size_t* size) const = 0; + virtual void getLinkIdentifierList(CIdentifier** listID, size_t* size) const = 0; + virtual void getLinkIdentifierFromBoxList(const CIdentifier& boxID, CIdentifier** listID, size_t* size) const = 0; + virtual void getLinkIdentifierFromBoxOutputList(const CIdentifier& boxID, size_t outputIdx, CIdentifier** listID, size_t* size) const = 0; + virtual void getLinkIdentifierToBoxList(const CIdentifier& boxID, CIdentifier** listID, size_t* size) const = 0; + virtual void getLinkIdentifierToBoxInputList(const CIdentifier& boxID, size_t inputIdx, CIdentifier** listID, size_t* size) const = 0; + virtual void getOutdatedBoxIdentifierList(CIdentifier** listID, size_t* size) const = 0; + virtual void releaseIdentifierList(CIdentifier* listID) const = 0; + + _IsDerivedFromClass_(IBox, OV_ClassId_Kernel_Scenario_Scenario) +}; +} // namespace Kernel +} // namespace OpenViBE diff --git a/openvibe/include/openvibe/kernel/scenario/ovIScenarioManager.h b/openvibe/include/openvibe/kernel/scenario/ovIScenarioManager.h index e2fc6dc940887ae9be8c89eb7aa8e0eceb190532..46dfd97cf999907725df42b5f314dea430422e45 100644 --- a/openvibe/include/openvibe/kernel/scenario/ovIScenarioManager.h +++ b/openvibe/include/openvibe/kernel/scenario/ovIScenarioManager.h @@ -2,154 +2,152 @@ #include "../ovIKernelObject.h" -namespace OpenViBE +namespace OpenViBE { +class IMemoryBuffer; + +namespace Kernel { +class IScenario; + +/** + * \class IScenarioManager + * \author Yann Renard (IRISA/INRIA) + * \date 2006-10-05 + * \brief The scenario manager + * \ingroup Group_Scenario + * \ingroup Group_Kernel + * + * This manager is responsible to organize and handle + * all the scenarios of the kernel. + */ +class OV_API IScenarioManager : public IKernelObject { - class IMemoryBuffer; - - namespace Kernel - { - class IScenario; - - /** - * \class IScenarioManager - * \author Yann Renard (IRISA/INRIA) - * \date 2006-10-05 - * \brief The scenario manager - * \ingroup Group_Scenario - * \ingroup Group_Kernel - * - * This manager is responsible to organize and handle - * all the scenarios of the kernel. - */ - class OV_API IScenarioManager : public IKernelObject - { - public: - - /** - * \brief Gets next scenario identifier - * \param previousID [in] : The identifier - * for the preceeding scenario - * \return The identifier of the next scenario in case of success. - * \return \c OV_UndefinedIdentifier on error. - * \note Giving \c OV_UndefinedIdentifier as \c previousID - * will cause this function to return the first scenario - * identifier. - */ - virtual CIdentifier getNextScenarioIdentifier(const CIdentifier& previousID) const = 0; - - virtual bool isScenario(const CIdentifier& scenarioID) const = 0; - /** - * \brief Creates a new scenario - * \param scenarioID [out] : the identifier of - * the newly created scenario - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool createScenario(CIdentifier& scenarioID) = 0; - - /** - * @brief Import a scenario from a memory buffer and insert it in the scenario manager - * @param[out] newScenarioID New identifier of the imported scenario - * @param buffer Buffer to import the scenario from - * @param scenarioImporterAlgorithmID The importer algorithm to use - * @retval true In case of success - * @retval false In case of failure - */ - virtual bool importScenario(CIdentifier& newScenarioID, const IMemoryBuffer& buffer, const CIdentifier& scenarioImporterAlgorithmID) = 0; - - /** - * @brief Import a scenario from a file and insert it in the scenario manager - * @param[out] newScenarioID New identifier of the imported scenario - * @param fileName File to import the scenario from - * @param scenarioImporterAlgorithmID The importer algorithm to use - * @retval true In case of success - * @retval false In case of failure - */ - virtual bool importScenarioFromFile(CIdentifier& newScenarioID, const CString& fileName, const CIdentifier& scenarioImporterAlgorithmID) = 0; - - /** - * @brief Export a scenario to a memory buffer - * @param[out] buffer Buffer to be filled with the serialized scenario - * @param scenarioID Scenario to export - * @param scenarioExporterAlgorithmID Exporter to use - * @retval true In case of success - * @retval false In case of failure - */ - virtual bool exportScenario(IMemoryBuffer& buffer, const CIdentifier& scenarioID, const CIdentifier& scenarioExporterAlgorithmID) const = 0; - - /** - * @brief Export a scenario to a file - * @param fileName File to which export the scenario - * @param scenarioID Scenario to export - * @param scenarioExporterAlgorithmID Exporter to use - * @retval true In case of success - * @retval false In case of failure - */ - virtual bool exportScenarioToFile(const CString& fileName, const CIdentifier& scenarioID, const CIdentifier& scenarioExporterAlgorithmID) const = 0; - - /** - * \brief Releases an existing scenario - * \param id [in] : the existing scenario identifier - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool releaseScenario(const CIdentifier& id) = 0; - /** - * \brief Gets details on a specific scenario - * \param id [in] : the scenario identifier which details should be returned - * \return the corresponding scenario reference. - * \warning Calling this function with a bad identifier causes a crash - */ - virtual IScenario& getScenario(const CIdentifier& id) = 0; - - - /** @{ - * @name Scenario Importers and Exporters - * - * Scenario importers and exporters permit the Kernel to load and save scenarios from and to files - * without having the client to explicitly specify the algorithm identifier for export. - * - * Both are represented by a data structure that associates a Context with one or more File Name Extensions, - * each of the Context/Extension pair has then an Algorithm Identifier associated. This enables the kernel - * to use a different importer for different uses. - * - * For example, in authoring mode one does not need to load the complete scenario, just the descriptor components. - * - * Importers and exporters can be registered directly by plugins declaring new algorithms. - */ - - - /** - * @brief Copies all scenario importers and exporters declarations from a scenarioManager to the current one. - * @param scenarioManager The manager to copy the importers from. - */ - virtual void cloneScenarioImportersAndExporters(const IScenarioManager& scenarioManager) = 0; - - virtual bool importScenarioFromFile(CIdentifier& newScenarioID, const CIdentifier& importContext, const CString& fileName) = 0; - - virtual bool registerScenarioImporter(const CIdentifier& importContext, const CString& fileNameExtension, - const CIdentifier& scenarioImporterAlgorithmID) = 0; - - virtual bool unregisterScenarioImporter(const CIdentifier& importContext, const CString& fileNameExtension) = 0; - - virtual CIdentifier getNextScenarioImportContext(const CIdentifier& importContext) const = 0; - virtual CString getNextScenarioImporter(const CIdentifier& importContext, const CString& fileNameExtension) const = 0; - virtual CIdentifier getScenarioImporterAlgorithmIdentifier(const CIdentifier& importContext, const CString& fileNameExtension) const = 0; - - virtual bool exportScenarioToFile(const CIdentifier& exportContext, const CString& fileName, const CIdentifier& scenarioID) = 0; - - virtual bool registerScenarioExporter(const CIdentifier& exportContext, const CString& fileNameExtension, - const CIdentifier& scenarioExporterAlgorithmID) = 0; - - virtual bool unregisterScenarioExporter(const CIdentifier& exportContext, const CString& fileNameExtension) = 0; - - virtual CIdentifier getNextScenarioExportContext(const CIdentifier& exportContext) const = 0; - virtual CString getNextScenarioExporter(const CIdentifier& exportContext, const CString& fileNameExtension) const = 0; - virtual CIdentifier getScenarioExporterAlgorithmIdentifier(const CIdentifier& exportContext, const CString& fileNameExtension) const = 0; - - /** @} */ - - _IsDerivedFromClass_(IKernelObject, OV_ClassId_Kernel_Scenario_ScenarioManager) - }; - } // namespace Kernel -} // namespace OpenViBE +public: + + /** + * \brief Gets next scenario identifier + * \param previousID [in] : The identifier + * for the preceeding scenario + * \return The identifier of the next scenario in case of success. + * \return \c OV_UndefinedIdentifier on error. + * \note Giving \c OV_UndefinedIdentifier as \c previousID + * will cause this function to return the first scenario + * identifier. + */ + virtual CIdentifier getNextScenarioIdentifier(const CIdentifier& previousID) const = 0; + + virtual bool isScenario(const CIdentifier& scenarioID) const = 0; + /** + * \brief Creates a new scenario + * \param scenarioID [out] : the identifier of + * the newly created scenario + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool createScenario(CIdentifier& scenarioID) = 0; + + /** + * @brief Import a scenario from a memory buffer and insert it in the scenario manager + * @param[out] newScenarioID New identifier of the imported scenario + * @param buffer Buffer to import the scenario from + * @param scenarioImporterAlgorithmID The importer algorithm to use + * @retval true In case of success + * @retval false In case of failure + */ + virtual bool importScenario(CIdentifier& newScenarioID, const IMemoryBuffer& buffer, const CIdentifier& scenarioImporterAlgorithmID) = 0; + + /** + * @brief Import a scenario from a file and insert it in the scenario manager + * @param[out] newScenarioID New identifier of the imported scenario + * @param fileName File to import the scenario from + * @param scenarioImporterAlgorithmID The importer algorithm to use + * @retval true In case of success + * @retval false In case of failure + */ + virtual bool importScenarioFromFile(CIdentifier& newScenarioID, const CString& fileName, const CIdentifier& scenarioImporterAlgorithmID) = 0; + + /** + * @brief Export a scenario to a memory buffer + * @param[out] buffer Buffer to be filled with the serialized scenario + * @param scenarioID Scenario to export + * @param scenarioExporterAlgorithmID Exporter to use + * @retval true In case of success + * @retval false In case of failure + */ + virtual bool exportScenario(IMemoryBuffer& buffer, const CIdentifier& scenarioID, const CIdentifier& scenarioExporterAlgorithmID) const = 0; + + /** + * @brief Export a scenario to a file + * @param fileName File to which export the scenario + * @param scenarioID Scenario to export + * @param scenarioExporterAlgorithmID Exporter to use + * @retval true In case of success + * @retval false In case of failure + */ + virtual bool exportScenarioToFile(const CString& fileName, const CIdentifier& scenarioID, const CIdentifier& scenarioExporterAlgorithmID) const = 0; + + /** + * \brief Releases an existing scenario + * \param id [in] : the existing scenario identifier + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool releaseScenario(const CIdentifier& id) = 0; + /** + * \brief Gets details on a specific scenario + * \param id [in] : the scenario identifier which details should be returned + * \return the corresponding scenario reference. + * \warning Calling this function with a bad identifier causes a crash + */ + virtual IScenario& getScenario(const CIdentifier& id) = 0; + + + /** @{ + * @name Scenario Importers and Exporters + * + * Scenario importers and exporters permit the Kernel to load and save scenarios from and to files + * without having the client to explicitly specify the algorithm identifier for export. + * + * Both are represented by a data structure that associates a Context with one or more File Name Extensions, + * each of the Context/Extension pair has then an Algorithm Identifier associated. This enables the kernel + * to use a different importer for different uses. + * + * For example, in authoring mode one does not need to load the complete scenario, just the descriptor components. + * + * Importers and exporters can be registered directly by plugins declaring new algorithms. + */ + + + /** + * @brief Copies all scenario importers and exporters declarations from a scenarioManager to the current one. + * @param scenarioManager The manager to copy the importers from. + */ + virtual void cloneScenarioImportersAndExporters(const IScenarioManager& scenarioManager) = 0; + + virtual bool importScenarioFromFile(CIdentifier& newScenarioID, const CIdentifier& importContext, const CString& fileName) = 0; + + virtual bool registerScenarioImporter(const CIdentifier& importContext, const CString& fileNameExtension, + const CIdentifier& scenarioImporterAlgorithmID) = 0; + + virtual bool unregisterScenarioImporter(const CIdentifier& importContext, const CString& fileNameExtension) = 0; + + virtual CIdentifier getNextScenarioImportContext(const CIdentifier& importContext) const = 0; + virtual CString getNextScenarioImporter(const CIdentifier& importContext, const CString& fileNameExtension) const = 0; + virtual CIdentifier getScenarioImporterAlgorithmIdentifier(const CIdentifier& importContext, const CString& fileNameExtension) const = 0; + + virtual bool exportScenarioToFile(const CIdentifier& exportContext, const CString& fileName, const CIdentifier& scenarioID) = 0; + + virtual bool registerScenarioExporter(const CIdentifier& exportContext, const CString& fileNameExtension, + const CIdentifier& scenarioExporterAlgorithmID) = 0; + + virtual bool unregisterScenarioExporter(const CIdentifier& exportContext, const CString& fileNameExtension) = 0; + + virtual CIdentifier getNextScenarioExportContext(const CIdentifier& exportContext) const = 0; + virtual CString getNextScenarioExporter(const CIdentifier& exportContext, const CString& fileNameExtension) const = 0; + virtual CIdentifier getScenarioExporterAlgorithmIdentifier(const CIdentifier& exportContext, const CString& fileNameExtension) const = 0; + + /** @} */ + + _IsDerivedFromClass_(IKernelObject, OV_ClassId_Kernel_Scenario_ScenarioManager) +}; +} // namespace Kernel +} // namespace OpenViBE diff --git a/openvibe/include/openvibe/kernel/server/ovIServerExtensionContext.h b/openvibe/include/openvibe/kernel/server/ovIServerExtensionContext.h index d0461abc16a00f1b4402d2bfc76cdf0f4405501f..9c61de65360f24ce2fc23a72b25f4cc1727eee51 100644 --- a/openvibe/include/openvibe/kernel/server/ovIServerExtensionContext.h +++ b/openvibe/include/openvibe/kernel/server/ovIServerExtensionContext.h @@ -3,29 +3,27 @@ #include "../ovIKernelObject.h" #include "../log/ovILogManager.h" -namespace OpenViBE +namespace OpenViBE { +namespace Kernel { +/** + * \class IServerExtensionContext + * \author Jozef Legeny (Inria) + * \date 2013-06-12 + * \brief Static context of a Server Extension object + * \ingroup Group_Server + * \ingroup Group_Kernel + * \ingroup Group_Extend + * \sa Plugins::IServerExtension + */ +class OV_API IServerExtensionContext : public IKernelObject { - namespace Kernel - { - /** - * \class IServerExtensionContext - * \author Jozef Legeny (Inria) - * \date 2013-06-12 - * \brief Static context of a Server Extension object - * \ingroup Group_Server - * \ingroup Group_Kernel - * \ingroup Group_Extend - * \sa Plugins::IServerExtension - */ - class OV_API IServerExtensionContext : public IKernelObject - { - public: +public: - /** - * \brief Gets a reference on the current log manager - * \return a reference on the current log manager - */ - virtual ILogManager& getLogManager() = 0; - }; - } // namespace Kernel -} // namespace OpenViBE + /** + * \brief Gets a reference on the current log manager + * \return a reference on the current log manager + */ + virtual ILogManager& getLogManager() = 0; +}; +} // namespace Kernel +} // namespace OpenViBE diff --git a/openvibe/include/openvibe/kernel/server/ovIServerExtensionDynamicContext.h b/openvibe/include/openvibe/kernel/server/ovIServerExtensionDynamicContext.h index f0fb1b1112b864ef0cb9f9546a1173cce9f6467c..62b3ffd5e53371073b20c65f6b63c1dfc8e98159 100644 --- a/openvibe/include/openvibe/kernel/server/ovIServerExtensionDynamicContext.h +++ b/openvibe/include/openvibe/kernel/server/ovIServerExtensionDynamicContext.h @@ -2,37 +2,35 @@ #include "../ovIKernelObject.h" -namespace OpenViBE -{ - class IStimulationSet; +namespace OpenViBE { +class IStimulationSet; - namespace Kernel - { +namespace Kernel { - /** - * \class IServerExtensionDynamicContext - * \author Jozef Legeny (Inria) - * \date 2013-06-12 - * \brief Dynamic context of a Server Extension object - * \ingroup Group_Server - * \ingroup Group_Kernel - * \ingroup Group_Extend - * - * This class contains accessors to data structures made available by - * the driver running in the Acquisition Server during the acquisition. - * - * \sa Plugins::IServerExtension - */ +/** + * \class IServerExtensionDynamicContext + * \author Jozef Legeny (Inria) + * \date 2013-06-12 + * \brief Dynamic context of a Server Extension object + * \ingroup Group_Server + * \ingroup Group_Kernel + * \ingroup Group_Extend + * + * This class contains accessors to data structures made available by + * the driver running in the Acquisition Server during the acquisition. + * + * \sa Plugins::IServerExtension + */ - class OV_API IServerExtensionDynamicContext : public IKernelObject - { - public: - virtual size_t getChannelCount() = 0; - virtual size_t getSampleCountPerSentBlock() = 0; - virtual double* getBuffer() = 0; - virtual uint64_t getStimulationSetStartTime() = 0; - virtual uint64_t getStimulationSetEndTime() = 0; - virtual IStimulationSet& getStimulationSet() = 0; - }; - } // namespace Kernel -} // namespace OpenViBE +class OV_API IServerExtensionDynamicContext : public IKernelObject +{ +public: + virtual size_t getChannelCount() = 0; + virtual size_t getSampleCountPerSentBlock() = 0; + virtual double* getBuffer() = 0; + virtual uint64_t getStimulationSetStartTime() = 0; + virtual uint64_t getStimulationSetEndTime() = 0; + virtual IStimulationSet& getStimulationSet() = 0; +}; +} // namespace Kernel +} // namespace OpenViBE diff --git a/openvibe/include/openvibe/kernel/server/ovIServerExtensionProto.h b/openvibe/include/openvibe/kernel/server/ovIServerExtensionProto.h index f43d60cfab697ae1056351ba89e2f15534919ed1..33d2d82fc511770c0b706d008b7d351e695b201c 100644 --- a/openvibe/include/openvibe/kernel/server/ovIServerExtensionProto.h +++ b/openvibe/include/openvibe/kernel/server/ovIServerExtensionProto.h @@ -2,26 +2,24 @@ #include "../ovIConfigurable.h" -namespace OpenViBE -{ - namespace Kernel - { - /** - * \class IServerExtensionProto - * \brief Prototype interface for a server extension - * \author Jozef Legeny (Inria) - * \ingroup Group_Server - * \ingroup Group_Kernel - * \ingroup Group_Extend - * \sa Plugins::IServerExtension - * \sa Plugins::IServerExtensionDesc - */ +namespace OpenViBE { +namespace Kernel { +/** + * \class IServerExtensionProto + * \brief Prototype interface for a server extension + * \author Jozef Legeny (Inria) + * \ingroup Group_Server + * \ingroup Group_Kernel + * \ingroup Group_Extend + * \sa Plugins::IServerExtension + * \sa Plugins::IServerExtensionDesc + */ - class OV_API IServerExtensionProto : public IKernelObject - { - public: - virtual size_t addSetting(const CString& name, const CIdentifier& typeID, const CString& value) = 0; - _IsDerivedFromClass_(IKernelObject, OV_ClassId_Kernel_Server_ServerExtensionProto) - }; - } // namespace Kernel -} // namespace OpenViBE +class OV_API IServerExtensionProto : public IKernelObject +{ +public: + virtual size_t addSetting(const CString& name, const CIdentifier& typeID, const CString& value) = 0; + _IsDerivedFromClass_(IKernelObject, OV_ClassId_Kernel_Server_ServerExtensionProto) +}; +} // namespace Kernel +} // namespace OpenViBE diff --git a/openvibe/include/openvibe/metaboxes/ovIMetaboxObjectDesc.h b/openvibe/include/openvibe/metaboxes/ovIMetaboxObjectDesc.h index 8ecddeae9304afe1e282fba12e4408f20a903307..3cc501876980e0828e4dd0fa17e107b0935f574a 100755 --- a/openvibe/include/openvibe/metaboxes/ovIMetaboxObjectDesc.h +++ b/openvibe/include/openvibe/metaboxes/ovIMetaboxObjectDesc.h @@ -2,16 +2,14 @@ #include "../plugins/ovIBoxAlgorithmDesc.h" -namespace OpenViBE +namespace OpenViBE { +namespace Metabox { +class OV_API IMetaboxObjectDesc : virtual public Plugins::IBoxAlgorithmDesc { - namespace Metabox - { - class OV_API IMetaboxObjectDesc : virtual public Plugins::IBoxAlgorithmDesc - { - public: - virtual CString getMetaboxDescriptor() const = 0; +public: + virtual CString getMetaboxDescriptor() const = 0; - _IsDerivedFromClass_(Plugins::IBoxAlgorithmDesc, OV_ClassId_Metaboxes_MetaboxObjectDesc) - }; - } // namespace Metabox -} // namespace OpenViBE + _IsDerivedFromClass_(Plugins::IBoxAlgorithmDesc, OV_ClassId_Metaboxes_MetaboxObjectDesc) +}; +} // namespace Metabox +} // namespace OpenViBE diff --git a/openvibe/include/openvibe/ovAssert.h b/openvibe/include/openvibe/ovAssert.h index f40e22ebcda171c05e7fd99d4c4a4baa024e307f..494e08330a430cf5386dcb9b9055ea76d3b07d1a 100644 --- a/openvibe/include/openvibe/ovAssert.h +++ b/openvibe/include/openvibe/ovAssert.h @@ -61,7 +61,7 @@ inline std::ostream& operator<<(std::ostream& os, const CIdentifier id) os << id.str(); return os; } -} // namespace OpenViBE +} // namespace OpenViBE /** * \def OV_WARNING_LOG(message, logManager) @@ -111,9 +111,9 @@ inline std::ostream& operator<<(std::ostream& os, const CIdentifier id) #define OV_WARNING_UNLESS_K(expression, message) OV_WARNING_UNLESS(expression, message, this->getLogManager()) #if defined OV_DISPLAY_ERROR_LOCATION -#define OV_ERROR_LOG_LOCATION(file, line) ", {Error location} : {" << file << "::" << line << "}" +# define OV_ERROR_LOG_LOCATION(file, line) ", {Error location} : {" << file << "::" << line << "}" #else -#define OV_ERROR_LOG_LOCATION(file, line) "" +# define OV_ERROR_LOG_LOCATION(file, line) "" #endif /** * \def OV_ERROR_LOG(description, type, file, line, logManager) @@ -157,12 +157,7 @@ do { \ * instead. */ #define OV_ERROR_UNLESS(expression, description, type, returnValue, errorManager, logManager) \ -do { \ - if (!(expression)) \ - { \ - OV_ERROR(description, type, returnValue, errorManager, logManager); \ - } \ -} while(0) +do { if (!(expression)) { OV_ERROR(description, type, returnValue, errorManager, logManager); } } while(0) /** * \def OV_ERROR_K(description, type, returnValue) diff --git a/openvibe/include/openvibe/ovCIdentifier.h b/openvibe/include/openvibe/ovCIdentifier.h index ac9ecda39c09097e4161733d2bb10ee04689645a..68567f85323556c03f948f0b772a52f89e2d4b39 100644 --- a/openvibe/include/openvibe/ovCIdentifier.h +++ b/openvibe/include/openvibe/ovCIdentifier.h @@ -209,4 +209,4 @@ protected: uint64_t m_id = 0; ///< the 64 bit identifier value }; -} // namespace OpenViBE +} // namespace OpenViBE diff --git a/openvibe/include/openvibe/ovCKernelLoader.h b/openvibe/include/openvibe/ovCKernelLoader.h index 3843d85c9f55f67efe353fdbead4cc7255eacfe2..652e17eadfb6d0e248d3691d72e4d82ad87f8c38 100644 --- a/openvibe/include/openvibe/ovCKernelLoader.h +++ b/openvibe/include/openvibe/ovCKernelLoader.h @@ -2,24 +2,23 @@ #include "ovIKernelLoader.h" -namespace OpenViBE +namespace OpenViBE { +class OV_API CKernelLoader final : public IKernelLoader { - class OV_API CKernelLoader final : public IKernelLoader - { - public: +public: - CKernelLoader(); - ~CKernelLoader() override; - bool load(const CString& filename, CString* error = nullptr) override; - bool unload(CString* error = nullptr) override; - bool initialize() override; - bool getKernelDesc(Kernel::IKernelDesc*& desc) override; - bool uninitialize() override; + CKernelLoader(); + ~CKernelLoader() override; + bool load(const CString& filename, CString* error = nullptr) override; + bool unload(CString* error = nullptr) override; + bool initialize() override; + bool getKernelDesc(Kernel::IKernelDesc*& desc) override; + bool uninitialize() override; - _IsDerivedFromClass_Final_(IKernelLoader, OV_ClassId_KernelLoaderBridge) + _IsDerivedFromClass_Final_(IKernelLoader, OV_ClassId_KernelLoaderBridge) - private: +private: - IKernelLoader* m_impl = nullptr; ///< Internal implementation - }; -} // namespace OpenViBE + IKernelLoader* m_impl = nullptr; ///< Internal implementation +}; +} // namespace OpenViBE diff --git a/openvibe/include/openvibe/ovCMatrix.h b/openvibe/include/openvibe/ovCMatrix.h index fecadf71bbeaca1ab9cdaff33418bc585c87bf83..5c142400788b3666930f9c571d634516cd6ca7c2 100644 --- a/openvibe/include/openvibe/ovCMatrix.h +++ b/openvibe/include/openvibe/ovCMatrix.h @@ -2,61 +2,60 @@ #include "ovIMatrix.h" -namespace OpenViBE +namespace OpenViBE { +/** + * \class CMatrix + * \author Yann Renard (INRIA/IRISA) + * \date 2007-11-21 + * \brief Basic standalone OpenViBE matrix implementation + * \ingroup Group_Base + * + * This class offers a basic standalone impementation of the IMatrix + * interface. This class can be directly instanciated and used. + * + * Instances of this class use an internal implementation of the IMatrix + * interface and redirect their calls to this implementation. + */ +class OV_API CMatrix final : public IMatrix { +public: + + /** \name Constructors */ + //@{ + /** - * \class CMatrix - * \author Yann Renard (INRIA/IRISA) - * \date 2007-11-21 - * \brief Basic standalone OpenViBE matrix implementation - * \ingroup Group_Base + * \brief Default constructor * - * This class offers a basic standalone impementation of the IMatrix - * interface. This class can be directly instanciated and used. + * This constructor builds the internal implementation of this matrix. + */ + CMatrix(); + + + CMatrix(const CMatrix& other); + + CMatrix& operator=(const CMatrix& other); + /** + * \brief Destructor * - * Instances of this class use an internal implementation of the IMatrix - * interface and redirect their calls to this implementation. + * The internal implementation is released. */ - class OV_API CMatrix final : public IMatrix - { - public: - - /** \name Constructors */ - //@{ - - /** - * \brief Default constructor - * - * This constructor builds the internal implementation of this matrix. - */ - CMatrix(); - - - CMatrix(const CMatrix& other); - - CMatrix& operator=(const CMatrix& other); - /** - * \brief Destructor - * - * The internal implementation is released. - */ - ~CMatrix() override; - - //@} - size_t getDimensionCount() const override; - size_t getDimensionSize(const size_t index) const override; - const char* getDimensionLabel(const size_t index1, const size_t index2) const override; - const double* getBuffer() const override; - size_t getBufferElementCount() const override; - bool setDimensionCount(const size_t count) override; - bool setDimensionSize(const size_t index, const size_t size) override; - bool setDimensionLabel(const size_t index1, const size_t index2, const char* label) override; - double* getBuffer() override; - - _IsDerivedFromClass_Final_(IMatrix, OV_ClassId_MatrixBridge) - - private: - - IMatrix* m_impl = nullptr; ///< Internal implementation - }; -} // namespace OpenViBE + ~CMatrix() override; + + //@} + size_t getDimensionCount() const override; + size_t getDimensionSize(const size_t index) const override; + const char* getDimensionLabel(const size_t index1, const size_t index2) const override; + const double* getBuffer() const override; + size_t getBufferElementCount() const override; + bool setDimensionCount(const size_t count) override; + bool setDimensionSize(const size_t index, const size_t size) override; + bool setDimensionLabel(const size_t index1, const size_t index2, const char* label) override; + double* getBuffer() override; + + _IsDerivedFromClass_Final_(IMatrix, OV_ClassId_MatrixBridge) + +private: + + IMatrix* m_impl = nullptr; ///< Internal implementation +}; +} // namespace OpenViBE diff --git a/openvibe/include/openvibe/ovCMemoryBuffer.h b/openvibe/include/openvibe/ovCMemoryBuffer.h index 3fb324fc1d792083d92c9a2b6ee905f7cfddc38e..7efa14b2d786600bf3d35846b2b06fe0d120fc86 100644 --- a/openvibe/include/openvibe/ovCMemoryBuffer.h +++ b/openvibe/include/openvibe/ovCMemoryBuffer.h @@ -2,69 +2,68 @@ #include "ovIMemoryBuffer.h" -namespace OpenViBE +namespace OpenViBE { +/** + * \class CMemoryBuffer + * \author Yann Renard (INRIA/IRISA) + * \date 2007-11-21 + * \brief Basic standalone OpenViBE memory buffer implementation + * \ingroup Group_Base + * + * This class offers a basic standalone impementation of the IMemoryBuffer + * interface. This class can be directly instanciated and used. + * + * Instances of this class use an internal implementation of the IMemoryBuffer + * interface and redirect their calls to this implementation. + */ + +class OV_API CMemoryBuffer : public IMemoryBuffer { +public: + + /** \name Constructors */ + //@{ + /** - * \class CMemoryBuffer - * \author Yann Renard (INRIA/IRISA) - * \date 2007-11-21 - * \brief Basic standalone OpenViBE memory buffer implementation - * \ingroup Group_Base + * \brief Default constructor * - * This class offers a basic standalone impementation of the IMemoryBuffer - * interface. This class can be directly instanciated and used. + * This constructor builds the internal implementation of this memory buffer. + */ + CMemoryBuffer(); + /** + * \brief Copy constructor * - * Instances of this class use an internal implementation of the IMemoryBuffer - * interface and redirect their calls to this implementation. + * This constructor builds the internal implementation of this memory buffer and initializes it + * with the actual parameter of the constructor as a copy. */ + CMemoryBuffer(const IMemoryBuffer& buffer); + /** + * \brief Copy constructor + * + * This constructor builds the internal implementation of this memory buffer and initializes it + * with the actual parameter of the constructor as a copy. + */ + CMemoryBuffer(const uint8_t* buffer, size_t size); + /** + * \brief Destructor + * + * The internal implementation is released. + */ + ~CMemoryBuffer() override; - class OV_API CMemoryBuffer : public IMemoryBuffer - { - public: - - /** \name Constructors */ - //@{ - - /** - * \brief Default constructor - * - * This constructor builds the internal implementation of this memory buffer. - */ - CMemoryBuffer(); - /** - * \brief Copy constructor - * - * This constructor builds the internal implementation of this memory buffer and initializes it - * with the actual parameter of the constructor as a copy. - */ - CMemoryBuffer(const IMemoryBuffer& buffer); - /** - * \brief Copy constructor - * - * This constructor builds the internal implementation of this memory buffer and initializes it - * with the actual parameter of the constructor as a copy. - */ - CMemoryBuffer(const uint8_t* buffer, size_t size); - /** - * \brief Destructor - * - * The internal implementation is released. - */ - ~CMemoryBuffer() override; - - //@} - bool reserve(const size_t size) override; - bool setSize(const size_t size, const bool discard) override; - size_t getSize() const override; - uint8_t* getDirectPointer() override; - const uint8_t* getDirectPointer() const override; - bool append(const uint8_t* buffer, const size_t size) override; - bool append(const IMemoryBuffer& buffer) override; + //@} + bool reserve(const size_t size) override; + bool setSize(const size_t size, const bool discard) override; + size_t getSize() const override; + uint8_t* getDirectPointer() override; + const uint8_t* getDirectPointer() const override; + bool append(const uint8_t* buffer, const size_t size) override; + bool append(const IMemoryBuffer& buffer) override; - _IsDerivedFromClass_Final_(IMemoryBuffer, OV_ClassId_MemoryBufferBridge) + _IsDerivedFromClass_Final_(IMemoryBuffer, OV_ClassId_MemoryBufferBridge) - protected: +protected: - IMemoryBuffer* m_impl = nullptr; ///< Internal implementation - }; -} // namespace OpenViBE + IMemoryBuffer* m_impl = nullptr; ///< Internal implementation +}; +} // namespace OpenViBE diff --git a/openvibe/include/openvibe/ovCNameValuePairList.h b/openvibe/include/openvibe/ovCNameValuePairList.h index 20d7f58a7d52ee948468db3be419569beb214090..c127b629f41b6d383b5e4ad254e177d84ea8812b 100644 --- a/openvibe/include/openvibe/ovCNameValuePairList.h +++ b/openvibe/include/openvibe/ovCNameValuePairList.h @@ -136,4 +136,4 @@ protected: CNameValuePairListImpl* m_impl = nullptr; ///< The list implementation }; -} // namespace OpenViBE +} // namespace OpenViBE diff --git a/openvibe/include/openvibe/ovCObservable.h b/openvibe/include/openvibe/ovCObservable.h index b71a10a4df52e25235602cf12679041ec1169530..feca38d9accea35db149a9a2d6fa8a43c43b7d1b 100644 --- a/openvibe/include/openvibe/ovCObservable.h +++ b/openvibe/include/openvibe/ovCObservable.h @@ -3,69 +3,68 @@ #include "ovIObserver.h" #include "ov_defines.h" -namespace OpenViBE +namespace OpenViBE { +class IObserver; + +/** +* \class CObservable +* \author Guillaume Serrière (Inria/Loria) +* \date 2014-11-7 +* \brief OpenViBE Observable class +* +* This class furnished all mecanisms to handle the Observable part of the Observer/Observable +* pattern implementation of OpenViBE. +*/ +class OV_API CObservable { - class IObserver; +public: + CObservable(); + virtual ~CObservable(); /** - * \class CObservable - * \author Guillaume Serrière (Inria/Loria) - * \date 2014-11-7 - * \brief OpenViBE Observable class - * - * This class furnished all mecanisms to handle the Observable part of the Observer/Observable - * pattern implementation of OpenViBE. - */ - class OV_API CObservable - { - public: - CObservable(); - virtual ~CObservable(); - - /** - * \brief Add the observer give in parameter in the list of observers of the object. - * \param o [in] : the observer to add - * \note A same observer can be add multiple time. - */ - virtual void addObserver(IObserver* o); + * \brief Add the observer give in parameter in the list of observers of the object. + * \param o [in] : the observer to add + * \note A same observer can be add multiple time. + */ + virtual void addObserver(IObserver* o); - /** - * \brief Remove the observer give in parameter from the list of observers of the object. Only the first - * occurence of the observer will be remove from the list. - * \param o [in] : the observer to remove - */ - virtual void deleteObserver(IObserver* o); + /** + * \brief Remove the observer give in parameter from the list of observers of the object. Only the first + * occurence of the observer will be remove from the list. + * \param o [in] : the observer to remove + */ + virtual void deleteObserver(IObserver* o); - protected: - /** - * \brief This function is used to indicate when the notification need to reach the observers. If this function - * is not called before notifyObserver, the notification will be ignore. - * - * \note The "changed" state will be reverted after each call to clearChanged and notifyObservers. - */ - virtual void setChanged() { m_hasChanged = true; } +protected: + /** + * \brief This function is used to indicate when the notification need to reach the observers. If this function + * is not called before notifyObserver, the notification will be ignore. + * + * \note The "changed" state will be reverted after each call to clearChanged and notifyObservers. + */ + virtual void setChanged() { m_hasChanged = true; } - /** - * \brief Revert the effect of setChanged. - */ - virtual void clearChanged() { m_hasChanged = false; } + /** + * \brief Revert the effect of setChanged. + */ + virtual void clearChanged() { m_hasChanged = false; } - /** - * \brief Indicate if some change have been made. - * \return \e true if setChanged have been called this the last clearChanged/notifyObservers call. - * \return \e false in other case. - */ - virtual bool hasChanged() { return m_hasChanged; } + /** + * \brief Indicate if some change have been made. + * \return \e true if setChanged have been called this the last clearChanged/notifyObservers call. + * \return \e false in other case. + */ + virtual bool hasChanged() { return m_hasChanged; } - /** - * \brief Notify all registered observers. - * \param data [in] : a pointer to data that will be send to observers. - */ - virtual void notifyObservers(void* data = nullptr); + /** + * \brief Notify all registered observers. + * \param data [in] : a pointer to data that will be send to observers. + */ + virtual void notifyObservers(void* data = nullptr); - private: - struct SObserverList; - SObserverList* m_observers = nullptr; - bool m_hasChanged = false; - }; -} // namespace OpenViBE +private: + struct SObserverList; + SObserverList* m_observers = nullptr; + bool m_hasChanged = false; +}; +} // namespace OpenViBE diff --git a/openvibe/include/openvibe/ovCStimulationSet.h b/openvibe/include/openvibe/ovCStimulationSet.h index e4a1c22a1ce3bbff521f49842ea98c3f4ac0a389..0b9875e5d3e7bca56f0969b526fe981244494aca 100644 --- a/openvibe/include/openvibe/ovCStimulationSet.h +++ b/openvibe/include/openvibe/ovCStimulationSet.h @@ -2,68 +2,67 @@ #include "ovIStimulationSet.h" -namespace OpenViBE +namespace OpenViBE { +/** + * \class CStimulationSet + * \author Yann Renard (INRIA/IRISA) + * \date 2007-11-21 + * \brief Basic standalone OpenViBE stimulation set implementation + * \ingroup Group_Base + * + * This class offers a basic standalone impementation of the IStimulationSet + * interface. This class can be directly instanciated and used. + * + * Instances of this class use an internal implementation of the IStimulationSet + * interface and redirect their calls to this implementation. + */ +class OV_API CStimulationSet final : public IStimulationSet { +public: + + /** \name Constructors */ + //@{ + /** - * \class CStimulationSet - * \author Yann Renard (INRIA/IRISA) - * \date 2007-11-21 - * \brief Basic standalone OpenViBE stimulation set implementation - * \ingroup Group_Base + * \brief Default constructor * - * This class offers a basic standalone impementation of the IStimulationSet - * interface. This class can be directly instanciated and used. + * This constructor builds the internal implementation of this stimulation set. + */ + CStimulationSet(); + /** + * \brief Destructor * - * Instances of this class use an internal implementation of the IStimulationSet - * interface and redirect their calls to this implementation. + * The internal implementation is released. */ - class OV_API CStimulationSet final : public IStimulationSet - { - public: + ~CStimulationSet() override { delete m_stimSet; } - /** \name Constructors */ - //@{ + //@} + void clear() override { m_stimSet->clear(); } + size_t getStimulationCount() const override { return m_stimSet->getStimulationCount(); } + uint64_t getStimulationIdentifier(const size_t index) const override { return m_stimSet->getStimulationIdentifier(index); } + uint64_t getStimulationDate(const size_t index) const override { return m_stimSet->getStimulationDate(index); } + uint64_t getStimulationDuration(const size_t index) const override { return m_stimSet->getStimulationDuration(index); } + bool setStimulationCount(const size_t n) override { return m_stimSet->setStimulationCount(n); } + bool setStimulationIdentifier(const size_t index, const uint64_t id) override { return m_stimSet->setStimulationIdentifier(index, id); } + bool setStimulationDate(const size_t index, const uint64_t date) override { return m_stimSet->setStimulationDate(index, date); } + bool setStimulationDuration(const size_t index, const uint64_t duration) override { return m_stimSet->setStimulationDuration(index, duration); } - /** - * \brief Default constructor - * - * This constructor builds the internal implementation of this stimulation set. - */ - CStimulationSet(); - /** - * \brief Destructor - * - * The internal implementation is released. - */ - ~CStimulationSet() override { delete m_stimSet; } - - //@} - void clear() override { m_stimSet->clear(); } - size_t getStimulationCount() const override { return m_stimSet->getStimulationCount(); } - uint64_t getStimulationIdentifier(const size_t index) const override { return m_stimSet->getStimulationIdentifier(index); } - uint64_t getStimulationDate(const size_t index) const override { return m_stimSet->getStimulationDate(index); } - uint64_t getStimulationDuration(const size_t index) const override { return m_stimSet->getStimulationDuration(index); } - bool setStimulationCount(const size_t n) override { return m_stimSet->setStimulationCount(n); } - bool setStimulationIdentifier(const size_t index, const uint64_t id) override { return m_stimSet->setStimulationIdentifier(index, id); } - bool setStimulationDate(const size_t index, const uint64_t date) override { return m_stimSet->setStimulationDate(index, date); } - bool setStimulationDuration(const size_t index, const uint64_t duration) override { return m_stimSet->setStimulationDuration(index, duration); } - - size_t appendStimulation(const uint64_t id, const uint64_t date, const uint64_t duration) override - { - return m_stimSet->appendStimulation(id, date, duration); - } + size_t appendStimulation(const uint64_t id, const uint64_t date, const uint64_t duration) override + { + return m_stimSet->appendStimulation(id, date, duration); + } - size_t insertStimulation(const size_t index, const uint64_t id, const uint64_t date, const uint64_t duration) override - { - return m_stimSet->insertStimulation(index, id, date, duration); - } + size_t insertStimulation(const size_t index, const uint64_t id, const uint64_t date, const uint64_t duration) override + { + return m_stimSet->insertStimulation(index, id, date, duration); + } - bool removeStimulation(const size_t index) override { return m_stimSet->removeStimulation(index); } + bool removeStimulation(const size_t index) override { return m_stimSet->removeStimulation(index); } - _IsDerivedFromClass_Final_(IStimulationSet, OV_ClassId_StimulationSetBridge) + _IsDerivedFromClass_Final_(IStimulationSet, OV_ClassId_StimulationSetBridge) - private: +private: - IStimulationSet* m_stimSet = nullptr; ///< Internal implementation - }; -} // namespace OpenViBE + IStimulationSet* m_stimSet = nullptr; ///< Internal implementation +}; +} // namespace OpenViBE diff --git a/openvibe/include/openvibe/ovCString.h b/openvibe/include/openvibe/ovCString.h index 89b7c2df6f051ef382a03d1204e504feea9a5c97..0a9f697f6fd0c1a0c11d62b1e6556e9098eca963 100755 --- a/openvibe/include/openvibe/ovCString.h +++ b/openvibe/include/openvibe/ovCString.h @@ -152,4 +152,4 @@ protected: SStringImpl* m_impl = nullptr; ///< The string implementation }; -} // namespace OpenViBE +} // namespace OpenViBE diff --git a/openvibe/include/openvibe/ovExceptionHandler.h b/openvibe/include/openvibe/ovExceptionHandler.h index 9dd36e3e4e09f7dd8ddc3b9ab339bb692b9eface..698afa1cd61ffa1867631238e0aa7079fb5fbd50 100644 --- a/openvibe/include/openvibe/ovExceptionHandler.h +++ b/openvibe/include/openvibe/ovExceptionHandler.h @@ -25,38 +25,36 @@ #include <functional> #include <stdexcept> -namespace OpenViBE +namespace OpenViBE { +using ExceptionHandlerType = std::function<void(const std::exception&)>; + +/** + * \brief Invokes code and potentially translates exceptions to boolean + * + * \tparam TCallback callable type (e.g. functor) with TCallback() returning boolean + * + * \param callable code that must be guarded against exceptions + * \param handler callback that handles the exception + * \return false either if callable() returns false or an exception + * occurs, true otherwise + * + * \details This method is a specific exception-to-boolean translation + * method. If an exception is caught, it is handled by calling + * the provided exception handler. + */ +template <typename TCallback, typename std::enable_if<std::is_same<bool, typename std::result_of<TCallback()>::type>::value>::type* = nullptr> +bool translateException(TCallback&& callable, const ExceptionHandlerType& handler) { - using ExceptionHandlerType = std::function<void(const std::exception&)>; - - /** - * \brief Invokes code and potentially translates exceptions to boolean - * - * \tparam TCallback callable type (e.g. functor) with TCallback() returning boolean - * - * \param callable code that must be guarded against exceptions - * \param handler callback that handles the exception - * \return false either if callable() returns false or an exception - * occurs, true otherwise - * - * \details This method is a specific exception-to-boolean translation - * method. If an exception is caught, it is handled by calling - * the provided exception handler. - */ - template <typename TCallback, - typename std::enable_if<std::is_same<bool, typename std::result_of<TCallback()>::type>::value>::type* = nullptr> - bool translateException(TCallback&& callable, const ExceptionHandlerType& handler) + try { return callable(); } + catch (const std::exception& exception) + { + handler(exception); + return false; + } + catch (...) { - try { return callable(); } - catch (const std::exception& exception) - { - handler(exception); - return false; - } - catch (...) - { - handler(std::runtime_error("unknown exception")); - return false; - } + handler(std::runtime_error("unknown exception")); + return false; } -} // namespace OpenViBE +} +} // namespace OpenViBE diff --git a/openvibe/include/openvibe/ovIKernelLoader.h b/openvibe/include/openvibe/ovIKernelLoader.h index c395e1422a3b59197d7d149d253be66a370b4d79..b7c1d416b9456aa8cc837e86df292c5ba8fd01ed 100644 --- a/openvibe/include/openvibe/ovIKernelLoader.h +++ b/openvibe/include/openvibe/ovIKernelLoader.h @@ -2,75 +2,73 @@ #include "ovIObject.h" -namespace OpenViBE +namespace OpenViBE { +namespace Kernel { +class IKernelDesc; +} // namespace Kernel + +/** + * \class IKernelLoader + * \author Yann Renard (INRIA/IRISA) + * \date 2006-09-26 + * \brief This class allows an OpenViBE application to load a kernel module. + * + * This class allows an OpenViBE application to load a kernel module. + * The application should first load the DLL/so file and initialize it. + * Then it is able to get a kernel descriptor and to build its own kernel + * to use. The kernel DLL/so file should be freed thanks to the unintialization + * and unload methods. + * + * \sa Kernel::IKernel + * \sa Kernel::IKernelDesc + * + */ +class OV_API IKernelLoader : public IObject { - namespace Kernel - { - class IKernelDesc; - } // namespace Kernel +public: /** - * \class IKernelLoader - * \author Yann Renard (INRIA/IRISA) - * \date 2006-09-26 - * \brief This class allows an OpenViBE application to load a kernel module. - * - * This class allows an OpenViBE application to load a kernel module. - * The application should first load the DLL/so file and initialize it. - * Then it is able to get a kernel descriptor and to build its own kernel - * to use. The kernel DLL/so file should be freed thanks to the unintialization - * and unload methods. - * - * \sa Kernel::IKernel - * \sa Kernel::IKernelDesc + * \brief Loads a kernel DLL/so file + * \param filename [in] : the filename to load + * \param error [out] : an optional error string to get when loading fails + * \return \e true on success. + * \return \e false on error. + */ + virtual bool load(const CString& filename, CString* error = nullptr) = 0; + /** + * \brief Unloads a loaded kernel DLL/so file + * \return \e true on success. + * \return \e false on error. + * \warning \c load must have been called successfully before calling \c unload + */ + virtual bool unload(CString* error = nullptr) = 0; + /** + * \brief Requests the kernel DLL/so file to self initialize + * \return \e true on success. + * \return \e false on error. + * \warning \c load must have been called successfully before calling \c initialize * + * Calling this function results in calling the \c onInitialize global function of + * the kernel DLL/so file. See section \ref Doc_CreatingNewKernel to get a full description + * of how a kernel is loaded / used. */ - class OV_API IKernelLoader : public IObject - { - public: - - /** - * \brief Loads a kernel DLL/so file - * \param filename [in] : the filename to load - * \param error [out] : an optional error string to get when loading fails - * \return \e true on success. - * \return \e false on error. - */ - virtual bool load(const CString& filename, CString* error = nullptr) = 0; - /** - * \brief Unloads a loaded kernel DLL/so file - * \return \e true on success. - * \return \e false on error. - * \warning \c load must have been called successfully before calling \c unload - */ - virtual bool unload(CString* error = nullptr) = 0; - /** - * \brief Requests the kernel DLL/so file to self initialize - * \return \e true on success. - * \return \e false on error. - * \warning \c load must have been called successfully before calling \c initialize - * - * Calling this function results in calling the \c onInitialize global function of - * the kernel DLL/so file. See section \ref Doc_CreatingNewKernel to get a full description - * of how a kernel is loaded / used. - */ - virtual bool initialize() = 0; - /** - * \brief Gets the kernel description of the loaded kernel DLL/so file - * \param desc [out] : a pointer to the kernel description - * \return \e true on success. - * \return \e false on error. - * \warning both \c load and \c initialize must have been called successfully before calling \c getKernelDesc - */ - virtual bool getKernelDesc(Kernel::IKernelDesc*& desc) = 0; - /** - * \brief Uninitializes a loaded and initialized kernel DLL/so file - * \return \e true on success. - * \return \e false on error. - * \warning both \c load and \c initialize must have been called successfully before calling \c getKernelDesc - */ - virtual bool uninitialize() = 0; + virtual bool initialize() = 0; + /** + * \brief Gets the kernel description of the loaded kernel DLL/so file + * \param desc [out] : a pointer to the kernel description + * \return \e true on success. + * \return \e false on error. + * \warning both \c load and \c initialize must have been called successfully before calling \c getKernelDesc + */ + virtual bool getKernelDesc(Kernel::IKernelDesc*& desc) = 0; + /** + * \brief Uninitializes a loaded and initialized kernel DLL/so file + * \return \e true on success. + * \return \e false on error. + * \warning both \c load and \c initialize must have been called successfully before calling \c getKernelDesc + */ + virtual bool uninitialize() = 0; - _IsDerivedFromClass_(IObject, OV_ClassId_KernelLoader) - }; -} // namespace OpenViBE + _IsDerivedFromClass_(IObject, OV_ClassId_KernelLoader) +}; +} // namespace OpenViBE diff --git a/openvibe/include/openvibe/ovIMatrix.h b/openvibe/include/openvibe/ovIMatrix.h index 6434344da4d42bf76df5fb65943bdc372b489cd3..172051a6b95fe46f6ce1137509b6afb6b2b99e35 100644 --- a/openvibe/include/openvibe/ovIMatrix.h +++ b/openvibe/include/openvibe/ovIMatrix.h @@ -2,133 +2,132 @@ #include "ovIObject.h" -namespace OpenViBE +namespace OpenViBE { +/** + * \class IMatrix + * \author Yann Renard (INRIA/IRISA) + * \date 2007-11-21 + * \brief Basic OpenViBE matrix interface + * + * This interface offers functionalities to basically manipulate an n-dimensional + * matrix. The manipulation that can be done are very limited and nearly limits + * to memory manipulation. This is basically an unified way for storing matrices + * content in OpenViBE + * + * OpenViBE provides an standalone implementation of this interface in CMatrix + */ +class OV_API IMatrix : public IObject { +public: + + /** \name Accessors */ + //@{ + + /** + * \brief Gets the dimension count for this matrix + * \return the dimension count for this matrix + * \note Uninitialized matrices should return \c 0 + */ + virtual size_t getDimensionCount() const = 0; /** - * \class IMatrix - * \author Yann Renard (INRIA/IRISA) - * \date 2007-11-21 - * \brief Basic OpenViBE matrix interface + * \brief Gets the dimension size for a given dimension index + * \param index [in] : the dimension index which size has to be returned + * \return the dimension size for the specified dimension index + * \note Each dimension can have a different size + */ + virtual size_t getDimensionSize(const size_t index) const = 0; + /** + * \brief Gets the dimension label for a given dimension idx1 / dimension entry idx1 pair + * \param idx1 [in] : the dimension idx1 + * \param idx2 [in] : the dimension entry idx1 for the specified dimension idx1 + * \return the dimension label for the given dimension idx1 / dimension entry idx1 pair + * \note The string is permanent pointer until the dimension size or the label itself changes + */ + virtual const char* getDimensionLabel(const size_t idx1, const size_t idx2) const = 0; + + /** + * \brief Gets the raw buffer for this matrix + * \return the raw buffer for this matrix + * \note The raw buffer is permanent pointer until the dimension count or any dimension size changes + * + * When the raw buffer is acquired, the elements are accessed sequentially, using each dimension + * after the other. Suppose a matrix of 2 dimensions. First dimension size is 2 and second dimension + * size is 3 : + * + * \code + * + * IMatrix* matrix= // ... + * + * matrix->setDimensionCount(2); + * matrix->setDimensionSize(0, 2); + * matrix->setDimensionSize(1, 3); + * + * double* matrixRawBuffer=matrix->getBuffer(); + * + * matrixRawBuffer[0]; // this is matrixRawBuffer[0*3 + 0]; + * matrixRawBuffer[1]; // this is matrixRawBuffer[0*3 + 1]; + * matrixRawBuffer[2]; // this is matrixRawBuffer[0*3 + 2]; + * matrixRawBuffer[3]; // this is matrixRawBuffer[1*3 + 0]; + * matrixRawBuffer[4]; // this is matrixRawBuffer[1*3 + 1]; + * matrixRawBuffer[5]; // this is matrixRawBuffer[1*3 + 2]; * - * This interface offers functionalities to basically manipulate an n-dimensional - * matrix. The manipulation that can be done are very limited and nearly limits - * to memory manipulation. This is basically an unified way for storing matrices - * content in OpenViBE + * matrixRawBuffer[i*3+j]; // this is index i of the first dimension, and j of the second dimension * - * OpenViBE provides an standalone implementation of this interface in CMatrix + * \endcode + * \sa getBufferElementCount */ - class OV_API IMatrix : public IObject - { - public: - - /** \name Accessors */ - //@{ - - /** - * \brief Gets the dimension count for this matrix - * \return the dimension count for this matrix - * \note Uninitialized matrices should return \c 0 - */ - virtual size_t getDimensionCount() const = 0; - /** - * \brief Gets the dimension size for a given dimension index - * \param index [in] : the dimension index which size has to be returned - * \return the dimension size for the specified dimension index - * \note Each dimension can have a different size - */ - virtual size_t getDimensionSize(const size_t index) const = 0; - /** - * \brief Gets the dimension label for a given dimension idx1 / dimension entry idx1 pair - * \param idx1 [in] : the dimension idx1 - * \param idx2 [in] : the dimension entry idx1 for the specified dimension idx1 - * \return the dimension label for the given dimension idx1 / dimension entry idx1 pair - * \note The string is permanent pointer until the dimension size or the label itself changes - */ - virtual const char* getDimensionLabel(const size_t idx1, const size_t idx2) const = 0; - - /** - * \brief Gets the raw buffer for this matrix - * \return the raw buffer for this matrix - * \note The raw buffer is permanent pointer until the dimension count or any dimension size changes - * - * When the raw buffer is acquired, the elements are accessed sequentially, using each dimension - * after the other. Suppose a matrix of 2 dimensions. First dimension size is 2 and second dimension - * size is 3 : - * - * \code - * - * IMatrix* matrix= // ... - * - * matrix->setDimensionCount(2); - * matrix->setDimensionSize(0, 2); - * matrix->setDimensionSize(1, 3); - * - * double* matrixRawBuffer=matrix->getBuffer(); - * - * matrixRawBuffer[0]; // this is matrixRawBuffer[0*3 + 0]; - * matrixRawBuffer[1]; // this is matrixRawBuffer[0*3 + 1]; - * matrixRawBuffer[2]; // this is matrixRawBuffer[0*3 + 2]; - * matrixRawBuffer[3]; // this is matrixRawBuffer[1*3 + 0]; - * matrixRawBuffer[4]; // this is matrixRawBuffer[1*3 + 1]; - * matrixRawBuffer[5]; // this is matrixRawBuffer[1*3 + 2]; - * - * matrixRawBuffer[i*3+j]; // this is index i of the first dimension, and j of the second dimension - * - * \endcode - * \sa getBufferElementCount - */ - virtual const double* getBuffer() const = 0; - /** - * \brief Gets the total number of elements in the matrix - * \return the total number of elements in the matrix - * \note The value returned by this function is the size of the raw buffer returned by \c getBuffer - */ - virtual size_t getBufferElementCount() const = 0; + virtual const double* getBuffer() const = 0; + /** + * \brief Gets the total number of elements in the matrix + * \return the total number of elements in the matrix + * \note The value returned by this function is the size of the raw buffer returned by \c getBuffer + */ + virtual size_t getBufferElementCount() const = 0; - //@} - /** \name Modifiers */ - //@{ + //@} + /** \name Modifiers */ + //@{ - /** - * \brief Sets dimension count for this matrix - * \param count [in] : the number of dimension for this matrix - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool setDimensionCount(const size_t count) = 0; - /** - * \brief Sets the dimension size for this matrix on a given dimension index - * \param index [in] : the dimension index which size has to be changed - * \param size [in] : the new dimension size for this dimension - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool setDimensionSize(const size_t index, const size_t size) = 0; - /** - * \brief Sets the dimension label for this matrix on a given dimension idx1 / dimension entry idx1 pair - * \param idx1 [in] : the dimension idx1 - * \param idx2 [in] : the entry idx1 in the specificed dimension which label has to be changed - * \param label [in] : the new dimension label to apply to this dimension idx1 / dimension entry idx1 pair - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool setDimensionLabel(const size_t idx1, const size_t idx2, const char* label) = 0; + /** + * \brief Sets dimension count for this matrix + * \param count [in] : the number of dimension for this matrix + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool setDimensionCount(const size_t count) = 0; + /** + * \brief Sets the dimension size for this matrix on a given dimension index + * \param index [in] : the dimension index which size has to be changed + * \param size [in] : the new dimension size for this dimension + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool setDimensionSize(const size_t index, const size_t size) = 0; + /** + * \brief Sets the dimension label for this matrix on a given dimension idx1 / dimension entry idx1 pair + * \param idx1 [in] : the dimension idx1 + * \param idx2 [in] : the entry idx1 in the specificed dimension which label has to be changed + * \param label [in] : the new dimension label to apply to this dimension idx1 / dimension entry idx1 pair + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool setDimensionLabel(const size_t idx1, const size_t idx2, const char* label) = 0; - /** - * \brief Gets a writable raw buffer for this matrix - * \return the raw buffer for this matrix - * \note The raw buffer is permanent pointer until the dimension count or any dimension size changes - * - * \sa IMatrix::getBufferElementCount - * \sa IMatrix::getBuffer const - */ - virtual double* getBuffer() = 0; + /** + * \brief Gets a writable raw buffer for this matrix + * \return the raw buffer for this matrix + * \note The raw buffer is permanent pointer until the dimension count or any dimension size changes + * + * \sa IMatrix::getBufferElementCount + * \sa IMatrix::getBuffer const + */ + virtual double* getBuffer() = 0; - //@} + //@} - _IsDerivedFromClass_(IObject, OV_ClassId_Matrix) + _IsDerivedFromClass_(IObject, OV_ClassId_Matrix) - const double& operator [](const size_t index) const { return this->getBuffer()[index]; } - double& operator [](const size_t index) { return this->getBuffer()[index]; } - }; -} // namespace OpenViBE + const double& operator [](const size_t index) const { return this->getBuffer()[index]; } + double& operator [](const size_t index) { return this->getBuffer()[index]; } +}; +} // namespace OpenViBE diff --git a/openvibe/include/openvibe/ovIMemoryBuffer.h b/openvibe/include/openvibe/ovIMemoryBuffer.h index f49e664ea7f6d461b1ccbc786d4af4832b131e8f..c740b8c8946d6bc3c5c4362f162dc77e760f8d5c 100644 --- a/openvibe/include/openvibe/ovIMemoryBuffer.h +++ b/openvibe/include/openvibe/ovIMemoryBuffer.h @@ -2,88 +2,87 @@ #include "ovIObject.h" -namespace OpenViBE +namespace OpenViBE { +/** + * \class IMemoryBuffer + * \author Yann Renard (INRIA/IRISA) + * \date 2007-11-21 + * \brief Basic OpenViBE memory buffer interface + * + * This interface offers functionalities to basically manipulate a raw memory buffer. + * It allows the buffer to be resized and manipulated easily with no care of allocation + * reallocation. Implementations for this interface may provide optimisations for such + * operations. + * + * OpenViBE provides an standalone implementation of this interface in CMemoryBuffer + */ +class OV_API IMemoryBuffer : public IObject { +public: + /** - * \class IMemoryBuffer - * \author Yann Renard (INRIA/IRISA) - * \date 2007-11-21 - * \brief Basic OpenViBE memory buffer interface + * \brief Reserves some memory for this memory buffer + * \param size [in] : the amount of memory to reserve + * \return \e true in case of success. + * \return \e false in case of error. * - * This interface offers functionalities to basically manipulate a raw memory buffer. - * It allows the buffer to be resized and manipulated easily with no care of allocation - * reallocation. Implementations for this interface may provide optimisations for such - * operations. + * This function reserves some memory space for later use. This does not + * affect the actual size of the buffer but allows later calls to \c append + * not to reallocate the whole buffer. * - * OpenViBE provides an standalone implementation of this interface in CMemoryBuffer + * \note if \c size is lower than the actual buffer size + * then \e true is returned and nothing is done. */ - class OV_API IMemoryBuffer : public IObject - { - public: - - /** - * \brief Reserves some memory for this memory buffer - * \param size [in] : the amount of memory to reserve - * \return \e true in case of success. - * \return \e false in case of error. - * - * This function reserves some memory space for later use. This does not - * affect the actual size of the buffer but allows later calls to \c append - * not to reallocate the whole buffer. - * - * \note if \c size is lower than the actual buffer size - * then \e true is returned and nothing is done. - */ - virtual bool reserve(const size_t size) = 0; - /** - * \brief Changes the size of this memory buffer - * \param size [in] : the new size to give to the buffer - * \param discard [in] : tells the reallocation process whether it should presever currently stored data or not - * \return \e true in case of success. - * \return \e false in case of error. - * \note On error, the buffer is left unchanged. - * \note If the new size if lower than the current size and \c discard is true, the - * buffer is simply truncated to the \c size first bytes. - * \sa getSize - */ - virtual bool setSize(const size_t size, const bool discard) = 0; - /** - * \brief Gets the current size of this memory buffer - * \return the current size of this memory buffer - * \sa setSize - */ - virtual size_t getSize() const = 0; - /** - * \brief Gets a direct pointer to the byte array for read/write access - * \return a direct pointer to the byte array for read/write access - * \sa getSize - */ - virtual uint8_t* getDirectPointer() = 0; - /** - * \brief Gets a direct pointer to the byte array for read access - * \return a direct pointer to the byte array for read access - * \sa getSize - */ - virtual const uint8_t* getDirectPointer() const = 0; - /** - * \brief Appends data to this memory buffer - * \param buffer [in] : the buffer containing data that should be appended - * \param size [in] : the buffer size that should be appended - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool append(const uint8_t* buffer, const size_t size) = 0; - /** - * \brief Appends data to this memory buffer - * \param buffer [in] : the memory buffer containing data that should be appended - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool append(const IMemoryBuffer& buffer) { return this->append(buffer.getDirectPointer(), buffer.getSize()); } + virtual bool reserve(const size_t size) = 0; + /** + * \brief Changes the size of this memory buffer + * \param size [in] : the new size to give to the buffer + * \param discard [in] : tells the reallocation process whether it should presever currently stored data or not + * \return \e true in case of success. + * \return \e false in case of error. + * \note On error, the buffer is left unchanged. + * \note If the new size if lower than the current size and \c discard is true, the + * buffer is simply truncated to the \c size first bytes. + * \sa getSize + */ + virtual bool setSize(const size_t size, const bool discard) = 0; + /** + * \brief Gets the current size of this memory buffer + * \return the current size of this memory buffer + * \sa setSize + */ + virtual size_t getSize() const = 0; + /** + * \brief Gets a direct pointer to the byte array for read/write access + * \return a direct pointer to the byte array for read/write access + * \sa getSize + */ + virtual uint8_t* getDirectPointer() = 0; + /** + * \brief Gets a direct pointer to the byte array for read access + * \return a direct pointer to the byte array for read access + * \sa getSize + */ + virtual const uint8_t* getDirectPointer() const = 0; + /** + * \brief Appends data to this memory buffer + * \param buffer [in] : the buffer containing data that should be appended + * \param size [in] : the buffer size that should be appended + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool append(const uint8_t* buffer, const size_t size) = 0; + /** + * \brief Appends data to this memory buffer + * \param buffer [in] : the memory buffer containing data that should be appended + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool append(const IMemoryBuffer& buffer) { return this->append(buffer.getDirectPointer(), buffer.getSize()); } - _IsDerivedFromClass_(IObject, OV_ClassId_MemoryBuffer) + _IsDerivedFromClass_(IObject, OV_ClassId_MemoryBuffer) - const uint8_t& operator [](const size_t index) const { return this->getDirectPointer()[index]; } - uint8_t& operator [](const size_t index) { return this->getDirectPointer()[index]; } - }; -} // namespace OpenViBE + const uint8_t& operator [](const size_t index) const { return this->getDirectPointer()[index]; } + uint8_t& operator [](const size_t index) { return this->getDirectPointer()[index]; } +}; +} // namespace OpenViBE diff --git a/openvibe/include/openvibe/ovIObject.h b/openvibe/include/openvibe/ovIObject.h index 2c7861f0a93271a8cea61261a1f3556a38c013b8..555b4b367474b941bb0bc35ae0152c6e5fc0186b 100644 --- a/openvibe/include/openvibe/ovIObject.h +++ b/openvibe/include/openvibe/ovIObject.h @@ -3,14 +3,12 @@ #include "ov_defines.h" #include "ovCIdentifier.h" -namespace OpenViBE -{ - class IObjectVisitor; +namespace OpenViBE { +class IObjectVisitor; - namespace Kernel - { - class CKernelObjectFactory; - } // namespace Kernel +namespace Kernel { +class CKernelObjectFactory; +} // namespace Kernel #define _IsDerivedFromClass_(_SuperClassName_,_ClassIdentifier_) \ bool isDerivedFromClass( const OpenViBE::CIdentifier& classId) const override { return ((classId==(_ClassIdentifier_)) || _SuperClassName_::isDerivedFromClass(classId)); } @@ -19,72 +17,72 @@ namespace OpenViBE _IsDerivedFromClass_(_SuperClassName_,_ClassIdentifier_) \ OpenViBE::CIdentifier getClassIdentifier() const override { return _ClassIdentifier_; } +/** + * \class IObject + * \author Yann Renard (INRIA/IRISA) + * \date 2006-06-16 + * \brief Base class for all the OpenViBE platform objects + * + * Most of the complex objects existing in the OpenViBE platform should derive this base interface. Thus, several operations can + * be performed in order to work on the object. The most important may be the isDerivedFromClass method that allows the caller to + * know it the object has specific interface implementation and if the object could finally be casted in this interface or subclass. + * Several interfaces are provided in the OpenViBE specficiation but custom class could also be created. It is the responsability + * of the developer to notify the user of what interfaces are implemented in a concrete class. + * + * See isDerivedFromClass to have a sample of how this function + * could be used. + */ +class OV_API IObject +{ +public: + + friend class Kernel::CKernelObjectFactory; + + /** \name Class identification */ + //@{ + /** - * \class IObject - * \author Yann Renard (INRIA/IRISA) - * \date 2006-06-16 - * \brief Base class for all the OpenViBE platform objects + * \brief Returns the final class identifier of the concrete class + * \return The class identifier of this object. * - * Most of the complex objects existing in the OpenViBE platform should derive this base interface. Thus, several operations can - * be performed in order to work on the object. The most important may be the isDerivedFromClass method that allows the caller to - * know it the object has specific interface implementation and if the object could finally be casted in this interface or subclass. - * Several interfaces are provided in the OpenViBE specficiation but custom class could also be created. It is the responsability - * of the developer to notify the user of what interfaces are implemented in a concrete class. + * This method should return the class identifier of the concrete instanciated class. + */ + virtual CIdentifier getClassIdentifier() const = 0; + /** + * \brief Checks if this object is compatible with a class identifier + * \param classId [in] : the class identifier you want to test this object compatibility with + * \return \e true if this object si compatible with the given class identifier (this means the concrete class + * overloads the class with given class identifier) and \e false when this object is not compatible. * - * See isDerivedFromClass to have a sample of how this function - * could be used. + * This method should be used to check object compatibility with super classes and interfaces. For any concrete class + * instance derived from IObject, one can check if plugin functions are implemented and so on... see + * Plugins::IPluginObject for an example... */ - class OV_API IObject - { - public: - - friend class Kernel::CKernelObjectFactory; - - /** \name Class identification */ - //@{ - - /** - * \brief Returns the final class identifier of the concrete class - * \return The class identifier of this object. - * - * This method should return the class identifier of the concrete instanciated class. - */ - virtual CIdentifier getClassIdentifier() const = 0; - /** - * \brief Checks if this object is compatible with a class identifier - * \param classId [in] : the class identifier you want to test this object compatibility with - * \return \e true if this object si compatible with the given class identifier (this means the concrete class - * overloads the class with given class identifier) and \e false when this object is not compatible. - * - * This method should be used to check object compatibility with super classes and interfaces. For any concrete class - * instance derived from IObject, one can check if plugin functions are implemented and so on... see - * Plugins::IPluginObject for an example... - */ - virtual bool isDerivedFromClass(const CIdentifier& classId) const { return (classId == OV_ClassId_Object); } - - //@} - /** \name Visiting processes */ - //@{ - - /** - * \brief Requests this object to accept a visitor - * \param visitor [in] : the visitor reference which should act on this object - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool acceptVisitor(IObjectVisitor& visitor) { return true; } - - //@} - - protected: - - virtual ~IObject() { } - }; - - class CNullObject final : public IObject - { - public: - - _IsDerivedFromClass_Final_(IObject, OV_ClassId_Object) - }; + virtual bool isDerivedFromClass(const CIdentifier& classId) const { return (classId == OV_ClassId_Object); } + + //@} + /** \name Visiting processes */ + //@{ + + /** + * \brief Requests this object to accept a visitor + * \param visitor [in] : the visitor reference which should act on this object + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool acceptVisitor(IObjectVisitor& visitor) { return true; } + + //@} + +protected: + + virtual ~IObject() { } +}; + +class CNullObject final : public IObject +{ +public: + + _IsDerivedFromClass_Final_(IObject, OV_ClassId_Object) +}; } // namespace OpenViBE diff --git a/openvibe/include/openvibe/ovIObjectVisitor.h b/openvibe/include/openvibe/ovIObjectVisitor.h index 244bf5abcd43eaacc34e28d5269303d541618025..3d659aece460486ba427b4b15502526c18930ced 100644 --- a/openvibe/include/openvibe/ovIObjectVisitor.h +++ b/openvibe/include/openvibe/ovIObjectVisitor.h @@ -2,35 +2,33 @@ #include "ovIObject.h" -namespace OpenViBE -{ - namespace Kernel - { - class IObjectVisitorContext; +namespace OpenViBE { +namespace Kernel { +class IObjectVisitorContext; - class IBox; - class IComment; - class IMetadata; - class ILink; - class IScenario; - } // namespace kernel +class IBox; +class IComment; +class IMetadata; +class ILink; +class IScenario; +} // namespace kernel - class OV_API IObjectVisitor : public IObject - { - public: +class OV_API IObjectVisitor : public IObject +{ +public: - virtual bool processBegin(Kernel::IObjectVisitorContext& /*visitorCtx*/, Kernel::IBox& /*box*/) { return true; } - virtual bool processBegin(Kernel::IObjectVisitorContext& /*visitorCtx*/, Kernel::IComment& /*comment*/) { return true; } - virtual bool processBegin(Kernel::IObjectVisitorContext& /*visitorCtx*/, Kernel::IMetadata& /*metadata*/) { return true; } - virtual bool processBegin(Kernel::IObjectVisitorContext& /*visitorCtx*/, Kernel::ILink& /*link*/) { return true; } - virtual bool processBegin(Kernel::IObjectVisitorContext& /*visitorCtx*/, Kernel::IScenario& /*scenario*/) { return true; } + virtual bool processBegin(Kernel::IObjectVisitorContext& /*visitorCtx*/, Kernel::IBox& /*box*/) { return true; } + virtual bool processBegin(Kernel::IObjectVisitorContext& /*visitorCtx*/, Kernel::IComment& /*comment*/) { return true; } + virtual bool processBegin(Kernel::IObjectVisitorContext& /*visitorCtx*/, Kernel::IMetadata& /*metadata*/) { return true; } + virtual bool processBegin(Kernel::IObjectVisitorContext& /*visitorCtx*/, Kernel::ILink& /*link*/) { return true; } + virtual bool processBegin(Kernel::IObjectVisitorContext& /*visitorCtx*/, Kernel::IScenario& /*scenario*/) { return true; } - virtual bool processEnd(Kernel::IObjectVisitorContext& /*visitorCtx*/, Kernel::IBox& /*box*/) { return true; } - virtual bool processEnd(Kernel::IObjectVisitorContext& /*visitorCtx*/, Kernel::IComment& /*comment*/) { return true; } - virtual bool processEnd(Kernel::IObjectVisitorContext& /*visitorCtx*/, Kernel::IMetadata& /*metadata*/) { return true; } - virtual bool processEnd(Kernel::IObjectVisitorContext& /*visitorCtx*/, Kernel::ILink& /*link*/) { return true; } - virtual bool processEnd(Kernel::IObjectVisitorContext& /*visitorCtx*/, Kernel::IScenario& /*scenario*/) { return true; } + virtual bool processEnd(Kernel::IObjectVisitorContext& /*visitorCtx*/, Kernel::IBox& /*box*/) { return true; } + virtual bool processEnd(Kernel::IObjectVisitorContext& /*visitorCtx*/, Kernel::IComment& /*comment*/) { return true; } + virtual bool processEnd(Kernel::IObjectVisitorContext& /*visitorCtx*/, Kernel::IMetadata& /*metadata*/) { return true; } + virtual bool processEnd(Kernel::IObjectVisitorContext& /*visitorCtx*/, Kernel::ILink& /*link*/) { return true; } + virtual bool processEnd(Kernel::IObjectVisitorContext& /*visitorCtx*/, Kernel::IScenario& /*scenario*/) { return true; } - _IsDerivedFromClass_(IObject, OV_ClassId_ObjectVisitor) - }; -} // namespace OpenViBE + _IsDerivedFromClass_(IObject, OV_ClassId_ObjectVisitor) +}; +} // namespace OpenViBE diff --git a/openvibe/include/openvibe/ovIObserver.h b/openvibe/include/openvibe/ovIObserver.h index 65c38ce36ae8d8f4773a544e52899b4d692dd413..05bf82dfd27779b4cce37bb5c7a5b1a2fcd7cacd 100644 --- a/openvibe/include/openvibe/ovIObserver.h +++ b/openvibe/include/openvibe/ovIObserver.h @@ -4,29 +4,28 @@ #include "ovCObservable.h" #include "ov_defines.h" -namespace OpenViBE +namespace OpenViBE { +class CObservable; + +/** + * \class IObserver + * \author Guillaume Serrière (Inria/Loria) + * \date 2014-11-7 + * \brief OpenViBE Observer interface + * + * This interface is used in the Observer/Observable pattern + * implementation in OpenViBE. + */ +class IObserver { - class CObservable; +public: + virtual ~IObserver() = default; /** - * \class IObserver - * \author Guillaume Serrière (Inria/Loria) - * \date 2014-11-7 - * \brief OpenViBE Observer interface - * - * This interface is used in the Observer/Observable pattern - * implementation in OpenViBE. + * \brief Function called by the observed object when a notification is done. + * \param o [in] : the object which do the notification. + * \param data [in] : a pointer to data give by the observed object during the notification. */ - class IObserver - { - public: - virtual ~IObserver() = default; - - /** - * \brief Function called by the observed object when a notification is done. - * \param o [in] : the object which do the notification. - * \param data [in] : a pointer to data give by the observed object during the notification. - */ - virtual void update(CObservable& o, void* data) = 0; - }; -} // namespace OpenViBE + virtual void update(CObservable& o, void* data) = 0; +}; +} // namespace OpenViBE diff --git a/openvibe/include/openvibe/ovIStimulationSet.h b/openvibe/include/openvibe/ovIStimulationSet.h index 4e59c961b905233f1173c58bb62bfa480559dc60..1ab73fa172fc669805bf3eb7ce3ef7468cedac2b 100644 --- a/openvibe/include/openvibe/ovIStimulationSet.h +++ b/openvibe/include/openvibe/ovIStimulationSet.h @@ -2,119 +2,118 @@ #include "ovIObject.h" -namespace OpenViBE +namespace OpenViBE { +/** + * \class IStimulationSet + * \author Yann Renard (INRIA/IRISA) + * \date 2007-11-21 + * \brief Basic OpenViBE stimulation set interface + * + * This interface offers functionalities to handle a collection of OpenViBE stimulations. + * This collection basicaly consists in a list of stimulation information. Each stimulation + * has three information : an identifier, a date and a duration. + * + * OpenViBE provides an standalone implementation of this interface in CStimulationSet + */ + +class OV_API IStimulationSet : public IObject { +public: + /** - * \class IStimulationSet - * \author Yann Renard (INRIA/IRISA) - * \date 2007-11-21 - * \brief Basic OpenViBE stimulation set interface - * - * This interface offers functionalities to handle a collection of OpenViBE stimulations. - * This collection basicaly consists in a list of stimulation information. Each stimulation - * has three information : an identifier, a date and a duration. - * - * OpenViBE provides an standalone implementation of this interface in CStimulationSet + * \brief Clears this stimulation set removing every existing stimulation */ + virtual void clear() = 0; + /** + * \brief Gets the number of stimulations contained in this stimulation set + * \return the number of stimulations contained in this stimulation set. + */ + virtual size_t getStimulationCount() const = 0; + /** + * \brief Gets the identifier of a specific stimulation in this stimulation set + * \param index [in] : the index of the stimulation which identifier has to be returned + * \return the identifier for the specified stimulation. + */ + virtual uint64_t getStimulationIdentifier(const size_t index) const = 0; + /** + * \brief Gets the date of a specific stimulation in this stimulation set + * \param index [in] : the index of the stimulation which date has to be returned + * \return the date for the specified stimulation. + * \note the returned date is relative to the beginning of this stimulation set + * \note dates and durations are returned in seconds fixed point 32:32. Refer to \Doc_TimeManagement for more details + */ + virtual uint64_t getStimulationDate(const size_t index) const = 0; + /** + * \brief Gets the duration of a specific stimulation in this stimulation set + * \param index [in] : the index of the stimulation which duration has to be returned + * \return the duration for the specified stimulation. + * \note dates and durations are returned in seconds fixed point 32:32. Refer to \Doc_TimeManagement for more details + */ + virtual uint64_t getStimulationDuration(const size_t index) const = 0; + /** + * \brief Changes the stimulation count in this stimulation set + * \param n [in] : the new number of stimulations + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool setStimulationCount(const size_t n) = 0; + /** + * \brief Changes the identifier of a specific stimulation in this stimulation set + * \param index [in] : the index of the stimulation which id should be changed + * \param id [in] : the new id for the specified stimulation + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool setStimulationIdentifier(const size_t index, const uint64_t id) = 0; + /** + * \brief Changes the date of a specific stimulation in this stimulation set + * \param index [in] : the index of the stimulation which date should be changed + * \param date [in] : the new date for the specified stimulation + * \return \e true in case of success. + * \return \e false in case of error. + * \note dates and durations are returned in seconds fixed point 32:32. Refer to \Doc_TimeManagement for more details + */ + virtual bool setStimulationDate(const size_t index, const uint64_t date) = 0; + /** + * \brief Changes the duration of a specific stimulation in this stimulation set + * \param index [in] : the index of the stimulation which duration should be changed + * \param duration [in] : the new duration for the specified stimulation + * \return \e true in case of success. + * \return \e false in case of error. + * \note the returned date is relative to the beginning of this stimulation set + * \note dates and durations are returned in seconds fixed point 32:32. Refer to \Doc_TimeManagement for more details + */ + virtual bool setStimulationDuration(const size_t index, const uint64_t duration) = 0; + /** + * \brief Appends a stimulation to this stimulation set + * \param id [in] : the identifier of the stimulation to append + * \param date [in] : the date of the stimulation + * \param duration [in] : the duration of the stimulation + * \return the index of the appended stimulation in this stimulation set + */ + virtual size_t appendStimulation(const uint64_t id, const uint64_t date, const uint64_t duration) = 0; + /** + * \brief Inserts a stimulation to this stimulation set + * \param index [in] : the index of the stimulation to insert + * \param id [in] : the identifier of the stimulation + * \param date [in] : the date of the stimulation + * \param duration [in] : the duration of the stimulation + * \return \e true in case of success + * \return \e false in case of error + * \warning stimulation indexing change after call to this function : + * following stimulation(s) get one more indexed. + */ + virtual size_t insertStimulation(const size_t index, const uint64_t id, const uint64_t date, const uint64_t duration) = 0; + /** + * \brief Removes a stimulation from this stimulation set + * \param index [in] : the index of the stimulation to remove + * \return \e true in case of success + * \return \e false in case of error + * \warning stimulation indexing change after call to this function : + * following stimulation(s) get one less indexed. + */ + virtual bool removeStimulation(const size_t index) = 0; - class OV_API IStimulationSet : public IObject - { - public: - - /** - * \brief Clears this stimulation set removing every existing stimulation - */ - virtual void clear() = 0; - /** - * \brief Gets the number of stimulations contained in this stimulation set - * \return the number of stimulations contained in this stimulation set. - */ - virtual size_t getStimulationCount() const = 0; - /** - * \brief Gets the identifier of a specific stimulation in this stimulation set - * \param index [in] : the index of the stimulation which identifier has to be returned - * \return the identifier for the specified stimulation. - */ - virtual uint64_t getStimulationIdentifier(const size_t index) const = 0; - /** - * \brief Gets the date of a specific stimulation in this stimulation set - * \param index [in] : the index of the stimulation which date has to be returned - * \return the date for the specified stimulation. - * \note the returned date is relative to the beginning of this stimulation set - * \note dates and durations are returned in seconds fixed point 32:32. Refer to \Doc_TimeManagement for more details - */ - virtual uint64_t getStimulationDate(const size_t index) const = 0; - /** - * \brief Gets the duration of a specific stimulation in this stimulation set - * \param index [in] : the index of the stimulation which duration has to be returned - * \return the duration for the specified stimulation. - * \note dates and durations are returned in seconds fixed point 32:32. Refer to \Doc_TimeManagement for more details - */ - virtual uint64_t getStimulationDuration(const size_t index) const = 0; - /** - * \brief Changes the stimulation count in this stimulation set - * \param n [in] : the new number of stimulations - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool setStimulationCount(const size_t n) = 0; - /** - * \brief Changes the identifier of a specific stimulation in this stimulation set - * \param index [in] : the index of the stimulation which id should be changed - * \param id [in] : the new id for the specified stimulation - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool setStimulationIdentifier(const size_t index, const uint64_t id) = 0; - /** - * \brief Changes the date of a specific stimulation in this stimulation set - * \param index [in] : the index of the stimulation which date should be changed - * \param date [in] : the new date for the specified stimulation - * \return \e true in case of success. - * \return \e false in case of error. - * \note dates and durations are returned in seconds fixed point 32:32. Refer to \Doc_TimeManagement for more details - */ - virtual bool setStimulationDate(const size_t index, const uint64_t date) = 0; - /** - * \brief Changes the duration of a specific stimulation in this stimulation set - * \param index [in] : the index of the stimulation which duration should be changed - * \param duration [in] : the new duration for the specified stimulation - * \return \e true in case of success. - * \return \e false in case of error. - * \note the returned date is relative to the beginning of this stimulation set - * \note dates and durations are returned in seconds fixed point 32:32. Refer to \Doc_TimeManagement for more details - */ - virtual bool setStimulationDuration(const size_t index, const uint64_t duration) = 0; - /** - * \brief Appends a stimulation to this stimulation set - * \param id [in] : the identifier of the stimulation to append - * \param date [in] : the date of the stimulation - * \param duration [in] : the duration of the stimulation - * \return the index of the appended stimulation in this stimulation set - */ - virtual size_t appendStimulation(const uint64_t id, const uint64_t date, const uint64_t duration) = 0; - /** - * \brief Inserts a stimulation to this stimulation set - * \param index [in] : the index of the stimulation to insert - * \param id [in] : the identifier of the stimulation - * \param date [in] : the date of the stimulation - * \param duration [in] : the duration of the stimulation - * \return \e true in case of success - * \return \e false in case of error - * \warning stimulation indexing change after call to this function : - * following stimulation(s) get one more indexed. - */ - virtual size_t insertStimulation(const size_t index, const uint64_t id, const uint64_t date, const uint64_t duration) = 0; - /** - * \brief Removes a stimulation from this stimulation set - * \param index [in] : the index of the stimulation to remove - * \return \e true in case of success - * \return \e false in case of error - * \warning stimulation indexing change after call to this function : - * following stimulation(s) get one less indexed. - */ - virtual bool removeStimulation(const size_t index) = 0; - - _IsDerivedFromClass_(IObject, OV_ClassId_StimulationSet) - }; -} // namespace OpenViBE + _IsDerivedFromClass_(IObject, OV_ClassId_StimulationSet) +}; +} // namespace OpenViBE diff --git a/openvibe/include/openvibe/ov_all.h b/openvibe/include/openvibe/ov_all.h index 4a3810c73531a491cfbfa0d28d12e900a0d09ac4..61ffe64f7c8c572d095a0f20dea52ab0886e3100 100755 --- a/openvibe/include/openvibe/ov_all.h +++ b/openvibe/include/openvibe/ov_all.h @@ -68,10 +68,7 @@ #include "kernel/error/ovErrorType.h" #include "kernel/player/ovIBoxAlgorithmContext.h" -#include "kernel/player/ovIMessage.h" -#include "kernel/player/ovIMessageClock.h" -#include "kernel/player/ovIMessageEvent.h" -#include "kernel/player/ovIMessageSignal.h" +#include "kernel/player/CMessageClock.hpp" #include "kernel/player/ovIPlayer.h" #include "kernel/player/ovIPlayerContext.h" #include "kernel/player/ovIPlayerManager.h" @@ -110,15 +107,13 @@ #include "plugins/ovIBoxAlgorithm.h" #include "plugins/ovIBoxAlgorithmDesc.h" -namespace OpenViBE -{ - namespace Plugins - { - // Backward compatibility - typedef Kernel::IBox IStaticBoxContext; - typedef Kernel::IBoxIO IDynamicBoxContext; - } // namespace Plugins -} // namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +// Backward compatibility +typedef Kernel::IBox IStaticBoxContext; +typedef Kernel::IBoxIO IDynamicBoxContext; +} // namespace Plugins +} // namespace OpenViBE //___________________________________________________________________// // // @@ -133,8 +128,7 @@ namespace OpenViBE OVP_API bool onInitialize(const OpenViBE::Kernel::IPluginModuleContext& context) \ { -#define OVP_Declare_New(Class) \ - g_descriptors.emplace_back(new Class); +#define OVP_Declare_New(Class) g_descriptors.emplace_back(new Class); #define OVP_Declare_End() \ return true; \ diff --git a/openvibe/include/openvibe/ov_defines.h b/openvibe/include/openvibe/ov_defines.h index f329bf333c82a40d9e04294c61aaec95d43adf9b..bd068434ef9d3238969b3065f8b70bff1662d8b8 100755 --- a/openvibe/include/openvibe/ov_defines.h +++ b/openvibe/include/openvibe/ov_defines.h @@ -36,8 +36,6 @@ #define OV_ClassId_Kernel_Player_BoxAlgorithmContext OpenViBE::CIdentifier(0x275F4BB8, 0x49E08D24) #define OV_ClassId_Kernel_Player_Message OpenViBE::CIdentifier(0x64DCCE4E, 0x530CA785) #define OV_ClassId_Kernel_Player_MessageClock OpenViBE::CIdentifier(0x58AE3092, 0x0C3371A7) -#define OV_ClassId_Kernel_Player_MessageEvent OpenViBE::CIdentifier(0x1B9B49DB, 0x6DA217E7) -#define OV_ClassId_Kernel_Player_MessageSignal OpenViBE::CIdentifier(0x4E1709E5, 0x38AADA6C) #define OV_ClassId_Kernel_Player_Player OpenViBE::CIdentifier(0x790A8CC5, 0x1439C776) #define OV_ClassId_Kernel_Player_PlayerContext OpenViBE::CIdentifier(0x1F8D3E14, 0x73A4DB1F) #define OV_ClassId_Kernel_Player_PlayerManager OpenViBE::CIdentifier(0x2A49A89B, 0x78843238) diff --git a/openvibe/include/openvibe/ov_directories.h b/openvibe/include/openvibe/ov_directories.h index 0b4a39d1c3759ae6e5b333fdb9c6a3a6d46238aa..b1b0ca67999aab0953420bad84eb5d8f864eeefe 100644 --- a/openvibe/include/openvibe/ov_directories.h +++ b/openvibe/include/openvibe/ov_directories.h @@ -4,22 +4,21 @@ #include "ovCString.h" -namespace OpenViBE +namespace OpenViBE { +class Directories { - class Directories - { - // The functions in this file should be only used in bootstrapping circumstances where Configuration Manager (Kernel Context) is not available. - // With access to Configuration Manager, the paths should be fetched using tokens such as ${Path_UserData}. Note that in such a case changing the environment variable later may no longer be affected in the token value. + // The functions in this file should be only used in bootstrapping circumstances where Configuration Manager (Kernel Context) is not available. + // With access to Configuration Manager, the paths should be fetched using tokens such as ${Path_UserData}. Note that in such a case changing the environment variable later may no longer be affected in the token value. - // @NOTE These functions may not be thread-safe - public: - Directories() = delete; - static CString getDistRootDir() { return StringDirectories::getDistRootDir().c_str(); } - static CString getBinDir() { return StringDirectories::getBinDir().c_str(); } - static CString getDataDir() { return StringDirectories::getDataDir().c_str(); } - static CString getLibDir() { return StringDirectories::getLibDir().c_str(); } - static CString getUserHomeDir() { return StringDirectories::getUserHomeDir().c_str(); } - static CString getUserDataDir() { return StringDirectories::getUserDataDir().c_str(); } - static CString getLogDir() { return StringDirectories::getLogDir().c_str(); } - }; -} // namespace OpenViBE + // @NOTE These functions may not be thread-safe +public: + Directories() = delete; + static CString getDistRootDir() { return StringDirectories::getDistRootDir().c_str(); } + static CString getBinDir() { return StringDirectories::getBinDir().c_str(); } + static CString getDataDir() { return StringDirectories::getDataDir().c_str(); } + static CString getLibDir() { return StringDirectories::getLibDir().c_str(); } + static CString getUserHomeDir() { return StringDirectories::getUserHomeDir().c_str(); } + static CString getUserDataDir() { return StringDirectories::getUserDataDir().c_str(); } + static CString getLogDir() { return StringDirectories::getLogDir().c_str(); } +}; +} // namespace OpenViBE diff --git a/openvibe/include/openvibe/ov_directories_string.h b/openvibe/include/openvibe/ov_directories_string.h index ddb7afd58b3bedda064e94d0b4c55c83c8e7b6c7..696563683484d19410801429c9d276184d375ef3 100644 --- a/openvibe/include/openvibe/ov_directories_string.h +++ b/openvibe/include/openvibe/ov_directories_string.h @@ -20,137 +20,133 @@ #include <mach-o/dyld.h> #endif -namespace OpenViBE +namespace OpenViBE { +class StringDirectories { - class StringDirectories - { - public: - StringDirectories() = delete; +public: + StringDirectories() = delete; #ifdef OV_USE_CMAKE_DEFAULT_PATHS static std::string getDistRootDir() { return pathFromEnv("OV_PATH_ROOT", OV_CMAKE_PATH_ROOT); } #else - static std::string getDistRootDir() { return pathFromEnv("OV_PATH_ROOT", guessRootDir().c_str()); } + static std::string getDistRootDir() { return pathFromEnv("OV_PATH_ROOT", guessRootDir().c_str()); } #endif - static std::string getBinDir() { return pathFromEnvOrExtendedRoot("OV_PATH_BIN", "/bin", OV_CMAKE_PATH_BIN); } - static std::string getDataDir() { return pathFromEnvOrExtendedRoot("OV_PATH_DATA", "/share/openvibe", OV_CMAKE_PATH_DATA); } + static std::string getBinDir() { return pathFromEnvOrExtendedRoot("OV_PATH_BIN", "/bin", OV_CMAKE_PATH_BIN); } + static std::string getDataDir() { return pathFromEnvOrExtendedRoot("OV_PATH_DATA", "/share/openvibe", OV_CMAKE_PATH_DATA); } #if defined TARGET_OS_Windows - static std::string getLibDir() { return pathFromEnvOrExtendedRoot("OV_PATH_LIB", "/bin", OV_CMAKE_PATH_BIN); } - static std::string getUserHomeDir() { return pathFromEnv("USERPROFILE", "openvibe-user"); } - static std::string getUserDataDir() { return (pathFromEnv("APPDATA", "openvibe-user") + "/" + OV_CONFIG_SUBDIR); } + static std::string getLibDir() { return pathFromEnvOrExtendedRoot("OV_PATH_LIB", "/bin", OV_CMAKE_PATH_BIN); } + static std::string getUserHomeDir() { return pathFromEnv("USERPROFILE", "openvibe-user"); } + static std::string getUserDataDir() { return (pathFromEnv("APPDATA", "openvibe-user") + "/" + OV_CONFIG_SUBDIR); } - static std::string getAllUsersDataDir() - { - std::string path = pathFromEnv("PROGRAMDATA", ""); // first chance: Win7 and higher - if (path.empty()) { path = pathFromEnv("ALLUSERSPROFILE", ""); } // second chance: WinXP - if (path.empty()) { path = "openvibe-user"; } // fallback - return path + "/" + OV_CONFIG_SUBDIR; - } + static std::string getAllUsersDataDir() + { + std::string path = pathFromEnv("PROGRAMDATA", ""); // first chance: Win7 and higher + if (path.empty()) { path = pathFromEnv("ALLUSERSPROFILE", ""); } // second chance: WinXP + if (path.empty()) { path = "openvibe-user"; } // fallback + return path + "/" + OV_CONFIG_SUBDIR; + } #else - static std::string getLibDir() { return pathFromEnvOrExtendedRoot("OV_PATH_LIB", "/lib", OV_CMAKE_PATH_LIB); } - static std::string getUserHomeDir() { return pathFromEnv("HOME", "openvibe-user"); } - static std::string getUserDataDir() { return (getUserHomeDir() + "/.config/" + OV_CONFIG_SUBDIR); } - static std::string getAllUsersDataDir() { return (getUserHomeDir() + "/.config/" + OV_CONFIG_SUBDIR); } + static std::string getLibDir() { return pathFromEnvOrExtendedRoot("OV_PATH_LIB", "/lib", OV_CMAKE_PATH_LIB); } + static std::string getUserHomeDir() { return pathFromEnv("HOME", "openvibe-user"); } + static std::string getUserDataDir() { return (getUserHomeDir() + "/.config/" + OV_CONFIG_SUBDIR); } + static std::string getAllUsersDataDir() { return (getUserHomeDir() + "/.config/" + OV_CONFIG_SUBDIR); } #endif - static std::string getLogDir() { return getUserDataDir() + "/log"; } + static std::string getLogDir() { return getUserDataDir() + "/log"; } - private: +private: - // Used to convert \ in paths to /, we need this because \ is a special character for .conf token parsing - static std::string convertPath(const std::string& strIn) - { - std::string out(strIn); - const size_t len = strIn.length(); - for (size_t i = 0; i < len; ++i) { if (strIn[i] == '\\') { out[i] = '/'; } } - return out; - } + // Used to convert \ in paths to /, we need this because \ is a special character for .conf token parsing + static std::string convertPath(const std::string& strIn) + { + std::string out(strIn); + const size_t len = strIn.length(); + for (size_t i = 0; i < len; ++i) { if (strIn[i] == '\\') { out[i] = '/'; } } + return out; + } + + /// Try to guess the root directory by assuming that any program that uses the kernel is in the bin + /// subdirectory of the dist folder. + static std::string guessRootDir() + { + static std::string rootDir; + if (!rootDir.empty()) { return rootDir; } - /// Try to guess the root directory by assuming that any program that uses the kernel is in the bin - /// subdirectory of the dist folder. - static std::string guessRootDir() + std::string fullpath; +#if defined TARGET_OS_Windows + // Unlike GetEnvironmentVariableW, this function can not return the length of the actual path + const std::unique_ptr<wchar_t> utf16value(new wchar_t[1024]); + GetModuleFileNameW(nullptr, utf16value.get(), 1024); + const int multiByteSize = WideCharToMultiByte(CP_UTF8, 0, utf16value.get(), -1, nullptr, 0, nullptr, nullptr); + if (multiByteSize == 0) { - static std::string rootDir; - if (!rootDir.empty()) { return rootDir; } + // There are no sensible values to return if the above call fails and the program will not be + // able to run in any case. + std::abort(); + } + const std::unique_ptr<char> utf8Value(new char[size_t(multiByteSize)]); + if (WideCharToMultiByte(CP_UTF8, 0, utf16value.get(), -1, utf8Value.get(), multiByteSize, nullptr, nullptr) == 0) { std::abort(); } - std::string fullpath; -#if defined TARGET_OS_Windows - // Unlike GetEnvironmentVariableW, this function can not return the length of the actual path - const std::unique_ptr<wchar_t> utf16value(new wchar_t[1024]); - GetModuleFileNameW(nullptr, utf16value.get(), 1024); - const int multiByteSize = WideCharToMultiByte(CP_UTF8, 0, utf16value.get(), -1, nullptr, 0, nullptr, nullptr); - if (multiByteSize == 0) - { - // There are no sensible values to return if the above call fails and the program will not be - // able to run in any case. - std::abort(); - } - const std::unique_ptr<char> utf8Value(new char[size_t(multiByteSize)]); - if (WideCharToMultiByte(CP_UTF8, 0, utf16value.get(), -1, utf8Value.get(), multiByteSize, nullptr, nullptr) == 0) { std::abort(); } - - fullpath = convertPath(utf8Value.get()); + fullpath = convertPath(utf8Value.get()); #elif defined TARGET_OS_Linux - char path[2048]; - memset(path, 0, sizeof(path)); // readlink does not produce 0 terminated strings - readlink("/proc/self/exe", path, sizeof(path)); - fullpath = std::string(path); + char path[2048]; + memset(path, 0, sizeof(path)); // readlink does not produce 0 terminated strings + readlink("/proc/self/exe", path, sizeof(path)); + fullpath = std::string(path); #elif defined TARGET_OS_MacOS - size_t size = 0; - _NSGetExecutablePath(nullptr, &size); - std::unique_ptr<char> path(new char[size + 1]); + size_t size = 0; + _NSGetExecutablePath(nullptr, &size); + std::unique_ptr<char> path(new char[size + 1]); - if (_NSGetExecutablePath(path.get(), &size) != 0) { std::abort(); } + if (_NSGetExecutablePath(path.get(), &size) != 0) { std::abort(); } - fullpath = std::string(path.get()); + fullpath = std::string(path.get()); #endif - const auto slashBeforeLast = fullpath.find_last_of('/', fullpath.find_last_of('/') - 1); - rootDir = fullpath.substr(0, slashBeforeLast); - return rootDir; - } + const auto slashBeforeLast = fullpath.find_last_of('/', fullpath.find_last_of('/') - 1); + rootDir = fullpath.substr(0, slashBeforeLast); + return rootDir; + } - // Returns ENV variable value or sDefaultPath if the variable doesn't exist. The path is converted with each \ to /. - static std::string pathFromEnv(const char* sEnvVar, const char* sDefaultPath) - { + // Returns ENV variable value or sDefaultPath if the variable doesn't exist. The path is converted with each \ to /. + static std::string pathFromEnv(const char* sEnvVar, const char* sDefaultPath) + { #if defined TARGET_OS_Windows - // Using std::getenv on Windows yields UTF7 strings which do not work with the Utf8ToUtf16 function - // as this seems to be the only place where we actually get UTF7, let's get it as UTF16 by default - const DWORD wideBufferSize = GetEnvironmentVariableW(Common::Converter::Utf8ToUtf16(sEnvVar).c_str(), nullptr, 0); - if (wideBufferSize == 0) { return convertPath(sDefaultPath); } - const std::unique_ptr<wchar_t> utf16value(new wchar_t[wideBufferSize]); - GetEnvironmentVariableW(Common::Converter::Utf8ToUtf16(sEnvVar).c_str(), utf16value.get(), wideBufferSize); - - const int multiByteSize = WideCharToMultiByte(CP_UTF8, 0, utf16value.get(), -1, nullptr, 0, nullptr, nullptr); - if (multiByteSize == 0) { return convertPath(sDefaultPath); } - const std::unique_ptr<char> utf8Value(new char[size_t(multiByteSize)]); - if (WideCharToMultiByte(CP_UTF8, 0, utf16value.get(), -1, utf8Value.get(), multiByteSize, nullptr, nullptr) == 0) - { - return convertPath(sDefaultPath); - } - - const char* pathPtr = utf8Value.get(); + // Using std::getenv on Windows yields UTF7 strings which do not work with the Utf8ToUtf16 function + // as this seems to be the only place where we actually get UTF7, let's get it as UTF16 by default + const DWORD wideBufferSize = GetEnvironmentVariableW(Common::Converter::Utf8ToUtf16(sEnvVar).c_str(), nullptr, 0); + if (wideBufferSize == 0) { return convertPath(sDefaultPath); } + const std::unique_ptr<wchar_t> utf16value(new wchar_t[wideBufferSize]); + GetEnvironmentVariableW(Common::Converter::Utf8ToUtf16(sEnvVar).c_str(), utf16value.get(), wideBufferSize); + + const int multiByteSize = WideCharToMultiByte(CP_UTF8, 0, utf16value.get(), -1, nullptr, 0, nullptr, nullptr); + if (multiByteSize == 0) { return convertPath(sDefaultPath); } + const std::unique_ptr<char> utf8Value(new char[size_t(multiByteSize)]); + if (WideCharToMultiByte(CP_UTF8, 0, utf16value.get(), -1, utf8Value.get(), multiByteSize, nullptr, nullptr) == 0) { return convertPath(sDefaultPath); } + + const char* pathPtr = utf8Value.get(); #else const char * pathPtr = std::getenv(sEnvVar); #endif - const std::string path = (pathPtr ? pathPtr : sDefaultPath); - return convertPath(path); - } + const std::string path = (pathPtr ? pathPtr : sDefaultPath); + return convertPath(path); + } - // Returns ENV variable if it is defined, otherwise it extends the ROOT variable if it exists, finally returns a default path - static std::string pathFromEnvOrExtendedRoot(const char* envVar, const char* rootPostfix, const char* defaultPath) + // Returns ENV variable if it is defined, otherwise it extends the ROOT variable if it exists, finally returns a default path + static std::string pathFromEnvOrExtendedRoot(const char* envVar, const char* rootPostfix, const char* defaultPath) + { + if (std::getenv(envVar)) { return pathFromEnv(envVar, defaultPath); } + if (std::getenv("OV_PATH_ROOT")) { - if (std::getenv(envVar)) { return pathFromEnv(envVar, defaultPath); } - if (std::getenv("OV_PATH_ROOT")) - { - // the default case for this one is wrong but it should never happen - return pathFromEnv("OV_PATH_ROOT", "") + rootPostfix; - } + // the default case for this one is wrong but it should never happen + return pathFromEnv("OV_PATH_ROOT", "") + rootPostfix; + } #ifdef OV_USE_CMAKE_DEFAULT_PATHS - return convertPath(defaultPath); + return convertPath(defaultPath); #else - return guessRootDir() + rootPostfix; + return guessRootDir() + rootPostfix; #endif - } - }; -} // namespace OpenViBE + } +}; +} // namespace OpenViBE diff --git a/openvibe/include/openvibe/plugins/ovIAlgorithm.h b/openvibe/include/openvibe/plugins/ovIAlgorithm.h index a3abbed98df8590918cde4a49b55823904e0fbcf..6f85b5bece8a42c135086db6fc48ddee4b75a824 100644 --- a/openvibe/include/openvibe/plugins/ovIAlgorithm.h +++ b/openvibe/include/openvibe/plugins/ovIAlgorithm.h @@ -2,68 +2,65 @@ #include "ovIPluginObject.h" -namespace OpenViBE -{ - namespace Kernel - { - class IAlgorithmContext; - } // namespace Kernel +namespace OpenViBE { +namespace Kernel { +class IAlgorithmContext; +} // namespace Kernel - namespace Plugins - { - /** - * \class IAlgorithm - * \author Yann Renard (INRIA/IRISA) - * \date 2007-11-06 - * \brief Abstract algorithm, base element of OpenViBE processing objects - * \ingroup Group_Extend - * - * This class should be derived by any plugin that is related - * to data processing. It basically has a parameterable interface - * contained in the IAlgorithmContext object. This interface - * stores several typed parameters which can be modified either by - * outside world in order to provide input paramters to this algorithm - * or by this algorithm itself in order to produce output parameters. - * - * This is the heart of the extension mechanism of the - * OpenViBE platform. - * - * \sa Kernel::IAlgorithmDesc - * \sa Kernel::IAlgorithmContext - * - * \todo details about building new plugins - */ - class OV_API IAlgorithm : public IPluginObject - { - public: +namespace Plugins { +/** + * \class IAlgorithm + * \author Yann Renard (INRIA/IRISA) + * \date 2007-11-06 + * \brief Abstract algorithm, base element of OpenViBE processing objects + * \ingroup Group_Extend + * + * This class should be derived by any plugin that is related + * to data processing. It basically has a parameterable interface + * contained in the IAlgorithmContext object. This interface + * stores several typed parameters which can be modified either by + * outside world in order to provide input paramters to this algorithm + * or by this algorithm itself in order to produce output parameters. + * + * This is the heart of the extension mechanism of the + * OpenViBE platform. + * + * \sa Kernel::IAlgorithmDesc + * \sa Kernel::IAlgorithmContext + * + * \todo details about building new plugins + */ +class OV_API IAlgorithm : public IPluginObject +{ +public: - /** - * \brief Initializes this algorithm - * \param ctx [in] : the execution context for this algorithm - * \return \e true in case of success. - * \return \e false in case of error. - */ - virtual bool initialize(Kernel::IAlgorithmContext& ctx) { return true; } - /** - * \brief Unitializes this algorithm - * \param ctx [in] : the extecution context for this algorithm - * \return \e true in case of success. - * \return \e false in case of error. - * \exception this method must be noexcept - */ - virtual bool uninitialize(Kernel::IAlgorithmContext& ctx) { return true; } - /** - * \brief Effectively executes this algorithm - * \param ctx [in] : the extecution context for this algorithm - * \return \e true in case of success. - * \return \e false in case of error. - * - * When called, this function should get its "input" parameters, do stuffs with them - * and finally produce "output" parameters. - */ - virtual bool process(Kernel::IAlgorithmContext& ctx) = 0; + /** + * \brief Initializes this algorithm + * \param ctx [in] : the execution context for this algorithm + * \return \e true in case of success. + * \return \e false in case of error. + */ + virtual bool initialize(Kernel::IAlgorithmContext& ctx) { return true; } + /** + * \brief Unitializes this algorithm + * \param ctx [in] : the extecution context for this algorithm + * \return \e true in case of success. + * \return \e false in case of error. + * \exception this method must be noexcept + */ + virtual bool uninitialize(Kernel::IAlgorithmContext& ctx) { return true; } + /** + * \brief Effectively executes this algorithm + * \param ctx [in] : the extecution context for this algorithm + * \return \e true in case of success. + * \return \e false in case of error. + * + * When called, this function should get its "input" parameters, do stuffs with them + * and finally produce "output" parameters. + */ + virtual bool process(Kernel::IAlgorithmContext& ctx) = 0; - _IsDerivedFromClass_(IPluginObject, OV_ClassId_Plugins_Algorithm) - }; - } // namespace Plugins -} // namespace OpenViBE + _IsDerivedFromClass_(IPluginObject, OV_ClassId_Plugins_Algorithm) +}; +} // namespace Plugins +} // namespace OpenViBE diff --git a/openvibe/include/openvibe/plugins/ovIAlgorithmDesc.h b/openvibe/include/openvibe/plugins/ovIAlgorithmDesc.h index c6c72791866e4e1f9f758f3a1126196b3270415a..dbb10dc9c98342f4c13b33865d815468d7edd5bc 100644 --- a/openvibe/include/openvibe/plugins/ovIAlgorithmDesc.h +++ b/openvibe/include/openvibe/plugins/ovIAlgorithmDesc.h @@ -3,44 +3,42 @@ #include "ovIPluginObjectDesc.h" #include "../kernel/algorithm/ovIAlgorithmProto.h" -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +/** + * \class IAlgorithmDesc + * \author Yann Renard (INRIA/IRISA) + * \date 2007-11-06 + * \brief Algorithm plugin descriptor + * \ingroup Group_Extend + * + * This class should be derived by any plugin developer in + * order to describe a specific OpenViBE algorithm. + * + * \sa IAlgorithm + * + * \todo details about building new plugins + */ +class OV_API IAlgorithmDesc : public IPluginObjectDesc { - namespace Plugins - { - /** - * \class IAlgorithmDesc - * \author Yann Renard (INRIA/IRISA) - * \date 2007-11-06 - * \brief Algorithm plugin descriptor - * \ingroup Group_Extend - * - * This class should be derived by any plugin developer in - * order to describe a specific OpenViBE algorithm. - * - * \sa IAlgorithm - * - * \todo details about building new plugins - */ - class OV_API IAlgorithmDesc : public IPluginObjectDesc - { - public: +public: - /** - * \brief Gets the prototype for this algorithm - * \param prototype [out] : the prototype to fill - * \return \e true in case of success \e false in other cases. - * - * When this function is called by the OpenViBE - * platform, the plugin descriptor should fill in - * the structure to let the OpenViBE platform know - * what the algorithm should look like - * (inputs/outputs/triggers). - * - * \sa IAlgorithmProto - */ - virtual bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const = 0; + /** + * \brief Gets the prototype for this algorithm + * \param prototype [out] : the prototype to fill + * \return \e true in case of success \e false in other cases. + * + * When this function is called by the OpenViBE + * platform, the plugin descriptor should fill in + * the structure to let the OpenViBE platform know + * what the algorithm should look like + * (inputs/outputs/triggers). + * + * \sa IAlgorithmProto + */ + virtual bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const = 0; - _IsDerivedFromClass_(IPluginObjectDesc, OV_ClassId_Plugins_AlgorithmDesc) - }; - } // namespace Plugins -} // namespace OpenViBE + _IsDerivedFromClass_(IPluginObjectDesc, OV_ClassId_Plugins_AlgorithmDesc) +}; +} // namespace Plugins +} // namespace OpenViBE diff --git a/openvibe/include/openvibe/plugins/ovIBoxAlgorithm.h b/openvibe/include/openvibe/plugins/ovIBoxAlgorithm.h index 66bc7345387504551bebe1c234e3699835a865c4..202a2bc9e918de00ee624854dcf3d535a370f6a1 100644 --- a/openvibe/include/openvibe/plugins/ovIBoxAlgorithm.h +++ b/openvibe/include/openvibe/plugins/ovIBoxAlgorithm.h @@ -2,270 +2,223 @@ #include "ovIPluginObject.h" -namespace OpenViBE +namespace OpenViBE { +namespace Kernel { + +/** + * \brief This enum lists all the way a box can be modified + * \sa Plugins::IBoxListener::process + */ +enum class EBoxModification { - namespace Kernel - { - class IMessageClock; - class IMessageEvent; - class IMessageSignal; - - /** - * \brief This enum lists all the way a box can be modified - * \sa Plugins::IBoxListener::process - */ - enum class EBoxModification - { - Initialized, DefaultInitialized, - NameChanged, IdentifierChanged, AlgorithmClassIdentifierChanged, - InputConnected, InputDisconnected, InputAdded, InputRemoved, InputTypeChanged, InputNameChanged, - OutputConnected, OutputDisconnected, OutputAdded, OutputRemoved, OutputTypeChanged, OutputNameChanged, - SettingAdded, SettingRemoved, SettingTypeChanged, SettingNameChanged, SettingDefaultValueChanged, SettingValueChanged - }; - } // namespace Kernel - - // for backward compatibility - typedef Kernel::IMessageClock CMessageClock; - typedef Kernel::IMessageEvent CMessageEvent; - typedef Kernel::IMessageSignal CMessageSignal; - - namespace Kernel - { - class IBoxAlgorithmContext; - class IBoxListenerContext; - } - - namespace Plugins - { - /** - * \class IBoxAlgorithm - * \author Yann Renard (INRIA/IRISA) - * \date 2006-06-19 - * \brief Algorithm to create/process/transform OpenViBE data - * \ingroup Group_Extend - * - * This class should be derived by any plugin that is related - * to data processing. It can be data acquisition/production - * from an hardware device or from a file. It can be data - * processing/transforming, moving time information into - * frequency space for example. It can be data classification - * generating discrete classification events better than - * continuous data flow. - * - * This is the heart of the extension mechanism of the - * OpenViBE platform. - * - * \sa Kernel::IBoxAlgorithmDesc - * - * \todo details about building new plugins - */ - class OV_API IBoxAlgorithm : public IPluginObject - { - public: - - /** \name Behavioral configuration */ - //@{ - - /** - * \brief Gets the clock frequency to call this algorithm - * \param ctx [in] : The current box state - * \return The clock frequency to call this algorithm - * \note Default implementation returns 0 - * - * This function is used for algorithms that are triggered on - * clock signals. The frequency is given in Hz, with 32:32 fixed - * point representation thus returning \c (1<<32) will make the - * algorithm to be called every second, returning \c (100<<32) - * will make the algorithm being called 100 times a second, - * returning \c (1<<31) will make the algorithm be called once - * every two seconds and so on... - * - * \note Returning 0 means the algorithm should not be - * clock activated. - * - * \sa processClock - */ - virtual uint64_t getClockFrequency(Kernel::IBoxAlgorithmContext& ctx) { return 0; } - - //@} - /** \name Initialization / Uninitialization */ - //@{ - - /** - * \brief Prepares plugin object - * \param ctx [in] : the plugin object context - * \return \e true when this object successfully initialized - * or \e false if it didn't succeed to initialize. - * \note Default implementation simply returns \e true. - * - * After a successful initialization, the caller knows - * the object can safely be used... On failure, this object - * should be ready to be uninitialized and then released. - * - * \sa uninitialize - */ - virtual bool initialize(Kernel::IBoxAlgorithmContext& ctx) { return true; } - /** - * \brief Unprepares the object so it can be deleted - * \param ctx [in] : the plugin object context - * \return \e true when this object sucessfully uninitialized or \e false if didn't succeed to uninitialize. - * \exception this method must be noexcept - * \note Default implementation simply returns \e true. - * - * If this function returns \e false, it means it could not - * uninitialize the object members correctly. Thus, the - * object won't be released and none of its method will - * be called anymore for security. Note that this results - * in memory leaks. This is why this method should return - * \e true as often as possible. - * - * \sa initialize - */ - virtual bool uninitialize(Kernel::IBoxAlgorithmContext& ctx) { return true; } - - //@} - /** \name Several event processing callbacks */ - //@{ - - /** - * \brief Reaction to an event launched by another box - * \param ctx [in] : the box algorithm context to use - * \param msgEvent [in] : the message the box just received - * \return \e true when the message is processed. - * \return \e false when the message is not processed. - * \note Default implementation returns \e false - * - * This function is called by the OpenViBE kernel when - * another box tries to send an event message to this - * box. This event message is described in the - * msgEvent parameter and can be interpreted by this - * algorithm. - * - * \sa IBoxAlgorithmContext - */ - virtual bool processEvent(Kernel::IBoxAlgorithmContext& ctx, Kernel::IMessageEvent& msgEvent) { return false; } - /** - * \brief Reaction to a signal - * \param ctx [in] : the box algorithm context to use - * \param msgSignal [in] : the signal the box just received - * \return \e true when the message is processed. - * \return \e false when the message is not processed. - * \note Default implementation returns \e false - * - * This function is called by the OpenViBE kernel when - * it has sent a signal. Signal are special messages, - * mainly sent by the kernel to all of the OpenViBE - * boxes in order to tell them it is about to start, - * processing, stop processing, load a new scenario - * and so on... - * - * \sa Kernel::IBoxAlgorithmContext - */ - virtual bool processSignal(Kernel::IBoxAlgorithmContext& ctx, Kernel::IMessageSignal& msgSignal) { return false; } - /** - * \brief Reaction to a clock tick - * \param ctx [in] : the box algorithm context to use - * \param msgClock [in] : the clock message the box received - * \return \e true when the message is processed. - * \return \e false when the message is not processed. - * \note Default implementation returns \e false - * - * This function is called by the OpenViBE kernel when - * it has sent clock messages. Clock messages are used for - * processes that should be executed regularly and which - * can not be triggered thanks to their inputs (for example - * acquisition modules). They also can be used for example - * when viewing inputs on smaller range than what input - * sends periodically, thus needing a moving - * 'viewed-window' on lastly received data. - * - * \sa Kernel::IBoxAlgorithmContext - * \sa getClockFrequency - */ - virtual bool processClock(Kernel::IBoxAlgorithmContext& ctx, Kernel::IMessageClock& msgClock) { return false; } - /** - * \brief Reaction to an input update - * \param ctx [in] : the box algorithm context to use - * \param index [in] : the index of the input which has ben updated - * \return \e true when the message is processed. - * \return \e false when the message is not processed. - * \note Default implementation returns \e false - * - * This function is called by the OpenViBE kernel each - * time an input of this box is updated. This allows the - * algorithm to decide to call the process function and - * eventually to the received data. - * - * \sa Kernel::IBoxAlgorithmContext - */ - virtual bool processInput(Kernel::IBoxAlgorithmContext& ctx, const size_t index) { return false; } - - //@} - /** \name Algorithm processing */ - //@{ - - /** - * \brief Processing function - * \param ctx [in] : the box algorithm context to use - * \return \e true on success, \e false when something went wrong. - * - * This function is used to process the arrived data and - * eventually generate results. See OpenViBE global - * architecture to understand how the commponents interact - * and how an OpenViBE box works internally. - * - * The processing function may use the provided context - * in order to read its inputs and write its outputs... - * Also it could use the provided context to send - * messages/events to other boxes. Finally, it may use - * the provided context in order to perform rendering - * tasks ! - * - * \sa Kernel::IBoxAlgorithmContext - */ - virtual bool process(Kernel::IBoxAlgorithmContext& ctx) = 0; - - //@} - - _IsDerivedFromClass_(IPluginObject, OV_ClassId_Plugins_BoxAlgorithm) - }; - - class OV_API IBoxListener : public IPluginObject - { - public: - ~IBoxListener() override { } - void release() override { } - - virtual bool initialize(Kernel::IBoxListenerContext& /*boxListenerCtx*/) { return true; } - - virtual bool uninitialize(Kernel::IBoxListenerContext& /*boxListenerCtx*/) { return true; } - - /** \name Box modifications callbacks */ - //@{ - - /** - * \brief This callback is called when the box is modified in some way - * \return \e true in case of success. - * \return \e false in case of error. - * \param boxListenerCtx [in] : the box listener context - * containing the description of the box - * \param boxModificationType [in] : the type of modification - * applied to the box - * - * This function is called as soon as a modification is done - * on the box which this listener is attached to. The box listener - * is then allowed to examine and check box status validity - * and to adpat the box itself according to this validity. - * - * \sa IBoxProto - * \sa IBoxListenerContext - * \sa EBoxModification - */ - virtual bool process(Kernel::IBoxListenerContext& boxListenerCtx, const Kernel::EBoxModification boxModificationType) = 0; - - //@} - - _IsDerivedFromClass_(IPluginObject, OV_ClassId_Plugins_BoxListener) - }; - } // namespace Plugins -} // namespace OpenViBE + Initialized, DefaultInitialized, + NameChanged, IdentifierChanged, AlgorithmClassIdentifierChanged, + InputConnected, InputDisconnected, InputAdded, InputRemoved, InputTypeChanged, InputNameChanged, + OutputConnected, OutputDisconnected, OutputAdded, OutputRemoved, OutputTypeChanged, OutputNameChanged, + SettingAdded, SettingRemoved, SettingTypeChanged, SettingNameChanged, SettingDefaultValueChanged, SettingValueChanged +}; +} // namespace Kernel + + +namespace Kernel { +class IBoxAlgorithmContext; +class IBoxListenerContext; +} + +namespace Plugins { +/** + * \class IBoxAlgorithm + * \author Yann Renard (INRIA/IRISA) + * \date 2006-06-19 + * \brief Algorithm to create/process/transform OpenViBE data + * \ingroup Group_Extend + * + * This class should be derived by any plugin that is related + * to data processing. It can be data acquisition/production + * from an hardware device or from a file. It can be data + * processing/transforming, moving time information into + * frequency space for example. It can be data classification + * generating discrete classification events better than + * continuous data flow. + * + * This is the heart of the extension mechanism of the + * OpenViBE platform. + * + * \sa Kernel::IBoxAlgorithmDesc + * + * \todo details about building new plugins + */ +class OV_API IBoxAlgorithm : public IPluginObject +{ +public: + + /** \name Behavioral configuration */ + //@{ + + /** + * \brief Gets the clock frequency to call this algorithm + * \param ctx [in] : The current box state + * \return The clock frequency to call this algorithm + * \note Default implementation returns 0 + * + * This function is used for algorithms that are triggered on + * clock signals. The frequency is given in Hz, with 32:32 fixed + * point representation thus returning \c (1<<32) will make the + * algorithm to be called every second, returning \c (100<<32) + * will make the algorithm being called 100 times a second, + * returning \c (1<<31) will make the algorithm be called once + * every two seconds and so on... + * + * \note Returning 0 means the algorithm should not be + * clock activated. + * + * \sa processClock + */ + virtual uint64_t getClockFrequency(Kernel::IBoxAlgorithmContext& ctx) { return 0; } + + //@} + /** \name Initialization / Uninitialization */ + //@{ + + /** + * \brief Prepares plugin object + * \param ctx [in] : the plugin object context + * \return \e true when this object successfully initialized + * or \e false if it didn't succeed to initialize. + * \note Default implementation simply returns \e true. + * + * After a successful initialization, the caller knows + * the object can safely be used... On failure, this object + * should be ready to be uninitialized and then released. + * + * \sa uninitialize + */ + virtual bool initialize(Kernel::IBoxAlgorithmContext& ctx) { return true; } + /** + * \brief Unprepares the object so it can be deleted + * \param ctx [in] : the plugin object context + * \return \e true when this object sucessfully uninitialized or \e false if didn't succeed to uninitialize. + * \exception this method must be noexcept + * \note Default implementation simply returns \e true. + * + * If this function returns \e false, it means it could not + * uninitialize the object members correctly. Thus, the + * object won't be released and none of its method will + * be called anymore for security. Note that this results + * in memory leaks. This is why this method should return + * \e true as often as possible. + * + * \sa initialize + */ + virtual bool uninitialize(Kernel::IBoxAlgorithmContext& ctx) { return true; } + + //@} + /** \name Several event processing callbacks */ + //@{ + + /** + * \brief Reaction to a clock tick + * \param ctx [in] : the box algorithm context to use + * \param msg [in] : the clock message the box received + * \return \e true when the message is processed. + * \return \e false when the message is not processed. + * \note Default implementation returns \e false + * + * This function is called by the OpenViBE kernel when + * it has sent clock messages. Clock messages are used for + * processes that should be executed regularly and which + * can not be triggered thanks to their inputs (for example + * acquisition modules). They also can be used for example + * when viewing inputs on smaller range than what input + * sends periodically, thus needing a moving + * 'viewed-window' on lastly received data. + * + * \sa Kernel::IBoxAlgorithmContext + * \sa getClockFrequency + */ + virtual bool processClock(Kernel::IBoxAlgorithmContext& ctx, Kernel::CMessageClock& msg) { return false; } + /** + * \brief Reaction to an input update + * \param ctx [in] : the box algorithm context to use + * \param index [in] : the index of the input which has ben updated + * \return \e true when the message is processed. + * \return \e false when the message is not processed. + * \note Default implementation returns \e false + * + * This function is called by the OpenViBE kernel each + * time an input of this box is updated. This allows the + * algorithm to decide to call the process function and + * eventually to the received data. + * + * \sa Kernel::IBoxAlgorithmContext + */ + virtual bool processInput(Kernel::IBoxAlgorithmContext& ctx, const size_t index) { return false; } + + //@} + /** \name Algorithm processing */ + //@{ + + /** + * \brief Processing function + * \param ctx [in] : the box algorithm context to use + * \return \e true on success, \e false when something went wrong. + * + * This function is used to process the arrived data and + * eventually generate results. See OpenViBE global + * architecture to understand how the commponents interact + * and how an OpenViBE box works internally. + * + * The processing function may use the provided context + * in order to read its inputs and write its outputs... + * Also it could use the provided context to send + * messages/events to other boxes. Finally, it may use + * the provided context in order to perform rendering + * tasks ! + * + * \sa Kernel::IBoxAlgorithmContext + */ + virtual bool process(Kernel::IBoxAlgorithmContext& ctx) = 0; + + //@} + + _IsDerivedFromClass_(IPluginObject, OV_ClassId_Plugins_BoxAlgorithm) +}; + +class OV_API IBoxListener : public IPluginObject +{ +public: + ~IBoxListener() override { } + void release() override { } + + virtual bool initialize(Kernel::IBoxListenerContext& /*boxListenerCtx*/) { return true; } + virtual bool uninitialize(Kernel::IBoxListenerContext& /*boxListenerCtx*/) { return true; } + + /** \name Box modifications callbacks */ + //@{ + + /** + * \brief This callback is called when the box is modified in some way + * \return \e true in case of success. + * \return \e false in case of error. + * \param boxListenerCtx [in] : the box listener context + * containing the description of the box + * \param boxModificationType [in] : the type of modification + * applied to the box + * + * This function is called as soon as a modification is done + * on the box which this listener is attached to. The box listener + * is then allowed to examine and check box status validity + * and to adpat the box itself according to this validity. + * + * \sa IBoxProto + * \sa IBoxListenerContext + * \sa EBoxModification + */ + virtual bool process(Kernel::IBoxListenerContext& boxListenerCtx, const Kernel::EBoxModification boxModificationType) = 0; + + //@} + + _IsDerivedFromClass_(IPluginObject, OV_ClassId_Plugins_BoxListener) +}; +} // namespace Plugins +} // namespace OpenViBE diff --git a/openvibe/include/openvibe/plugins/ovIBoxAlgorithmDesc.h b/openvibe/include/openvibe/plugins/ovIBoxAlgorithmDesc.h index 3bf806769232cc0bc3a3b7627de3cad2ebd4dc2a..4f49fab8aa154b4edb4473e3698571f8de4cc146 100644 --- a/openvibe/include/openvibe/plugins/ovIBoxAlgorithmDesc.h +++ b/openvibe/include/openvibe/plugins/ovIBoxAlgorithmDesc.h @@ -2,103 +2,100 @@ #include "ovIPluginObjectDesc.h" -namespace OpenViBE -{ - namespace Kernel - { - class IBoxProto; - class IBoxAlgorithmContext; - } //namespace Kernel +namespace OpenViBE { +namespace Kernel { +class IBoxProto; +class IBoxAlgorithmContext; +} //namespace Kernel - namespace Plugins - { - class IBoxListener; +namespace Plugins { +class IBoxListener; - /** - * \class IBoxAlgorithmDesc - * \author Yann Renard (INRIA/IRISA) - * \date 2006-06-19 - * \brief Box algorithm plugin descriptor - * \ingroup Group_Extend - * - * This class should be derived by any plugin developer in - * order to describe a specific OpenViBE box algorithm. - * - * \sa IBoxAlgorithm - * - * \todo details about building new plugins - */ - class OV_API IBoxAlgorithmDesc : public IPluginObjectDesc - { - public: +/** + * \class IBoxAlgorithmDesc + * \author Yann Renard (INRIA/IRISA) + * \date 2006-06-19 + * \brief Box algorithm plugin descriptor + * \ingroup Group_Extend + * + * This class should be derived by any plugin developer in + * order to describe a specific OpenViBE box algorithm. + * + * \sa IBoxAlgorithm + * + * \todo details about building new plugins + */ +class OV_API IBoxAlgorithmDesc : public IPluginObjectDesc +{ +public: - /** \name Box prototype and description */ - //@{ + /** \name Box prototype and description */ + //@{ - /** - * \brief Gets the box prototype for this algorithm - * \param prototype [out] : the box prototype to fill - * \return \e true in case of success \e false in other cases. - * - * When this function is called by the OpenViBE - * platform, the plugin descriptor should fill in - * the structure to let the OpenViBE platform know - * what the corresponding box should look like - * (inputs/outputs/settings). - * - * \sa IBoxProto - */ - virtual bool getBoxPrototype(Kernel::IBoxProto& prototype) const = 0; - /** - * \brief Gets the stock item to display with this algorithm - * \return The stock item to display with this algorithm. - * - * This item name will be used by the GUI to display - * a symbol to the algorithm list so a user can quickly - * find them in the list. - * - * Default implementation returns empty string. If - * the item can not be found by name, or an empty string - * is returned, a default item will be displayed. - * - * \deprecated This method was used when visualisation was handled - * within the Kernel. This is kept for backward compatibility. Such features - * should now be handled at application level. - * - */ - virtual CString getStockItemName() const { return CString(""); } + /** + * \brief Gets the box prototype for this algorithm + * \param prototype [out] : the box prototype to fill + * \return \e true in case of success \e false in other cases. + * + * When this function is called by the OpenViBE + * platform, the plugin descriptor should fill in + * the structure to let the OpenViBE platform know + * what the corresponding box should look like + * (inputs/outputs/settings). + * + * \sa IBoxProto + */ + virtual bool getBoxPrototype(Kernel::IBoxProto& prototype) const = 0; + /** + * \brief Gets the stock item to display with this algorithm + * \return The stock item to display with this algorithm. + * + * This item name will be used by the GUI to display + * a symbol to the algorithm list so a user can quickly + * find them in the list. + * + * Default implementation returns empty string. If + * the item can not be found by name, or an empty string + * is returned, a default item will be displayed. + * + * \deprecated This method was used when visualisation was handled + * within the Kernel. This is kept for backward compatibility. Such features + * should now be handled at application level. + * + */ + virtual CString getStockItemName() const { return CString(""); } - //@{ - /** \name Box modification monitoring */ - //@{ + //@{ + /** \name Box modification monitoring */ + //@{ - /** - * \brief Creates a new box listener - * \return a new box listener - * - * This function is called by the kernel when a box instance - * is created if any modification flag is set in its prototype. - * This box listener will be notified each time the box is modified. - * - * \sa Kernel::IBoxProto - * \sa IBoxListener - */ - virtual IBoxListener* createBoxListener() const { return nullptr; } - /** - * \brief Releases an existing box listener - * \param listener [in] : the box listener to release - * - * This function is called by the kernel as soon as it knows - * a box listener won't be used any more. In case this descriptor - * allocated some memory for this box listener, this memory - * can be freed safely, no more call will be done on this - * box listener. - */ - virtual void releaseBoxListener(IBoxListener* listener) const { } + /** + * \brief Creates a new box listener + * \return a new box listener + * + * This function is called by the kernel when a box instance + * is created if any modification flag is set in its prototype. + * This box listener will be notified each time the box is modified. + * + * \sa Kernel::IBoxProto + * \sa IBoxListener + */ + virtual IBoxListener* createBoxListener() const { return nullptr; } + /** + * \brief Releases an existing box listener + * \param listener [in] : the box listener to release + * + * This function is called by the kernel as soon as it knows + * a box listener won't be used any more. In case this descriptor + * allocated some memory for this box listener, this memory + * can be freed safely, no more call will be done on this + * box listener. + */ + virtual void releaseBoxListener(IBoxListener* listener) const { } - //@} + //@} - _IsDerivedFromClass_(IPluginObjectDesc, OV_ClassId_Plugins_BoxAlgorithmDesc) - }; - } // namespace Plugins -} // namespace OpenViBE + _IsDerivedFromClass_(IPluginObjectDesc, OV_ClassId_Plugins_BoxAlgorithmDesc) +}; +} // namespace Plugins +} // namespace OpenViBE diff --git a/openvibe/include/openvibe/plugins/ovIPluginObject.h b/openvibe/include/openvibe/plugins/ovIPluginObject.h index d64c903baabf07434a729eec4c680de44e9d66be..be29ae1377082466061f4cb26b43799c26608794 100644 --- a/openvibe/include/openvibe/plugins/ovIPluginObject.h +++ b/openvibe/include/openvibe/plugins/ovIPluginObject.h @@ -2,54 +2,52 @@ #include "../ovIObject.h" -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +/** + * \class IPluginObject + * \author Yann Renard (INRIA/IRISA) + * \date 2006-06-19 + * \brief Base class for plugin object + * \ingroup Group_Extend + * + * This class is the base class for all the concrete plugin + * classes that extend the OpenViBE platform. It comes with + * several basic functions each plugin should have in order + * to work in the OpenViBE platform. + * + * Each plugin class comes with a plugin descriptor class + * (which you can write deriving the IPluginObjectDesc + * interface). + * + * \sa IBoxAlgorithm + * \sa IScenarioImporter + * \sa IScenarioExporter + * \sa IPluginObjectDesc + * + * \todo details about building new plugins + */ +class OV_API IPluginObject : public IObject { - namespace Plugins - { - /** - * \class IPluginObject - * \author Yann Renard (INRIA/IRISA) - * \date 2006-06-19 - * \brief Base class for plugin object - * \ingroup Group_Extend - * - * This class is the base class for all the concrete plugin - * classes that extend the OpenViBE platform. It comes with - * several basic functions each plugin should have in order - * to work in the OpenViBE platform. - * - * Each plugin class comes with a plugin descriptor class - * (which you can write deriving the IPluginObjectDesc - * interface). - * - * \sa IBoxAlgorithm - * \sa IScenarioImporter - * \sa IScenarioExporter - * \sa IPluginObjectDesc - * - * \todo details about building new plugins - */ - class OV_API IPluginObject : public IObject - { - public: +public: - /** \name Memory management */ - //@{ + /** \name Memory management */ + //@{ - /** - * \brief Informs the plugin object it won't be used anymore - * - * This is called by the OpenViBE platform to inform - * the plugin object it is not useful anymore. The plugin - * can chose whether to delete itself or to stay in - * memory until it decides is is ok to be deleted. - * However, the OpenViBE platform will not call any - * of the plugin functions after release is called. - */ - virtual void release() = 0; + /** + * \brief Informs the plugin object it won't be used anymore + * + * This is called by the OpenViBE platform to inform + * the plugin object it is not useful anymore. The plugin + * can chose whether to delete itself or to stay in + * memory until it decides is is ok to be deleted. + * However, the OpenViBE platform will not call any + * of the plugin functions after release is called. + */ + virtual void release() = 0; - //@} - _IsDerivedFromClass_(IObject, OV_ClassId_Plugins_PluginObject) - }; - } // namespace Plugins -} // namespace OpenViBE + //@} + _IsDerivedFromClass_(IObject, OV_ClassId_Plugins_PluginObject) +}; +} // namespace Plugins +} // namespace OpenViBE diff --git a/openvibe/include/openvibe/plugins/ovIPluginObjectDesc.h b/openvibe/include/openvibe/plugins/ovIPluginObjectDesc.h index 4984ab9ffac949f26ae11049df4c794ff6b666b8..4536da8c21adb472b97d46b2e7aa1451fc9a88ee 100644 --- a/openvibe/include/openvibe/plugins/ovIPluginObjectDesc.h +++ b/openvibe/include/openvibe/plugins/ovIPluginObjectDesc.h @@ -2,164 +2,162 @@ #include "../ovIObject.h" -namespace OpenViBE -{ - namespace Plugins - { - /// <summary> Functionality enumeration in order to know what a plugin is capable of </summary> - enum class EPluginFunctionality { Undefined, Processing, Visualization }; +namespace OpenViBE { +namespace Plugins { +/// <summary> Functionality enumeration in order to know what a plugin is capable of </summary> +enum class EPluginFunctionality { Undefined, Processing, Visualization }; - class IPluginObject; +class IPluginObject; - /** - * \class IPluginObjectDesc - * \author Yann Renard (INRIA/IRISA) - * \date 2006-06-19 - * \brief Base class for plugin descriptor - * \ingroup Group_Extend - * - * This class is the base class for all the plugin description classes. - * It contains basic functions that could be used for each plugin description. - * Derived plugin descriptions will be used as a prototype of what they can create. - * - * \sa IBoxAlgorithmDesc - * \sa IScenarioImporterDesc - * \sa IScenarioExporterDesc - * \sa IPluginObject - * - * \todo details about building new plugins - */ - class OV_API IPluginObjectDesc : public IObject - { - public: - /** \name Memory management */ - //@{ +/** + * \class IPluginObjectDesc + * \author Yann Renard (INRIA/IRISA) + * \date 2006-06-19 + * \brief Base class for plugin descriptor + * \ingroup Group_Extend + * + * This class is the base class for all the plugin description classes. + * It contains basic functions that could be used for each plugin description. + * Derived plugin descriptions will be used as a prototype of what they can create. + * + * \sa IBoxAlgorithmDesc + * \sa IScenarioImporterDesc + * \sa IScenarioExporterDesc + * \sa IPluginObject + * + * \todo details about building new plugins + */ +class OV_API IPluginObjectDesc : public IObject +{ +public: + /** \name Memory management */ + //@{ - /** - * \brief Informs the plugin description it won't be used any more - * - * This is called by the OpenViBE platform to inform the plugin description it is not useful anymore. - * The plugin can chose whether to delete itself or to stay in memory until it decides it is ok to be deleted. - * However, the OpenViBE platform will not call any of the plugin functions after release is called. - */ - virtual void release() = 0; + /** + * \brief Informs the plugin description it won't be used any more + * + * This is called by the OpenViBE platform to inform the plugin description it is not useful anymore. + * The plugin can chose whether to delete itself or to stay in memory until it decides it is ok to be deleted. + * However, the OpenViBE platform will not call any of the plugin functions after release is called. + */ + virtual void release() = 0; - //@} - /** \name Creation process */ - //@{ + //@} + /** \name Creation process */ + //@{ - /** - * \brief Gives a tip on what this plugin descriptor is able to create - * - * This may inform the OpenViBE platform about what kind of plugin can be created using this plugin descriptor. - * It should return the concrete class identifier of the plugin object itself. - */ - virtual CIdentifier getCreatedClass() const = 0; - virtual CIdentifier getCreatedClassIdentifier() const { return this->getCreatedClass(); } - /** - * \brief Creates the plugin object itself - * \return the created object. - * - * This method creates the plugin object itself and returns it with the lowest level interface. - * The OpenVIBE platform then uses the IObject::isDerivedFromClass method to use the plugin correctly. - */ - virtual IPluginObject* create() = 0; + /** + * \brief Gives a tip on what this plugin descriptor is able to create + * + * This may inform the OpenViBE platform about what kind of plugin can be created using this plugin descriptor. + * It should return the concrete class identifier of the plugin object itself. + */ + virtual CIdentifier getCreatedClass() const = 0; + virtual CIdentifier getCreatedClassIdentifier() const { return this->getCreatedClass(); } + /** + * \brief Creates the plugin object itself + * \return the created object. + * + * This method creates the plugin object itself and returns it with the lowest level interface. + * The OpenVIBE platform then uses the IObject::isDerivedFromClass method to use the plugin correctly. + */ + virtual IPluginObject* create() = 0; - //@} - /** \name Textual plugin object description and information */ - //@{ + //@} + /** \name Textual plugin object description and information */ + //@{ - /** - * \brief Gets the plugin name - * \return The plugin name. - * - * Default implementation simply returns empty string. - */ - virtual CString getName() const { return CString("no name"); } - /** - * \brief Gets the author name for this plugin - * \return The author name for this plugin. - * - * Default implementation simply returns "no name". - */ - virtual CString getAuthorName() const { return CString("unknown"); } - /** - * \brief Gets the author company name for this plugin - * \return The author company name for this plugin. - * - * Default implementation simply returns "unknown". - */ - virtual CString getAuthorCompanyName() const { return CString("unknown"); } - /** - * \brief Gets a short description of the plugin - * \return A short description of the plugin. - * - * Default implementation simply returns "unknown". - */ - virtual CString getShortDescription() const { return CString(""); } - /** - * \brief Gets a detailed description of the plugin - * \return A detailed description of the plugin. - * - * Default implementation simply returns empty string. - * - * \note You can use std::endl to have the description on several lines when needed. - */ - virtual CString getDetailedDescription() const { return CString(""); } - /** - * \brief Gets a basic category of the plugin - * \return the category tokens of the plugin - * - * The tokens should be separated with '/' characters in order to create sub categories. - * - * Default implementation returns "unknown". - */ - virtual CString getCategory() const { return CString("unknown"); } - /** - * \brief Gets the version of the plugin - * \return the version of the plugin. - * - * Default implementation simply returns "unknown". - */ - virtual CString getVersion() const { return CString("unknown"); } - /** - * \brief Gets the component in which the plugin is defined - * - * OpenViBE SDK is used to build platforms that are composed of several components. - * Each component can come with its own set of plugins, and has its own version. - * The \ref getAddedSoftwareVersion and \ref getUpdatedSoftwareVersion will return versions of the component in which the plugin belongs. - * - * \return a string identifier of the component - * \retval "unknown" if not redefined - */ - virtual CString getSoftwareComponent() const { return CString("unknown"); } - /** - * \brief Gets the version of the software in the one the plugin was added - * \return the version of the software in the one the plugin was added. - * \retval "unknown" if not redefined - * - * \sa getSoftwareComponent - */ - virtual CString getAddedSoftwareVersion() const { return CString("unknown"); } - /** - * \brief Gets the version of the software in the one the plugin was last updated - * \return the version of the software in the one the plugin was last updated - * \retval "unknown" if not redefined - * - * \sa getSoftwareComponent - */ - virtual CString getUpdatedSoftwareVersion() const { return CString("unknown"); } - /** - * \brief Tests whether the plugin has a given functionality - * \param functionality [in] : functionality of interest - * \return \e true in case plugin has this functionality. - * \return \e false otherwise. - */ - virtual bool hasFunctionality(const EPluginFunctionality functionality) const { return false; } + /** + * \brief Gets the plugin name + * \return The plugin name. + * + * Default implementation simply returns empty string. + */ + virtual CString getName() const { return CString("no name"); } + /** + * \brief Gets the author name for this plugin + * \return The author name for this plugin. + * + * Default implementation simply returns "no name". + */ + virtual CString getAuthorName() const { return CString("unknown"); } + /** + * \brief Gets the author company name for this plugin + * \return The author company name for this plugin. + * + * Default implementation simply returns "unknown". + */ + virtual CString getAuthorCompanyName() const { return CString("unknown"); } + /** + * \brief Gets a short description of the plugin + * \return A short description of the plugin. + * + * Default implementation simply returns "unknown". + */ + virtual CString getShortDescription() const { return CString(""); } + /** + * \brief Gets a detailed description of the plugin + * \return A detailed description of the plugin. + * + * Default implementation simply returns empty string. + * + * \note You can use std::endl to have the description on several lines when needed. + */ + virtual CString getDetailedDescription() const { return CString(""); } + /** + * \brief Gets a basic category of the plugin + * \return the category tokens of the plugin + * + * The tokens should be separated with '/' characters in order to create sub categories. + * + * Default implementation returns "unknown". + */ + virtual CString getCategory() const { return CString("unknown"); } + /** + * \brief Gets the version of the plugin + * \return the version of the plugin. + * + * Default implementation simply returns "unknown". + */ + virtual CString getVersion() const { return CString("unknown"); } + /** + * \brief Gets the component in which the plugin is defined + * + * OpenViBE SDK is used to build platforms that are composed of several components. + * Each component can come with its own set of plugins, and has its own version. + * The \ref getAddedSoftwareVersion and \ref getUpdatedSoftwareVersion will return versions of the component in which the plugin belongs. + * + * \return a string identifier of the component + * \retval "unknown" if not redefined + */ + virtual CString getSoftwareComponent() const { return CString("unknown"); } + /** + * \brief Gets the version of the software in the one the plugin was added + * \return the version of the software in the one the plugin was added. + * \retval "unknown" if not redefined + * + * \sa getSoftwareComponent + */ + virtual CString getAddedSoftwareVersion() const { return CString("unknown"); } + /** + * \brief Gets the version of the software in the one the plugin was last updated + * \return the version of the software in the one the plugin was last updated + * \retval "unknown" if not redefined + * + * \sa getSoftwareComponent + */ + virtual CString getUpdatedSoftwareVersion() const { return CString("unknown"); } + /** + * \brief Tests whether the plugin has a given functionality + * \param functionality [in] : functionality of interest + * \return \e true in case plugin has this functionality. + * \return \e false otherwise. + */ + virtual bool hasFunctionality(const EPluginFunctionality functionality) const { return false; } - //@} + //@} - _IsDerivedFromClass_(IObject, OV_ClassId_Plugins_PluginObjectDesc) - }; - } // namespace Plugins -} // namespace OpenViBE + _IsDerivedFromClass_(IObject, OV_ClassId_Plugins_PluginObjectDesc) +}; +} // namespace Plugins +} // namespace OpenViBE diff --git a/openvibe/src/CTime.cpp b/openvibe/src/CTime.cpp index 0d94fbf3cb78ccc9067e47d7283c1990337409fb..352dba67a8875d2d38d161e8a796786f859b4527 100644 --- a/openvibe/src/CTime.cpp +++ b/openvibe/src/CTime.cpp @@ -52,4 +52,4 @@ std::string CTime::str(const bool inSecond, const bool inHexa) const } //-------------------------------------------------------------------------------- -} // namespace OpenViBE +} // namespace OpenViBE diff --git a/openvibe/src/ovCIdentifier.cpp b/openvibe/src/ovCIdentifier.cpp index b44e169e5a47541b14e24a4ee565d69ce0aabd2a..890a1562c1690f04f0dc03984dc05167e4dfda9b 100755 --- a/openvibe/src/ovCIdentifier.cpp +++ b/openvibe/src/ovCIdentifier.cpp @@ -68,4 +68,4 @@ CIdentifier CIdentifier::random() return CIdentifier(uni(rng)); } -} // namespace OpenViBE +} // namespace OpenViBE diff --git a/openvibe/src/ovCKernelLoader.cpp b/openvibe/src/ovCKernelLoader.cpp index 29968b951c01fb9d005a200e59118f879d43a9ae..15ca1b1415fea2b13898765989c87123a43051de 100755 --- a/openvibe/src/ovCKernelLoader.cpp +++ b/openvibe/src/ovCKernelLoader.cpp @@ -16,30 +16,29 @@ using namespace /*OpenViBE::*/Kernel; //___________________________________________________________________// // // -namespace OpenViBE +namespace OpenViBE { +class CKernelLoaderBase : public IKernelLoader { - class CKernelLoaderBase : public IKernelLoader - { - public: +public: - CKernelLoaderBase() { } - bool initialize() override; - bool getKernelDesc(IKernelDesc*& desc) override; - bool uninitialize() override; - virtual void release(); + CKernelLoaderBase() { } + bool initialize() override; + bool getKernelDesc(IKernelDesc*& desc) override; + bool uninitialize() override; + virtual void release(); - _IsDerivedFromClass_Final_(IKernelLoader, OV_UndefinedIdentifier) + _IsDerivedFromClass_Final_(IKernelLoader, OV_UndefinedIdentifier) - virtual bool isOpen() = 0; + virtual bool isOpen() = 0; - protected: +protected: - CString m_filename; - bool (*m_onInitializeCB)() = nullptr; - bool (*m_onUninitializeCB)() = nullptr; - bool (*m_onGetKernelDescCB)(IKernelDesc*&) = nullptr; - }; -} // namespace OpenViBE + CString m_filename; + bool (*m_onInitializeCB)() = nullptr; + bool (*m_onUninitializeCB)() = nullptr; + bool (*m_onGetKernelDescCB)(IKernelDesc*&) = nullptr; +}; +} // namespace OpenViBE //___________________________________________________________________// // // @@ -69,8 +68,7 @@ void CKernelLoaderBase::release() { delete this; } //___________________________________________________________________// // // -namespace OpenViBE -{ +namespace OpenViBE { #if defined TARGET_OS_Linux || defined TARGET_OS_MacOS class CKernelLoaderLinux : public CKernelLoaderBase { @@ -89,23 +87,23 @@ namespace OpenViBE }; #elif defined TARGET_OS_Windows - class CKernelLoaderWindows final : public CKernelLoaderBase - { - public: - CKernelLoaderWindows() : m_fileHandle(nullptr) { } - bool load(const CString& filename, CString* error) override; - bool unload(CString* error) override; +class CKernelLoaderWindows final : public CKernelLoaderBase +{ +public: + CKernelLoaderWindows() : m_fileHandle(nullptr) { } + bool load(const CString& filename, CString* error) override; + bool unload(CString* error) override; - protected: - bool isOpen() override { return m_fileHandle != nullptr; } +protected: + bool isOpen() override { return m_fileHandle != nullptr; } - HMODULE m_fileHandle; - }; + HMODULE m_fileHandle; +}; #else #endif -} // namespace OpenViBE +} // namespace OpenViBE //___________________________________________________________________// // // @@ -246,11 +244,7 @@ CKernelLoader::CKernelLoader() CKernelLoader::~CKernelLoader() { delete m_impl; } bool CKernelLoader::load(const CString& filename, CString* error) { return m_impl ? m_impl->load(filename, error) : false; } - bool CKernelLoader::unload(CString* error) { return m_impl ? m_impl->unload(error) : false; } - bool CKernelLoader::initialize() { return m_impl ? m_impl->initialize() : false; } - bool CKernelLoader::getKernelDesc(IKernelDesc*& desc) { return m_impl ? m_impl->getKernelDesc(desc) : false; } - bool CKernelLoader::uninitialize() { return m_impl ? m_impl->uninitialize() : false; } diff --git a/openvibe/src/ovCMatrix.cpp b/openvibe/src/ovCMatrix.cpp index f51de975b947ad140b15d0add902235b0bb81e64..126ba3ca2bf6515f9515363e47aceeae030dcbd9 100644 --- a/openvibe/src/ovCMatrix.cpp +++ b/openvibe/src/ovCMatrix.cpp @@ -7,43 +7,41 @@ using namespace OpenViBE; using namespace std; -namespace OpenViBE +namespace OpenViBE { +namespace { +class CMatrixImpl final : public IMatrix { - namespace - { - class CMatrixImpl final : public IMatrix - { - public: - - CMatrixImpl(); - CMatrixImpl(const CMatrixImpl& other); - ~CMatrixImpl() override; - size_t getDimensionCount() const override; - size_t getDimensionSize(const size_t index) const override; - const char* getDimensionLabel(const size_t idx1, const size_t idx2) const override; - const double* getBuffer() const override; - size_t getBufferElementCount() const override; - bool setDimensionCount(const size_t count) override; - bool setDimensionSize(const size_t index, const size_t size) override; - bool setDimensionLabel(const size_t idx1, const size_t idx2, const char* label) override; - double* getBuffer() override; - - _IsDerivedFromClass_Final_(IMatrix, OV_ClassId_MatrixImpl) - - private: - - bool refreshInternalBuffer() const; - - protected: - - mutable double* m_buffer = nullptr; - mutable size_t m_size = 0; - - std::vector<size_t> m_dimensionSizes; - std::vector<std::vector<std::string>> m_dimensionLabels; - }; - } // namespace -} // namespace OpenViBE +public: + + CMatrixImpl(); + CMatrixImpl(const CMatrixImpl& other); + ~CMatrixImpl() override; + size_t getDimensionCount() const override; + size_t getDimensionSize(const size_t index) const override; + const char* getDimensionLabel(const size_t idx1, const size_t idx2) const override; + const double* getBuffer() const override; + size_t getBufferElementCount() const override; + bool setDimensionCount(const size_t count) override; + bool setDimensionSize(const size_t index, const size_t size) override; + bool setDimensionLabel(const size_t idx1, const size_t idx2, const char* label) override; + double* getBuffer() override; + + _IsDerivedFromClass_Final_(IMatrix, OV_ClassId_MatrixImpl) + +private: + + bool refreshInternalBuffer() const; + +protected: + + mutable double* m_buffer = nullptr; + mutable size_t m_size = 0; + + std::vector<size_t> m_dimensionSizes; + std::vector<std::vector<std::string>> m_dimensionLabels; +}; +} // namespace +} // namespace OpenViBE // ________________________________________________________________________________________________________________ // diff --git a/openvibe/src/ovCMemoryBuffer.cpp b/openvibe/src/ovCMemoryBuffer.cpp index dbaaa0721dd809a8587de4ca50bfe13bc7c20f82..23cda04f5b9691ea120b791345f1e7f3218f1075 100644 --- a/openvibe/src/ovCMemoryBuffer.cpp +++ b/openvibe/src/ovCMemoryBuffer.cpp @@ -4,36 +4,34 @@ using namespace OpenViBE; -namespace OpenViBE +namespace OpenViBE { +namespace { +class CMemoryBufferImpl final : public IMemoryBuffer { - namespace - { - class CMemoryBufferImpl final : public IMemoryBuffer - { - public: - - CMemoryBufferImpl() {} - explicit CMemoryBufferImpl(const IMemoryBuffer& buffer); - CMemoryBufferImpl(const uint8_t* buffer, size_t size); - ~CMemoryBufferImpl() override; - bool reserve(const size_t size) override; - bool setSize(const size_t size, const bool discard) override; - size_t getSize() const override { return m_size; } - uint8_t* getDirectPointer() override { return m_buffer; } - const uint8_t* getDirectPointer() const override { return m_buffer; } - bool append(const uint8_t* buffer, const size_t size) override; - bool append(const IMemoryBuffer& buffer) override; - - _IsDerivedFromClass_Final_(IMemoryBuffer, OV_ClassId_MemoryBufferImpl) - - protected: - - uint8_t* m_buffer = nullptr; - size_t m_size = 0; - size_t m_allocatedSize = 0; - }; - } // namespace -} // namespace OpenViBE +public: + + CMemoryBufferImpl() {} + explicit CMemoryBufferImpl(const IMemoryBuffer& buffer); + CMemoryBufferImpl(const uint8_t* buffer, size_t size); + ~CMemoryBufferImpl() override; + bool reserve(const size_t size) override; + bool setSize(const size_t size, const bool discard) override; + size_t getSize() const override { return m_size; } + uint8_t* getDirectPointer() override { return m_buffer; } + const uint8_t* getDirectPointer() const override { return m_buffer; } + bool append(const uint8_t* buffer, const size_t size) override; + bool append(const IMemoryBuffer& buffer) override; + + _IsDerivedFromClass_Final_(IMemoryBuffer, OV_ClassId_MemoryBufferImpl) + +protected: + + uint8_t* m_buffer = nullptr; + size_t m_size = 0; + size_t m_allocatedSize = 0; +}; +} // namespace +} // namespace OpenViBE // ________________________________________________________________________________________________________________ // diff --git a/openvibe/src/ovCNameValuePairList.cpp b/openvibe/src/ovCNameValuePairList.cpp index a62f19abe18e4f9d26b6778705e9f26573ef1df9..45fd76e74417ceb8258a3a218b32a49c47c532f8 100644 --- a/openvibe/src/ovCNameValuePairList.cpp +++ b/openvibe/src/ovCNameValuePairList.cpp @@ -102,4 +102,4 @@ bool CNameValuePairList::getValue(const size_t index, CString& name, CString& va size_t CNameValuePairList::getSize() const { return m_impl->m_Map.size(); } -} // namespace OpenViBE +} // namespace OpenViBE diff --git a/openvibe/src/ovCObservable.cpp b/openvibe/src/ovCObservable.cpp index bd64f0d463e266fce75cfb3f48c974143f0a2279..cf999f17917768da5f5cfab5850813ab9fd01495 100644 --- a/openvibe/src/ovCObservable.cpp +++ b/openvibe/src/ovCObservable.cpp @@ -40,4 +40,4 @@ void CObservable::notifyObservers(void* data) } } -} // namespace OpenViBE +} // namespace OpenViBE diff --git a/openvibe/src/ovCStimulationSet.cpp b/openvibe/src/ovCStimulationSet.cpp index 1fb6ca7ec60362b85c940123b1f6696ba2a75b08..9c7b59d86bc6cd0fb2714e3db85d7dce00abed12 100755 --- a/openvibe/src/ovCStimulationSet.cpp +++ b/openvibe/src/ovCStimulationSet.cpp @@ -5,48 +5,46 @@ using namespace OpenViBE; using namespace std; -namespace OpenViBE +namespace OpenViBE { +namespace { +class CStimulation { - namespace - { - class CStimulation - { - public: - - CStimulation() { } - - CStimulation(const uint64_t id, const uint64_t date, const uint64_t duration) - : m_Id(id), m_Date(date), m_Duration(duration) { } - - uint64_t m_Id = 0; - uint64_t m_Date = 0; - uint64_t m_Duration = 0; - }; - - class CStimulationSetImpl final : public IStimulationSet - { - public: - void clear() override { m_stimulations.clear(); } - size_t getStimulationCount() const override { return m_stimulations.size(); } - uint64_t getStimulationIdentifier(const size_t index) const override { return m_stimulations[index].m_Id; } - uint64_t getStimulationDate(const size_t index) const override { return m_stimulations[index].m_Date; } - uint64_t getStimulationDuration(const size_t index) const override { return m_stimulations[index].m_Duration; } - bool setStimulationCount(const size_t n) override; - bool setStimulationIdentifier(const size_t index, const uint64_t id) override; - bool setStimulationDate(const size_t index, const uint64_t date) override; - bool setStimulationDuration(const size_t index, const uint64_t duration) override; - size_t appendStimulation(const uint64_t id, const uint64_t date, const uint64_t duration) override; - size_t insertStimulation(const size_t index, const uint64_t id, const uint64_t date, const uint64_t duration) override; - bool removeStimulation(const size_t index) override; - - _IsDerivedFromClass_Final_(IStimulationSet, OV_ClassId_StimulationSetImpl) - - private: - - vector<CStimulation> m_stimulations; - }; - } // namespace -} // namespace OpenViBE +public: + + CStimulation() { } + + CStimulation(const uint64_t id, const uint64_t date, const uint64_t duration) + : m_Id(id), m_Date(date), m_Duration(duration) { } + + uint64_t m_Id = 0; + uint64_t m_Date = 0; + uint64_t m_Duration = 0; +}; + +class CStimulationSetImpl final : public IStimulationSet +{ +public: + void clear() override { m_stimulations.clear(); } + size_t getStimulationCount() const override { return m_stimulations.size(); } + uint64_t getStimulationIdentifier(const size_t index) const override { return m_stimulations[index].m_Id; } + uint64_t getStimulationDate(const size_t index) const override { return m_stimulations[index].m_Date; } + uint64_t getStimulationDuration(const size_t index) const override { return m_stimulations[index].m_Duration; } + bool setStimulationCount(const size_t n) override; + bool setStimulationIdentifier(const size_t index, const uint64_t id) override; + bool setStimulationDate(const size_t index, const uint64_t date) override; + bool setStimulationDuration(const size_t index, const uint64_t duration) override; + size_t appendStimulation(const uint64_t id, const uint64_t date, const uint64_t duration) override; + size_t insertStimulation(const size_t index, const uint64_t id, const uint64_t date, const uint64_t duration) override; + bool removeStimulation(const size_t index) override; + + _IsDerivedFromClass_Final_(IStimulationSet, OV_ClassId_StimulationSetImpl) + +private: + + vector<CStimulation> m_stimulations; +}; +} // namespace +} // namespace OpenViBE // ________________________________________________________________________________________________________________ // diff --git a/openvibe/src/ovCString.cpp b/openvibe/src/ovCString.cpp index 01d20156f6f62bcf34bae9abfebc663be5d64452..de4365d4be99c83c4ae37b0aa7c76b61f006b015 100755 --- a/openvibe/src/ovCString.cpp +++ b/openvibe/src/ovCString.cpp @@ -68,4 +68,4 @@ const char* CString::toASCIIString() const { return m_impl->m_Value.c_str(); } size_t CString::length() const { return m_impl->m_Value.length(); } -} // namespace OpenViBE +} // namespace OpenViBE diff --git a/plugins/processing/classification/CMakeLists.txt b/plugins/processing/classification/CMakeLists.txt index 1fb9b049850e87f4fb7087aa880c6582de9a7e7a..f20ee40049d2a69cb302b79f6433d00a8a0cc1ac 100644 --- a/plugins/processing/classification/CMakeLists.txt +++ b/plugins/processing/classification/CMakeLists.txt @@ -11,6 +11,7 @@ ADD_LIBRARY(${PROJECT_NAME} SHARED ${SRC_FILES}) SET_TARGET_PROPERTIES(${PROJECT_NAME} PROPERTIES VERSION ${PROJECT_VERSION} SOVERSION ${PROJECT_VERSION_MAJOR} + FOLDER ${PLUGINS_FOLDER} COMPILE_FLAGS "-DOVP_Exports -DOVP_Shared") INCLUDE("FindOpenViBE") @@ -24,9 +25,7 @@ INCLUDE("FindThirdPartyEigen") # --------------------------------- # Target macros -# Defines target operating system -# Defines target architecture -# Defines target compiler +# Defines target operating system, architecture, compiler # --------------------------------- SET_BUILD_PLATFORM() diff --git a/plugins/processing/classification/src/algorithms/ovpCAlgorithmClassifierLDA.cpp b/plugins/processing/classification/src/algorithms/ovpCAlgorithmClassifierLDA.cpp index 346af869119457b89b1d894957cedde2c8a7c59c..84e5ad055f699062a24a0ac41a5b1255907ae91c 100644 --- a/plugins/processing/classification/src/algorithms/ovpCAlgorithmClassifierLDA.cpp +++ b/plugins/processing/classification/src/algorithms/ovpCAlgorithmClassifierLDA.cpp @@ -21,15 +21,14 @@ using namespace /*OpenViBE::Plugins::*/Classification; using namespace Eigen; -namespace -{ - const char* const TYPE_NODE_NAME = "LDA"; - const char* const CLASSES_NODE_NAME = "Classes"; - //const char* const COEFFICIENTS_NODE_NAME = "Weights"; - //const char* const BIAS_DISTANCE_NODE_NAME = "Bias-distance"; - //const char* const COEFFICIENT_PROBABILITY_NODE_NAME = "Coefficient-probability"; - const char* const COMPUTATION_HELPERS_CONFIGURATION_NODE = "Class-config-list"; - const char* const LDA_CONFIG_FILE_VERSION_ATTRIBUTE_NAME = "version"; +namespace { +const char* const TYPE_NODE_NAME = "LDA"; +const char* const CLASSES_NODE_NAME = "Classes"; +//const char* const COEFFICIENTS_NODE_NAME = "Weights"; +//const char* const BIAS_DISTANCE_NODE_NAME = "Bias-distance"; +//const char* const COEFFICIENT_PROBABILITY_NODE_NAME = "Coefficient-probability"; +const char* const COMPUTATION_HELPERS_CONFIGURATION_NODE = "Class-config-list"; +const char* const LDA_CONFIG_FILE_VERSION_ATTRIBUTE_NAME = "version"; } extern const char* const CLASSIFIER_ROOT; diff --git a/plugins/processing/classification/src/algorithms/ovpCAlgorithmClassifierLDA.h b/plugins/processing/classification/src/algorithms/ovpCAlgorithmClassifierLDA.h index 9e4e3843d05a1ab4a1ff26ae46ca934979dc7104..edf26cc3801400b4c7f82f40a55fae8be7eb5ee4 100644 --- a/plugins/processing/classification/src/algorithms/ovpCAlgorithmClassifierLDA.h +++ b/plugins/processing/classification/src/algorithms/ovpCAlgorithmClassifierLDA.h @@ -13,90 +13,85 @@ #include <Eigen/Dense> -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace Classification { +class CAlgorithmLDADiscriminantFunction; + +int LDAClassificationCompare(IMatrix& first, IMatrix& second); + +typedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> MatrixXdRowMajor; + +class CAlgorithmClassifierLDA final : public Toolkit::CAlgorithmClassifier +{ +public: + bool initialize() override; + bool uninitialize() override; + bool train(const Toolkit::IFeatureVectorSet& dataset) override; + bool classify(const Toolkit::IFeatureVector& sample, double& classId, Toolkit::IVector& distance, Toolkit::IVector& probability) override; + XML::IXMLNode* saveConfig() override; + bool loadConfig(XML::IXMLNode* configNode) override; + size_t getNProbabilities() override { return m_discriminantFunctions.size(); } + size_t getNDistances() override { return m_discriminantFunctions.size(); } + + _IsDerivedFromClass_Final_(CAlgorithmClassifier, OVP_ClassId_Algorithm_ClassifierLDA) + +protected: + // Debug method. Prints the matrix to the logManager. May be disabled in implementation. + static void dumpMatrix(Kernel::ILogManager& pMgr, const MatrixXdRowMajor& mat, const CString& desc); + + std::vector<double> m_labels; + std::vector<CAlgorithmLDADiscriminantFunction> m_discriminantFunctions; + + Eigen::MatrixXd m_coefficients; + Eigen::MatrixXd m_weights; + double m_biasDistance = 0; + double m_w0 = 0; + + size_t m_nCols = 0; + size_t m_nClasses = 0; + + Kernel::IAlgorithmProxy* m_covAlgorithm = nullptr; + +private: + void loadClassesFromNode(XML::IXMLNode* node); + void loadCoefsFromNode(XML::IXMLNode* node); + + size_t getClassCount() const { return m_nClasses; } +}; + +class CAlgorithmClassifierLDADesc final : public Toolkit::CAlgorithmClassifierDesc { - namespace Plugins +public: + void release() override { } + CString getName() const override { return CString("LDA Classifier"); } + CString getAuthorName() const override { return CString("Jussi T. Lindgren / Guillaume Serrière"); } + CString getAuthorCompanyName() const override { return CString("Inria / Loria"); } + CString getShortDescription() const override { return CString("Estimates LDA using regularized or classic covariances"); } + CString getDetailedDescription() const override { return CString(""); } + CString getCategory() const override { return CString(""); } + CString getVersion() const override { return CString("2.0"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_Algorithm_ClassifierLDA; } + IPluginObject* create() override { return new CAlgorithmClassifierLDA; } + + bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override { - namespace Classification - { - class CAlgorithmLDADiscriminantFunction; - - int LDAClassificationCompare(IMatrix& first, IMatrix& second); - - typedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> MatrixXdRowMajor; - - class CAlgorithmClassifierLDA final : public Toolkit::CAlgorithmClassifier - { - public: - bool initialize() override; - bool uninitialize() override; - bool train(const Toolkit::IFeatureVectorSet& dataset) override; - bool classify(const Toolkit::IFeatureVector& sample, double& classId, Toolkit::IVector& distance, - Toolkit::IVector& probability) override; - XML::IXMLNode* saveConfig() override; - bool loadConfig(XML::IXMLNode* configNode) override; - size_t getNProbabilities() override { return m_discriminantFunctions.size(); } - size_t getNDistances() override { return m_discriminantFunctions.size(); } - - _IsDerivedFromClass_Final_(CAlgorithmClassifier, OVP_ClassId_Algorithm_ClassifierLDA) - - protected: - // Debug method. Prints the matrix to the logManager. May be disabled in implementation. - static void dumpMatrix(Kernel::ILogManager& pMgr, const MatrixXdRowMajor& mat, const CString& desc); - - std::vector<double> m_labels; - std::vector<CAlgorithmLDADiscriminantFunction> m_discriminantFunctions; - - Eigen::MatrixXd m_coefficients; - Eigen::MatrixXd m_weights; - double m_biasDistance = 0; - double m_w0 = 0; - - size_t m_nCols = 0; - size_t m_nClasses = 0; - - Kernel::IAlgorithmProxy* m_covAlgorithm = nullptr; - - private: - void loadClassesFromNode(XML::IXMLNode* node); - void loadCoefsFromNode(XML::IXMLNode* node); - - size_t getClassCount() const { return m_nClasses; } - }; - - class CAlgorithmClassifierLDADesc final : public Toolkit::CAlgorithmClassifierDesc - { - public: - void release() override { } - CString getName() const override { return CString("LDA Classifier"); } - CString getAuthorName() const override { return CString("Jussi T. Lindgren / Guillaume Serrière"); } - CString getAuthorCompanyName() const override { return CString("Inria / Loria"); } - CString getShortDescription() const override { return CString("Estimates LDA using regularized or classic covariances"); } - CString getDetailedDescription() const override { return CString(""); } - CString getCategory() const override { return CString(""); } - CString getVersion() const override { return CString("2.0"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_Algorithm_ClassifierLDA; } - IPluginObject* create() override { return new CAlgorithmClassifierLDA; } - - bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override - { - prototype.addInputParameter(OVP_Algorithm_ClassifierLDA_InputParameterId_UseShrinkage, "Use shrinkage", Kernel::ParameterType_Boolean); - prototype.addInputParameter( - OVP_Algorithm_ClassifierLDA_InputParameterId_DiagonalCov, "Shrinkage: Force diagonal cov (DDA)", Kernel::ParameterType_Boolean); - prototype.addInputParameter( - OVP_Algorithm_ClassifierLDA_InputParameterId_Shrinkage, "Shrinkage coefficient (-1 == auto)", Kernel::ParameterType_Float); - - CAlgorithmClassifierDesc::getAlgorithmPrototype(prototype); - return true; - } - - _IsDerivedFromClass_Final_(CAlgorithmClassifierDesc, OVP_ClassId_Algorithm_ClassifierLDADesc) - }; - } // namespace Classification - } // namespace Plugins + prototype.addInputParameter(OVP_Algorithm_ClassifierLDA_InputParameterId_UseShrinkage, "Use shrinkage", Kernel::ParameterType_Boolean); + prototype.addInputParameter(OVP_Algorithm_ClassifierLDA_InputParameterId_DiagonalCov, "Shrinkage: Force diagonal cov (DDA)", + Kernel::ParameterType_Boolean); + prototype.addInputParameter(OVP_Algorithm_ClassifierLDA_InputParameterId_Shrinkage, "Shrinkage coefficient (-1 == auto)", Kernel::ParameterType_Float); + + CAlgorithmClassifierDesc::getAlgorithmPrototype(prototype); + return true; + } + + _IsDerivedFromClass_Final_(CAlgorithmClassifierDesc, OVP_ClassId_Algorithm_ClassifierLDADesc) +}; +} // namespace Classification +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/classification/src/algorithms/ovpCAlgorithmClassifierNULL.h b/plugins/processing/classification/src/algorithms/ovpCAlgorithmClassifierNULL.h index c4d12e7201f0d6842b224ea405012768b5a42d48..5402b4bb4de14122cec84fd1e3485bcf67cae98a 100644 --- a/plugins/processing/classification/src/algorithms/ovpCAlgorithmClassifierNULL.h +++ b/plugins/processing/classification/src/algorithms/ovpCAlgorithmClassifierNULL.h @@ -7,58 +7,54 @@ #include <xml/IXMLNode.h> -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace Classification { +class CAlgorithmClassifierNULL final : public Toolkit::CAlgorithmClassifier { - namespace Plugins - { - namespace Classification - { - class CAlgorithmClassifierNULL final : public Toolkit::CAlgorithmClassifier - { - public: - - CAlgorithmClassifierNULL() { } - bool initialize() override; - bool train(const Toolkit::IFeatureVectorSet& featureVectorSet) override; - bool classify(const Toolkit::IFeatureVector& featureVector, double& classId, Toolkit::IVector& distance, - Toolkit::IVector& probability) override; - XML::IXMLNode* saveConfig() override { return nullptr; } - bool loadConfig(XML::IXMLNode* /*configurationNode*/) override { return true; } - size_t getNProbabilities() override { return 1; } - size_t getNDistances() override { return 1; } - - _IsDerivedFromClass_Final_(CAlgorithmClassifier, OVP_ClassId_Algorithm_ClassifierNULL) - }; +public: - class CAlgorithmClassifierNULLDesc final : public Toolkit::CAlgorithmClassifierDesc - { - public: - void release() override { } - CString getName() const override { return CString("NULL Classifier (does nothing)"); } - CString getAuthorName() const override { return CString("Yann Renard"); } - CString getAuthorCompanyName() const override { return CString("INRIA"); } - CString getShortDescription() const override { return CString(""); } - CString getDetailedDescription() const override { return CString(""); } - CString getCategory() const override { return CString("Samples"); } - CString getVersion() const override { return CString("1.0"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_Algorithm_ClassifierNULL; } - IPluginObject* create() override { return new CAlgorithmClassifierNULL; } + CAlgorithmClassifierNULL() { } + bool initialize() override; + bool train(const Toolkit::IFeatureVectorSet& featureVectorSet) override; + bool classify(const Toolkit::IFeatureVector& featureVector, double& classId, Toolkit::IVector& distance, Toolkit::IVector& probability) override; + XML::IXMLNode* saveConfig() override { return nullptr; } + bool loadConfig(XML::IXMLNode* /*configurationNode*/) override { return true; } + size_t getNProbabilities() override { return 1; } + size_t getNDistances() override { return 1; } - bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override - { - CAlgorithmClassifierDesc::getAlgorithmPrototype(prototype); - prototype.addInputParameter(OVP_Algorithm_ClassifierNULL_InputParameterId_Parameter1, "Parameter 1", Kernel::ParameterType_Boolean); - prototype.addInputParameter(OVP_Algorithm_ClassifierNULL_InputParameterId_Parameter2, "Parameter 2", Kernel::ParameterType_Float); - prototype.addInputParameter( - OVP_Algorithm_ClassifierNULL_InputParameterId_Parameter3, "Parameter 3", Kernel::ParameterType_Enumeration, OV_TypeId_Stimulation); - return true; - } + _IsDerivedFromClass_Final_(CAlgorithmClassifier, OVP_ClassId_Algorithm_ClassifierNULL) +}; - _IsDerivedFromClass_Final_(CAlgorithmClassifierDesc, OVP_ClassId_Algorithm_ClassifierNULLDesc) - }; - } // namespace Classification - } // namespace Plugins +class CAlgorithmClassifierNULLDesc final : public Toolkit::CAlgorithmClassifierDesc +{ +public: + void release() override { } + CString getName() const override { return CString("NULL Classifier (does nothing)"); } + CString getAuthorName() const override { return CString("Yann Renard"); } + CString getAuthorCompanyName() const override { return CString("INRIA"); } + CString getShortDescription() const override { return CString(""); } + CString getDetailedDescription() const override { return CString(""); } + CString getCategory() const override { return CString("Samples"); } + CString getVersion() const override { return CString("1.0"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_Algorithm_ClassifierNULL; } + IPluginObject* create() override { return new CAlgorithmClassifierNULL; } + + bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override + { + CAlgorithmClassifierDesc::getAlgorithmPrototype(prototype); + prototype.addInputParameter(OVP_Algorithm_ClassifierNULL_InputParameterId_Parameter1, "Parameter 1", Kernel::ParameterType_Boolean); + prototype.addInputParameter(OVP_Algorithm_ClassifierNULL_InputParameterId_Parameter2, "Parameter 2", Kernel::ParameterType_Float); + prototype.addInputParameter(OVP_Algorithm_ClassifierNULL_InputParameterId_Parameter3, "Parameter 3", Kernel::ParameterType_Enumeration, + OV_TypeId_Stimulation); + return true; + } + + _IsDerivedFromClass_Final_(CAlgorithmClassifierDesc, OVP_ClassId_Algorithm_ClassifierNULLDesc) +}; +} // namespace Classification +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/classification/src/algorithms/ovpCAlgorithmClassifierOneVsAll.cpp b/plugins/processing/classification/src/algorithms/ovpCAlgorithmClassifierOneVsAll.cpp index 032edfe0d328842845ef40e81bb8f7365941c795..797479282cdf1f2fc208052f52cd5437a206f440 100755 --- a/plugins/processing/classification/src/algorithms/ovpCAlgorithmClassifierOneVsAll.cpp +++ b/plugins/processing/classification/src/algorithms/ovpCAlgorithmClassifierOneVsAll.cpp @@ -5,15 +5,14 @@ #include <utility> #include <iostream> -namespace -{ - const char* const TYPE_NODE_NAME = "OneVsAll"; - const char* const SUB_CLASSIFIER_IDENTIFIER_NODE_NAME = "SubClassifierIdentifier"; - const char* const ALGORITHM_ID_ATTRIBUTE = "algorithm-id"; - const char* const SUB_CLASSIFIER_COUNT_NODE_NAME = "SubClassifierCount"; - const char* const SUB_CLASSIFIERS_NODE_NAME = "SubClassifiers"; - //const char* const SUB_CLASSIFIER_NODE_NAME = "SubClassifier"; -} // namespace +namespace { +const char* const TYPE_NODE_NAME = "OneVsAll"; +const char* const SUB_CLASSIFIER_IDENTIFIER_NODE_NAME = "SubClassifierIdentifier"; +const char* const ALGORITHM_ID_ATTRIBUTE = "algorithm-id"; +const char* const SUB_CLASSIFIER_COUNT_NODE_NAME = "SubClassifierCount"; +const char* const SUB_CLASSIFIERS_NODE_NAME = "SubClassifiers"; +//const char* const SUB_CLASSIFIER_NODE_NAME = "SubClassifier"; +} // namespace using namespace OpenViBE; using namespace /*OpenViBE::*/Kernel; @@ -198,8 +197,7 @@ bool CAlgorithmClassifierOneVsAll::addNewClassifierAtBack() const CIdentifier subClassifierAlgorithm = this->getAlgorithmManager().createAlgorithm(this->m_subClassifierAlgorithmID); OV_ERROR_UNLESS_KRF(subClassifierAlgorithm != OV_UndefinedIdentifier, - "Invalid classifier identifier [" << this->m_subClassifierAlgorithmID.str() << "]", - ErrorType::BadConfig); + "Invalid classifier identifier [" << this->m_subClassifierAlgorithmID.str() << "]", ErrorType::BadConfig); IAlgorithmProxy* subClassifier = &this->getAlgorithmManager().getAlgorithm(subClassifierAlgorithm); subClassifier->initialize(); @@ -317,8 +315,7 @@ bool CAlgorithmClassifierOneVsAll::setSubClassifierIdentifier(const CIdentifier& m_fAlgorithmComparison = getClassificationComparisonFunction(id); OV_ERROR_UNLESS_KRF(m_fAlgorithmComparison != nullptr, - "No comparison function found for classifier [" << m_subClassifierAlgorithmID.str() << "]", - ErrorType::ResourceNotFound); + "No comparison function found for classifier [" << m_subClassifierAlgorithmID.str() << "]", ErrorType::ResourceNotFound); return true; } diff --git a/plugins/processing/classification/src/algorithms/ovpCAlgorithmClassifierOneVsAll.h b/plugins/processing/classification/src/algorithms/ovpCAlgorithmClassifierOneVsAll.h index 5251339089c68cfd284bcae207c1c1a64baf4a4f..16ce9ded0ed582d8d0d32bd59205f7d53bed3aa3 100644 --- a/plugins/processing/classification/src/algorithms/ovpCAlgorithmClassifierOneVsAll.h +++ b/plugins/processing/classification/src/algorithms/ovpCAlgorithmClassifierOneVsAll.h @@ -9,68 +9,63 @@ #include <vector> -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace Classification { +class CAlgorithmClassifierOneVsAll final : public Toolkit::CAlgorithmPairingStrategy { - namespace Plugins - { - namespace Classification - { - class CAlgorithmClassifierOneVsAll final : public Toolkit::CAlgorithmPairingStrategy - { - public: - bool initialize() override; - bool uninitialize() override; - bool train(const Toolkit::IFeatureVectorSet& dataset) override; - bool classify(const Toolkit::IFeatureVector& sample, double& classId, Toolkit::IVector& distance, - Toolkit::IVector& probability) override; - bool designArchitecture(const CIdentifier& id, const size_t nClass) override; - XML::IXMLNode* saveConfig() override; - bool loadConfig(XML::IXMLNode* configNode) override; - size_t getNProbabilities() override { return m_subClassifiers.size(); } - size_t getNDistances() override; - - _IsDerivedFromClass_Final_(Toolkit::CAlgorithmPairingStrategy, OVP_ClassId_Algorithm_ClassifierOneVsAll) +public: + bool initialize() override; + bool uninitialize() override; + bool train(const Toolkit::IFeatureVectorSet& dataset) override; + bool classify(const Toolkit::IFeatureVector& sample, double& classId, Toolkit::IVector& distance, Toolkit::IVector& probability) override; + bool designArchitecture(const CIdentifier& id, const size_t nClass) override; + XML::IXMLNode* saveConfig() override; + bool loadConfig(XML::IXMLNode* configNode) override; + size_t getNProbabilities() override { return m_subClassifiers.size(); } + size_t getNDistances() override; + _IsDerivedFromClass_Final_(Toolkit::CAlgorithmPairingStrategy, OVP_ClassId_Algorithm_ClassifierOneVsAll) - private: - static XML::IXMLNode* getClassifierConfig(Kernel::IAlgorithmProxy* classifier); - bool addNewClassifierAtBack(); - void removeClassifierAtBack(); - bool setSubClassifierIdentifier(const CIdentifier& id); - size_t getClassCount() const { return m_subClassifiers.size(); } - bool loadSubClassifierConfig(XML::IXMLNode* node); +private: + static XML::IXMLNode* getClassifierConfig(Kernel::IAlgorithmProxy* classifier); + bool addNewClassifierAtBack(); + void removeClassifierAtBack(); + bool setSubClassifierIdentifier(const CIdentifier& id); + size_t getClassCount() const { return m_subClassifiers.size(); } - std::vector<Kernel::IAlgorithmProxy*> m_subClassifiers; - fClassifierComparison m_fAlgorithmComparison = nullptr; - }; + bool loadSubClassifierConfig(XML::IXMLNode* node); - class CAlgorithmClassifierOneVsAllDesc final : public Toolkit::CAlgorithmPairingStrategyDesc - { - public: - void release() override { } - CString getName() const override { return CString("OneVsAll pairing classifier"); } - CString getAuthorName() const override { return CString("Guillaume Serriere"); } - CString getAuthorCompanyName() const override { return CString("INRIA/Loria"); } - CString getShortDescription() const override { return CString(""); } - CString getDetailedDescription() const override { return CString(""); } - CString getCategory() const override { return CString(""); } - CString getVersion() const override { return CString("0.1"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_Algorithm_ClassifierOneVsAll; } - IPluginObject* create() override { return new CAlgorithmClassifierOneVsAll; } + std::vector<Kernel::IAlgorithmProxy*> m_subClassifiers; + fClassifierComparison m_fAlgorithmComparison = nullptr; +}; - bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override - { - CAlgorithmPairingStrategyDesc::getAlgorithmPrototype(prototype); +class CAlgorithmClassifierOneVsAllDesc final : public Toolkit::CAlgorithmPairingStrategyDesc +{ +public: + void release() override { } + CString getName() const override { return CString("OneVsAll pairing classifier"); } + CString getAuthorName() const override { return CString("Guillaume Serriere"); } + CString getAuthorCompanyName() const override { return CString("INRIA/Loria"); } + CString getShortDescription() const override { return CString(""); } + CString getDetailedDescription() const override { return CString(""); } + CString getCategory() const override { return CString(""); } + CString getVersion() const override { return CString("0.1"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_Algorithm_ClassifierOneVsAll; } + IPluginObject* create() override { return new CAlgorithmClassifierOneVsAll; } - return true; - } + bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override + { + CAlgorithmPairingStrategyDesc::getAlgorithmPrototype(prototype); + return true; + } - _IsDerivedFromClass_Final_(CAlgorithmPairingStrategyDesc, OVP_ClassId_Algorithm_ClassifierOneVsAllDesc) - }; - } // namespace Classification - } // namespace Plugins + _IsDerivedFromClass_Final_(CAlgorithmPairingStrategyDesc, OVP_ClassId_Algorithm_ClassifierOneVsAllDesc) +}; +} // namespace Classification +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/classification/src/algorithms/ovpCAlgorithmClassifierOneVsOne.cpp b/plugins/processing/classification/src/algorithms/ovpCAlgorithmClassifierOneVsOne.cpp index 789223258344b989ee066d2e9c81ee68671ec4e1..7fa3132872327b0a107d02adc7e31356ffd5028c 100755 --- a/plugins/processing/classification/src/algorithms/ovpCAlgorithmClassifierOneVsOne.cpp +++ b/plugins/processing/classification/src/algorithms/ovpCAlgorithmClassifierOneVsOne.cpp @@ -7,21 +7,20 @@ #include <utility> #include <iostream> -namespace -{ - const char* const TYPE_NODE_NAME = "OneVsOne"; - const char* const SUB_CLASSIFIER_IDENTIFIER_NODE_NAME = "SubClassifierIdentifier"; - const char* const PAIRWISE_DECISION_NAME = "PairwiseDecision"; - const char* const ALGORITHM_ID_ATTRIBUTE = "algorithm-id"; - const char* const SUB_CLASSIFIER_COUNT_NODE_NAME = "SubClassifierCount"; - const char* const SUB_CLASSIFIERS_NODE_NAME = "SubClassifiers"; - const char* const SUB_CLASSIFIER_NODE_NAME = "SubClassifier"; - const char* const FIRST_CLASS_ATRRIBUTE_NAME = "first-class"; - const char* const SECOND_CLASS_ATTRIBUTE_NAME = "second-class"; - - //This map is used to record the decision strategies available for each algorithm - //std::map<uint64_t, OpenViBE::CIdentifier> g_oDecisionMap; -} // namespace +namespace { +const char* const TYPE_NODE_NAME = "OneVsOne"; +const char* const SUB_CLASSIFIER_IDENTIFIER_NODE_NAME = "SubClassifierIdentifier"; +const char* const PAIRWISE_DECISION_NAME = "PairwiseDecision"; +const char* const ALGORITHM_ID_ATTRIBUTE = "algorithm-id"; +const char* const SUB_CLASSIFIER_COUNT_NODE_NAME = "SubClassifierCount"; +const char* const SUB_CLASSIFIERS_NODE_NAME = "SubClassifiers"; +const char* const SUB_CLASSIFIER_NODE_NAME = "SubClassifier"; +const char* const FIRST_CLASS_ATRRIBUTE_NAME = "first-class"; +const char* const SECOND_CLASS_ATTRIBUTE_NAME = "second-class"; + +//This map is used to record the decision strategies available for each algorithm +//std::map<uint64_t, OpenViBE::CIdentifier> g_oDecisionMap; +} // namespace extern const char* const CLASSIFIER_ROOT; @@ -96,15 +95,14 @@ bool CAlgorithmClassifierOneVsOne::train(const IFeatureVectorSet& dataset) OV_ERROR_UNLESS_KRF(m_decisionStrategyAlgorithm->initialize(), "Failed to unitialize decision strategy algorithm", ErrorType::Internal); - TParameterHandler<CIdentifier *> ip_classificationAlgorithm( + TParameterHandler<CIdentifier*> ip_classificationAlgorithm( m_decisionStrategyAlgorithm->getInputParameter(OVP_Algorithm_Classifier_Pairwise_InputParameterId_AlgorithmIdentifier)); ip_classificationAlgorithm = &m_subClassifierAlgorithmID; TParameterHandler<uint64_t> ip_classCount(m_decisionStrategyAlgorithm->getInputParameter(OVP_Algorithm_Classifier_Pairwise_InputParameter_ClassCount)); ip_classCount = m_nClasses; OV_ERROR_UNLESS_KRF(m_decisionStrategyAlgorithm->process(OVP_Algorithm_Classifier_Pairwise_InputTriggerId_Parameterize), - "Failed to run decision strategy algorithm", - ErrorType::Internal); + "Failed to run decision strategy algorithm", ErrorType::Internal); OV_ERROR_UNLESS_KRF(this->uninitializeExtraParameterMechanism(), "Failed to uninitialize extra parameters", ErrorType::Internal); @@ -209,7 +207,7 @@ bool CAlgorithmClassifierOneVsOne::classify(const IFeatureVector& sample, double // } // std::cout << std::endl; - TParameterHandler<std::vector<classification_info_t> *> ip_infos( + TParameterHandler<std::vector<classification_info_t>*> ip_infos( m_decisionStrategyAlgorithm->getInputParameter(OVP_Algorithm_Classifier_Pairwise_InputParameter_ClassificationOutputs)); ip_infos = &classificationList; @@ -379,7 +377,7 @@ bool CAlgorithmClassifierOneVsOne::loadConfig(XML::IXMLNode* configNode) TParameterHandler<XML::IXMLNode*> ip_config(m_decisionStrategyAlgorithm->getInputParameter(OVP_Algorithm_Classifier_Pairwise_InputParameterId_Config)); ip_config = tempNode->getChild(0); - TParameterHandler<CIdentifier *> ip_algorithm( + TParameterHandler<CIdentifier*> ip_algorithm( m_decisionStrategyAlgorithm->getInputParameter(OVP_Algorithm_Classifier_Pairwise_InputParameterId_AlgorithmIdentifier)); ip_algorithm = &algorithmID; diff --git a/plugins/processing/classification/src/algorithms/ovpCAlgorithmClassifierOneVsOne.h b/plugins/processing/classification/src/algorithms/ovpCAlgorithmClassifierOneVsOne.h index 8cd400b0bfb733dbedd160fee76f4a17c74e358c..3df3c42cc1c8f4c7e1b9a1c60725b16920f6dffc 100755 --- a/plugins/processing/classification/src/algorithms/ovpCAlgorithmClassifierOneVsOne.h +++ b/plugins/processing/classification/src/algorithms/ovpCAlgorithmClassifierOneVsOne.h @@ -8,93 +8,89 @@ #include <map> -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace Classification { +//The aim of this structure is to record informations returned by the sub-classifier. They will be used by +// pairwise decision algorithms to compute probability vector. +// Should be use only by OneVsOne and pairwise decision algorithm +typedef struct { - namespace Plugins + double firstClass; + double secondClass; + double classLabel; + //This output is probabilist + IMatrix* classificationValue; +} classification_info_t; + + +class CAlgorithmClassifierOneVsOne final : public Toolkit::CAlgorithmPairingStrategy +{ +public: + bool initialize() override; + bool uninitialize() override; + bool train(const Toolkit::IFeatureVectorSet& dataset) override; + bool classify(const Toolkit::IFeatureVector& sample, double& classId, Toolkit::IVector& distance, Toolkit::IVector& probability) override; + bool designArchitecture(const CIdentifier& id, const size_t classCount) override; + XML::IXMLNode* saveConfig() override; + bool loadConfig(XML::IXMLNode* configNode) override; + size_t getNProbabilities() override { return m_nClasses; } + size_t getNDistances() override { return 0; } + + _IsDerivedFromClass_Final_(Toolkit::CAlgorithmPairingStrategy, OVP_ClassId_Algorithm_ClassifierOneVsOne) + +protected: + + bool createSubClassifiers(); + +private: + size_t m_nClasses = 0; + size_t m_nSubClassifiers = 0; + + std::map<std::pair<size_t, size_t>, Kernel::IAlgorithmProxy*> m_subClassifiers; + fClassifierComparison m_algorithmComparison = nullptr; + + Kernel::IAlgorithmProxy* m_decisionStrategyAlgorithm = nullptr; + CIdentifier m_pairwiseDecisionID = OV_UndefinedIdentifier; + + static XML::IXMLNode* getClassifierConfig(double firstClass, double secondClass, Kernel::IAlgorithmProxy* subClassifier); + XML::IXMLNode* getPairwiseDecisionConfiguration() const; + + // size_t getClassCount() const; + + bool loadSubClassifierConfig(XML::IXMLNode* node); + + // SSubClassifierDescriptor& getSubClassifierDescriptor(const size_t FirstClass, const size_t SecondClass); + bool setSubClassifierIdentifier(const CIdentifier& id); +}; + +class CAlgorithmClassifierOneVsOneDesc final : public Toolkit::CAlgorithmPairingStrategyDesc +{ +public: + void release() override { } + CString getName() const override { return CString("OneVsOne pairing classifier"); } + CString getAuthorName() const override { return CString("Guillaume Serriere"); } + CString getAuthorCompanyName() const override { return CString("INRIA/Loria"); } + CString getShortDescription() const override { return CString(""); } + CString getDetailedDescription() const override { return CString(""); } + CString getCategory() const override { return CString(""); } + CString getVersion() const override { return CString("0.2"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_Algorithm_ClassifierOneVsOne; } + IPluginObject* create() override { return new CAlgorithmClassifierOneVsOne; } + + bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override { - namespace Classification - { - //The aim of this structure is to record informations returned by the sub-classifier. They will be used by - // pairwise decision algorithms to compute probability vector. - // Should be use only by OneVsOne and pairwise decision algorithm - typedef struct - { - double firstClass; - double secondClass; - double classLabel; - //This output is probabilist - IMatrix* classificationValue; - } classification_info_t; - - - class CAlgorithmClassifierOneVsOne final : public Toolkit::CAlgorithmPairingStrategy - { - public: - bool initialize() override; - bool uninitialize() override; - bool train(const Toolkit::IFeatureVectorSet& dataset) override; - bool classify(const Toolkit::IFeatureVector& sample, double& classId, Toolkit::IVector& distance, - Toolkit::IVector& probability) override; - bool designArchitecture(const CIdentifier& id, const size_t classCount) override; - XML::IXMLNode* saveConfig() override; - bool loadConfig(XML::IXMLNode* configNode) override; - size_t getNProbabilities() override { return m_nClasses; } - size_t getNDistances() override { return 0; } - - _IsDerivedFromClass_Final_(Toolkit::CAlgorithmPairingStrategy, OVP_ClassId_Algorithm_ClassifierOneVsOne) - - protected: - - bool createSubClassifiers(); - - private: - size_t m_nClasses = 0; - size_t m_nSubClassifiers = 0; - - std::map<std::pair<size_t, size_t>, Kernel::IAlgorithmProxy*> m_subClassifiers; - fClassifierComparison m_algorithmComparison = nullptr; - - Kernel::IAlgorithmProxy* m_decisionStrategyAlgorithm = nullptr; - CIdentifier m_pairwiseDecisionID = OV_UndefinedIdentifier; - - static XML::IXMLNode* getClassifierConfig(double firstClass, double secondClass, Kernel::IAlgorithmProxy* subClassifier); - XML::IXMLNode* getPairwiseDecisionConfiguration() const; - - // size_t getClassCount() const; - - bool loadSubClassifierConfig(XML::IXMLNode* node); - - // SSubClassifierDescriptor& getSubClassifierDescriptor(const size_t FirstClass, const size_t SecondClass); - bool setSubClassifierIdentifier(const CIdentifier& id); - }; - - class CAlgorithmClassifierOneVsOneDesc final : public Toolkit::CAlgorithmPairingStrategyDesc - { - public: - void release() override { } - CString getName() const override { return CString("OneVsOne pairing classifier"); } - CString getAuthorName() const override { return CString("Guillaume Serriere"); } - CString getAuthorCompanyName() const override { return CString("INRIA/Loria"); } - CString getShortDescription() const override { return CString(""); } - CString getDetailedDescription() const override { return CString(""); } - CString getCategory() const override { return CString(""); } - CString getVersion() const override { return CString("0.2"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_Algorithm_ClassifierOneVsOne; } - IPluginObject* create() override { return new CAlgorithmClassifierOneVsOne; } - - bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override - { - CAlgorithmPairingStrategyDesc::getAlgorithmPrototype(prototype); - prototype.addInputParameter(OVP_Algorithm_OneVsOneStrategy_InputParameterId_DecisionType, "Pairwise Decision Strategy", - Kernel::ParameterType_Enumeration, OVP_TypeId_ClassificationPairwiseStrategy); - return true; - } - - _IsDerivedFromClass_Final_(CAlgorithmPairingStrategyDesc, OVP_ClassId_Algorithm_ClassifierOneVsOneDesc) - }; - } // namespace Classification - } // namespace Plugins + CAlgorithmPairingStrategyDesc::getAlgorithmPrototype(prototype); + prototype.addInputParameter(OVP_Algorithm_OneVsOneStrategy_InputParameterId_DecisionType, "Pairwise Decision Strategy", + Kernel::ParameterType_Enumeration, OVP_TypeId_ClassificationPairwiseStrategy); + return true; + } + + _IsDerivedFromClass_Final_(CAlgorithmPairingStrategyDesc, OVP_ClassId_Algorithm_ClassifierOneVsOneDesc) +}; +} // namespace Classification +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/classification/src/algorithms/ovpCAlgorithmConditionedCovariance.cpp b/plugins/processing/classification/src/algorithms/ovpCAlgorithmConditionedCovariance.cpp index f31281b05a6a20c23fbef476eca96a37ba7db947..1cb24c8684c1b33365681d766af65b9277e12e4b 100644 --- a/plugins/processing/classification/src/algorithms/ovpCAlgorithmConditionedCovariance.cpp +++ b/plugins/processing/classification/src/algorithms/ovpCAlgorithmConditionedCovariance.cpp @@ -52,20 +52,16 @@ bool CAlgorithmConditionedCovariance::process() TParameterHandler<IMatrix*> op_covMatrix(getOutputParameter(OVP_Algorithm_ConditionedCovariance_OutputParameterId_CovarianceMatrix)); double shrinkage = ip_shrinkage; - OV_ERROR_UNLESS_KRF(shrinkage <= 1.0, "Invalid shrinkage value " << shrinkage << "(expected value <= 1.0)", - ErrorType::BadConfig); + OV_ERROR_UNLESS_KRF(shrinkage <= 1.0, "Invalid shrinkage value " << shrinkage << "(expected value <= 1.0)", ErrorType::BadConfig); OV_ERROR_UNLESS_KRF(ip_sample->getDimensionCount() == 2, - "Invalid dimension count for vector set " << ip_sample->getDimensionCount() << "(expected value = 2)", - ErrorType::BadInput); + "Invalid dimension count for vector set " << ip_sample->getDimensionCount() << "(expected value = 2)", ErrorType::BadInput); const size_t nRows = ip_sample->getDimensionSize(0); const size_t nCols = ip_sample->getDimensionSize(1); - OV_ERROR_UNLESS_KRF(nRows >= 1 && nCols >= 1, - "Invalid input matrix [" << nRows << "x" << nCols << "] (expected at least 1x1 size)", - ErrorType::BadInput); + OV_ERROR_UNLESS_KRF(nRows >= 1 && nCols >= 1, "Invalid input matrix [" << nRows << "x" << nCols << "] (expected at least 1x1 size)", ErrorType::BadInput); const double* buffer = ip_sample->getBuffer(); diff --git a/plugins/processing/classification/src/algorithms/ovpCAlgorithmConditionedCovariance.h b/plugins/processing/classification/src/algorithms/ovpCAlgorithmConditionedCovariance.h index aa480a14b30001a2ac894bdbeadcc4d2b8daab62..b80bd4d6bd0b5c7033b38a9c39746e57fddcedc0 100644 --- a/plugins/processing/classification/src/algorithms/ovpCAlgorithmConditionedCovariance.h +++ b/plugins/processing/classification/src/algorithms/ovpCAlgorithmConditionedCovariance.h @@ -8,72 +8,65 @@ #include <Eigen/Dense> -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace Classification { +class CAlgorithmConditionedCovariance final : virtual public Toolkit::TAlgorithm<IAlgorithm> { - namespace Plugins + typedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> MatrixXdRowMajor; + +public: + void release() override { delete this; } + bool initialize() override; + bool uninitialize() override { return true; } + bool process() override; + + _IsDerivedFromClass_Final_(Toolkit::TAlgorithm<IAlgorithm>, OVP_ClassId_Algorithm_ConditionedCovariance) + +protected: + // Debug method. Prints the matrix to the logManager. May be disabled in implementation. + static void dumpMatrix(Kernel::ILogManager& mgr, const MatrixXdRowMajor& mat, const CString& desc); +}; + +class CAlgorithmConditionedCovarianceDesc final : virtual public IAlgorithmDesc +{ +public: + void release() override { } + CString getName() const override { return CString("Conditioned Covariance"); } + CString getAuthorName() const override { return CString("Jussi T. Lindgren"); } + CString getAuthorCompanyName() const override { return CString("Inria"); } + CString getShortDescription() const override { return CString("Computes covariance with shrinkage."); } + + CString getDetailedDescription() const override { - namespace Classification - { - class CAlgorithmConditionedCovariance final : virtual public Toolkit::TAlgorithm<IAlgorithm> - { - typedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> MatrixXdRowMajor; - - public: - void release() override { delete this; } - bool initialize() override; - bool uninitialize() override { return true; } - bool process() override; - - _IsDerivedFromClass_Final_(Toolkit::TAlgorithm<IAlgorithm>, OVP_ClassId_Algorithm_ConditionedCovariance) - - protected: - // Debug method. Prints the matrix to the logManager. May be disabled in implementation. - static void dumpMatrix(Kernel::ILogManager& mgr, const MatrixXdRowMajor& mat, const CString& desc); - }; - - class CAlgorithmConditionedCovarianceDesc final : virtual public IAlgorithmDesc - { - public: - void release() override { } - CString getName() const override { return CString("Conditioned Covariance"); } - CString getAuthorName() const override { return CString("Jussi T. Lindgren"); } - CString getAuthorCompanyName() const override { return CString("Inria"); } - CString getShortDescription() const override { return CString("Computes covariance with shrinkage."); } - - CString getDetailedDescription() const override - { - return CString( - "Shrinkage: {<0 = auto-estimate, [0,1] balance between prior and sample cov}. The conditioned covariance matrix may allow better accuracies with models that rely on inverting the cov matrix, in cases where the regular cov matrix is close to singular."); - } - - CString getCategory() const override { return CString(""); } - CString getVersion() const override { return CString("1.0"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_Algorithm_ConditionedCovariance; } - IPluginObject* create() override { return new CAlgorithmConditionedCovariance; } - - bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override - { - prototype.addInputParameter( - OVP_Algorithm_ConditionedCovariance_InputParameterId_Shrinkage, "Shrinkage (-1 == auto)", Kernel::ParameterType_Float); - prototype.addInputParameter( - OVP_Algorithm_ConditionedCovariance_InputParameterId_FeatureVectorSet, "Feature vectors", Kernel::ParameterType_Matrix); - - // The algorithm returns these outputs - prototype.addOutputParameter( - OVP_Algorithm_ConditionedCovariance_OutputParameterId_Mean, "Mean vector", Kernel::ParameterType_Matrix); - prototype.addOutputParameter( - OVP_Algorithm_ConditionedCovariance_OutputParameterId_CovarianceMatrix, "Covariance matrix", Kernel::ParameterType_Matrix); - - return true; - } - - _IsDerivedFromClass_Final_(IAlgorithmDesc, OVP_ClassId_Algorithm_ConditionedCovarianceDesc) - }; - } // namespace Classification - } // namespace Plugins + return CString( + "Shrinkage: {<0 = auto-estimate, [0,1] balance between prior and sample cov}. The conditioned covariance matrix may allow better accuracies with models that rely on inverting the cov matrix, in cases where the regular cov matrix is close to singular."); + } + + CString getCategory() const override { return CString(""); } + CString getVersion() const override { return CString("1.0"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_Algorithm_ConditionedCovariance; } + IPluginObject* create() override { return new CAlgorithmConditionedCovariance; } + + bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override + { + prototype.addInputParameter(OVP_Algorithm_ConditionedCovariance_InputParameterId_Shrinkage, "Shrinkage (-1 == auto)", Kernel::ParameterType_Float); + prototype.addInputParameter(OVP_Algorithm_ConditionedCovariance_InputParameterId_FeatureVectorSet, "Feature vectors", Kernel::ParameterType_Matrix); + + // The algorithm returns these outputs + prototype.addOutputParameter(OVP_Algorithm_ConditionedCovariance_OutputParameterId_Mean, "Mean vector", Kernel::ParameterType_Matrix); + prototype.addOutputParameter(OVP_Algorithm_ConditionedCovariance_OutputParameterId_CovarianceMatrix, "Covariance matrix", Kernel::ParameterType_Matrix); + + return true; + } + + _IsDerivedFromClass_Final_(IAlgorithmDesc, OVP_ClassId_Algorithm_ConditionedCovarianceDesc) +}; +} // namespace Classification +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/classification/src/algorithms/ovpCAlgorithmLDADiscriminantFunction.cpp b/plugins/processing/classification/src/algorithms/ovpCAlgorithmLDADiscriminantFunction.cpp index 69d19c93f124d9cb924000a566900a01848a8813..6960f2b679c928e547d3df7ba5923fcdec59f413 100644 --- a/plugins/processing/classification/src/algorithms/ovpCAlgorithmLDADiscriminantFunction.cpp +++ b/plugins/processing/classification/src/algorithms/ovpCAlgorithmLDADiscriminantFunction.cpp @@ -14,12 +14,11 @@ using namespace /*OpenViBE::*/Toolkit; using namespace Eigen; -namespace -{ - const char* const BASE_NODE_NAME = "Class-config"; - const char* const WEIGHT_NODE_NAME = "Weights"; - const char* const BIAS_NODE_NAME = "Bias"; -} // namespace +namespace { +const char* const BASE_NODE_NAME = "Class-config"; +const char* const WEIGHT_NODE_NAME = "Weights"; +const char* const BIAS_NODE_NAME = "Bias"; +} // namespace bool CAlgorithmLDADiscriminantFunction::loadConfig(const XML::IXMLNode* configuration) { diff --git a/plugins/processing/classification/src/algorithms/ovpCAlgorithmLDADiscriminantFunction.h b/plugins/processing/classification/src/algorithms/ovpCAlgorithmLDADiscriminantFunction.h index 587ec21051b861d6977d8ca735f27ee6546b863d..1b8789d0eaf938ebbee2725fb730e7b8bec6074e 100644 --- a/plugins/processing/classification/src/algorithms/ovpCAlgorithmLDADiscriminantFunction.h +++ b/plugins/processing/classification/src/algorithms/ovpCAlgorithmLDADiscriminantFunction.h @@ -10,38 +10,35 @@ #include "ovpCAlgorithmClassifierLDA.h" #include <xml/IXMLNode.h> -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace Classification { +//The purpose of this class is to compute the "membership" of a vector +class CAlgorithmLDADiscriminantFunction { - namespace Plugins - { - namespace Classification - { - //The purpose of this class is to compute the "membership" of a vector - class CAlgorithmLDADiscriminantFunction - { - public: - CAlgorithmLDADiscriminantFunction() {} - - void setWeight(const Eigen::VectorXd& weigth) { m_weight = weigth; } - void setBias(const double bias) { m_bias = bias; } - - //Return the class membership of the feature vector - double getValue(const Eigen::VectorXd& featureVector) { return (m_weight.transpose() * featureVector)(0) + m_bias; } - size_t getNWeight() const { return m_weight.size(); } - - - bool loadConfig(const XML::IXMLNode* configuration); - XML::IXMLNode* getConfiguration(); - - const Eigen::VectorXd& getWeight() const { return m_weight; } - double getBias() const { return m_bias; } - - private: - double m_bias = 0; - Eigen::VectorXd m_weight; - }; - } // namespace Classification - } // namespace Plugins +public: + CAlgorithmLDADiscriminantFunction() {} + + void setWeight(const Eigen::VectorXd& weigth) { m_weight = weigth; } + void setBias(const double bias) { m_bias = bias; } + + //Return the class membership of the feature vector + double getValue(const Eigen::VectorXd& featureVector) { return (m_weight.transpose() * featureVector)(0) + m_bias; } + size_t getNWeight() const { return m_weight.size(); } + + + bool loadConfig(const XML::IXMLNode* configuration); + XML::IXMLNode* getConfiguration(); + + const Eigen::VectorXd& getWeight() const { return m_weight; } + double getBias() const { return m_bias; } + +private: + double m_bias = 0; + Eigen::VectorXd m_weight; +}; +} // namespace Classification +} // namespace Plugins } // namespace OpenViBE #endif diff --git a/plugins/processing/classification/src/algorithms/ovpCAlgorithmPairwiseDecision.cpp b/plugins/processing/classification/src/algorithms/ovpCAlgorithmPairwiseDecision.cpp index f86d8422acad43f51c62b99db4aeae3d6ed567d7..20c3bf21556e4dc8b7eedaf8da96c49e64881f35 100644 --- a/plugins/processing/classification/src/algorithms/ovpCAlgorithmPairwiseDecision.cpp +++ b/plugins/processing/classification/src/algorithms/ovpCAlgorithmPairwiseDecision.cpp @@ -13,10 +13,10 @@ bool CAlgorithmPairwiseDecision::process() // @note there is essentially no test that these are called in correct order. Caller be careful! if (this->isInputTriggerActive(OVP_Algorithm_Classifier_Pairwise_InputTriggerId_Compute)) { - TParameterHandler<std::vector<classification_info_t> *> ip_classifications = this->getInputParameter( + TParameterHandler<std::vector<classification_info_t>*> ip_classifications = this->getInputParameter( OVP_Algorithm_Classifier_Pairwise_InputParameter_ClassificationOutputs); TParameterHandler<IMatrix*> op_probability = this->getOutputParameter(OVP_Algorithm_Classifier_OutputParameter_ProbabilityVector); - return this->compute(*static_cast<std::vector<classification_info_t> *>(ip_classifications), static_cast<IMatrix*>(op_probability)); + return this->compute(*static_cast<std::vector<classification_info_t>*>(ip_classifications), static_cast<IMatrix*>(op_probability)); } if (this->isInputTriggerActive(OVP_Algorithm_Classifier_Pairwise_InputTriggerId_SaveConfig)) { diff --git a/plugins/processing/classification/src/algorithms/ovpCAlgorithmPairwiseDecision.h b/plugins/processing/classification/src/algorithms/ovpCAlgorithmPairwiseDecision.h index dd885b075c81df5e72255afde48b77d14ec4105e..0141655d3b42db6a785f51bcd30e0ee305548525 100644 --- a/plugins/processing/classification/src/algorithms/ovpCAlgorithmPairwiseDecision.h +++ b/plugins/processing/classification/src/algorithms/ovpCAlgorithmPairwiseDecision.h @@ -7,62 +7,56 @@ #include <xml/IXMLNode.h> #include "ovpCAlgorithmClassifierOneVsOne.h" -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace Classification { +/** + * @brief The CAlgorithmPairwiseDecision class + * This is the default class for every decision usable with the One Vs One pairwise strategy. + */ +class CAlgorithmPairwiseDecision : virtual public Toolkit::TAlgorithm<IAlgorithm> { - namespace Plugins - { - namespace Classification - { - /** - * @brief The CAlgorithmPairwiseDecision class - * This is the default class for every decision usable with the One Vs One pairwise strategy. - */ - class CAlgorithmPairwiseDecision : virtual public Toolkit::TAlgorithm<IAlgorithm> - { - public: - void release() override { delete this; } - bool initialize() override = 0; - bool uninitialize() override = 0; - - virtual bool parameterize() = 0; - - virtual bool compute(std::vector<classification_info_t>& classifications, IMatrix* probabilities) = 0; - virtual XML::IXMLNode* saveConfig() = 0; - virtual bool loadConfig(XML::IXMLNode& node) = 0; - bool process() override; +public: + void release() override { delete this; } + bool initialize() override = 0; + bool uninitialize() override = 0; - _IsDerivedFromClass_Final_(Toolkit::TAlgorithm<IAlgorithm>, OVP_ClassId_Algorithm_PairwiseDecision) - }; + virtual bool parameterize() = 0; - class CAlgorithmPairwiseDecisionDesc : virtual public IAlgorithmDesc - { - public: - bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override - { - prototype.addInputParameter(OVP_Algorithm_Classifier_InputParameter_ProbabilityMatrix, "Probability Matrix", Kernel::ParameterType_Matrix); - prototype.addInputParameter(OVP_Algorithm_Classifier_Pairwise_InputParameterId_Config, "Configuration node", Kernel::ParameterType_Pointer); - prototype.addInputParameter( - OVP_Algorithm_Classifier_Pairwise_InputParameterId_SetRepartition, "Set repartition", Kernel::ParameterType_Matrix); - prototype.addInputParameter( - OVP_Algorithm_Classifier_Pairwise_InputParameterId_AlgorithmIdentifier, "Classification Algorithm", Kernel::ParameterType_Identifier); - prototype.addInputParameter( - OVP_Algorithm_Classifier_Pairwise_InputParameter_ClassificationOutputs, "Classification Outputs", Kernel::ParameterType_Pointer); - prototype.addInputParameter(OVP_Algorithm_Classifier_Pairwise_InputParameter_ClassCount, "Class Count", Kernel::ParameterType_UInteger); + virtual bool compute(std::vector<classification_info_t>& classifications, IMatrix* probabilities) = 0; + virtual XML::IXMLNode* saveConfig() = 0; + virtual bool loadConfig(XML::IXMLNode& node) = 0; + bool process() override; - prototype.addOutputParameter( - OVP_Algorithm_Classifier_OutputParameter_ProbabilityVector, "Probability Vector", Kernel::ParameterType_Matrix); - prototype.addOutputParameter( - OVP_Algorithm_Classifier_Pairwise_OutputParameterId_Config, "Configuration node", Kernel::ParameterType_Pointer); + _IsDerivedFromClass_Final_(Toolkit::TAlgorithm<IAlgorithm>, OVP_ClassId_Algorithm_PairwiseDecision) +}; - prototype.addInputTrigger(OVP_Algorithm_Classifier_Pairwise_InputTriggerId_Compute, "Compute"); - prototype.addInputTrigger(OVP_Algorithm_Classifier_Pairwise_InputTriggerId_Parameterize, "Parametrize"); - prototype.addInputTrigger(OVP_Algorithm_Classifier_Pairwise_InputTriggerId_SaveConfig, "Save configuration"); - prototype.addInputTrigger(OVP_Algorithm_Classifier_Pairwise_InputTriggerId_LoadConfig, "Load configuration"); - return true; - } - - _IsDerivedFromClass_Final_(IAlgorithmDesc, OVP_ClassId_Algorithm_PairwiseDecisionDesc) - }; - } // namespace Classification - } // namespace Plugins +class CAlgorithmPairwiseDecisionDesc : virtual public IAlgorithmDesc +{ +public: + bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override + { + prototype.addInputParameter(OVP_Algorithm_Classifier_InputParameter_ProbabilityMatrix, "Probability Matrix", Kernel::ParameterType_Matrix); + prototype.addInputParameter(OVP_Algorithm_Classifier_Pairwise_InputParameterId_Config, "Configuration node", Kernel::ParameterType_Pointer); + prototype.addInputParameter(OVP_Algorithm_Classifier_Pairwise_InputParameterId_SetRepartition, "Set repartition", Kernel::ParameterType_Matrix); + prototype.addInputParameter( + OVP_Algorithm_Classifier_Pairwise_InputParameterId_AlgorithmIdentifier, "Classification Algorithm", Kernel::ParameterType_Identifier); + prototype.addInputParameter( + OVP_Algorithm_Classifier_Pairwise_InputParameter_ClassificationOutputs, "Classification Outputs", Kernel::ParameterType_Pointer); + prototype.addInputParameter(OVP_Algorithm_Classifier_Pairwise_InputParameter_ClassCount, "Class Count", Kernel::ParameterType_UInteger); + + prototype.addOutputParameter(OVP_Algorithm_Classifier_OutputParameter_ProbabilityVector, "Probability Vector", Kernel::ParameterType_Matrix); + prototype.addOutputParameter(OVP_Algorithm_Classifier_Pairwise_OutputParameterId_Config, "Configuration node", Kernel::ParameterType_Pointer); + + prototype.addInputTrigger(OVP_Algorithm_Classifier_Pairwise_InputTriggerId_Compute, "Compute"); + prototype.addInputTrigger(OVP_Algorithm_Classifier_Pairwise_InputTriggerId_Parameterize, "Parametrize"); + prototype.addInputTrigger(OVP_Algorithm_Classifier_Pairwise_InputTriggerId_SaveConfig, "Save configuration"); + prototype.addInputTrigger(OVP_Algorithm_Classifier_Pairwise_InputTriggerId_LoadConfig, "Load configuration"); + return true; + } + + _IsDerivedFromClass_Final_(IAlgorithmDesc, OVP_ClassId_Algorithm_PairwiseDecisionDesc) +}; +} // namespace Classification +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/classification/src/algorithms/ovpCAlgorithmPairwiseDecisionHT.cpp b/plugins/processing/classification/src/algorithms/ovpCAlgorithmPairwiseDecisionHT.cpp index 06b436cff9dd75072faee8f2fe4dc5a2c66f10ed..fd267bc9feab4c651ee664fc75be5b31802be4c8 100644 --- a/plugins/processing/classification/src/algorithms/ovpCAlgorithmPairwiseDecisionHT.cpp +++ b/plugins/processing/classification/src/algorithms/ovpCAlgorithmPairwiseDecisionHT.cpp @@ -9,10 +9,9 @@ #include <xml/IXMLNode.h> #include <xml/IXMLHandler.h> -namespace -{ - const char* const TYPE_NODE_NAME = "PairwiseDecision_HT"; - const char* const REPARTITION_NODE_NAME = "Repartition"; +namespace { +const char* const TYPE_NODE_NAME = "PairwiseDecision_HT"; +const char* const REPARTITION_NODE_NAME = "Repartition"; } @@ -28,8 +27,7 @@ bool CAlgorithmPairwiseDecisionHT::parameterize() TParameterHandler<uint64_t> ip_nClass(this->getInputParameter(OVP_Algorithm_Classifier_Pairwise_InputParameter_ClassCount)); m_nClass = size_t(ip_nClass); - OV_ERROR_UNLESS_KRF(m_nClass >= 2, "Pairwise decision HT algorithm needs at least 2 classes [" << m_nClass << "] found", - ErrorType::BadInput); + OV_ERROR_UNLESS_KRF(m_nClass >= 2, "Pairwise decision HT algorithm needs at least 2 classes [" << m_nClass << "] found", ErrorType::BadInput); return true; } @@ -37,8 +35,7 @@ bool CAlgorithmPairwiseDecisionHT::parameterize() bool CAlgorithmPairwiseDecisionHT::compute(std::vector<classification_info_t>& classifications, IMatrix* probabilities) { - OV_ERROR_UNLESS_KRF(m_nClass >= 2, "Pairwise decision HT algorithm needs at least 2 classes [" << m_nClass << "] found", - ErrorType::BadConfig); + OV_ERROR_UNLESS_KRF(m_nClass >= 2, "Pairwise decision HT algorithm needs at least 2 classes [" << m_nClass << "] found", ErrorType::BadConfig); TParameterHandler<IMatrix*> ip_Repartition = this->getInputParameter(OVP_Algorithm_Classifier_Pairwise_InputParameterId_SetRepartition); std::vector<double> probability(m_nClass * m_nClass); diff --git a/plugins/processing/classification/src/algorithms/ovpCAlgorithmPairwiseDecisionHT.h b/plugins/processing/classification/src/algorithms/ovpCAlgorithmPairwiseDecisionHT.h index 37711429b87a1b84837ba62e4ad7a55deea70d5e..5a3a13587850b3d82d90ed02b866a4e9a2c4256c 100644 --- a/plugins/processing/classification/src/algorithms/ovpCAlgorithmPairwiseDecisionHT.h +++ b/plugins/processing/classification/src/algorithms/ovpCAlgorithmPairwiseDecisionHT.h @@ -6,68 +6,66 @@ #include "ovpCAlgorithmPairwiseDecision.h" -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace Classification { +/** + * @brief The CAlgorithmPairwiseDecisionHT class is a decision strategy for the One Vs One pairwise decision that implement the + * method describe in the article Hastie, Trevor; Tibshirani, Robert. Classification by pairwise coupling. The Annals of Statistics 26 (1998), no. 2, 451--471 + * + * Probability required + */ +class CAlgorithmPairwiseDecisionHT final : virtual public CAlgorithmPairwiseDecision { - namespace Plugins - { - namespace Classification - { /** - * @brief The CAlgorithmPairwiseDecisionHT class is a decision strategy for the One Vs One pairwise decision that implement the - * method describe in the article Hastie, Trevor; Tibshirani, Robert. Classification by pairwise coupling. The Annals of Statistics 26 (1998), no. 2, 451--471 - * - * Probability required - */ - class CAlgorithmPairwiseDecisionHT final : virtual public CAlgorithmPairwiseDecision - { - public: +public: - CAlgorithmPairwiseDecisionHT() { } - void release() override { delete this; } - bool initialize() override { return true; } - bool uninitialize() override { return true; } - bool parameterize() override; - bool compute(std::vector<classification_info_t>& classifications, IMatrix* probabilities) override; - XML::IXMLNode* saveConfig() override; - bool loadConfig(XML::IXMLNode& node) override; + CAlgorithmPairwiseDecisionHT() { } + void release() override { delete this; } + bool initialize() override { return true; } + bool uninitialize() override { return true; } + bool parameterize() override; + bool compute(std::vector<classification_info_t>& classifications, IMatrix* probabilities) override; + XML::IXMLNode* saveConfig() override; + bool loadConfig(XML::IXMLNode& node) override; - _IsDerivedFromClass_Final_(CAlgorithmPairwiseDecision, OVP_ClassId_Algorithm_PairwiseDecision_HT) + _IsDerivedFromClass_Final_(CAlgorithmPairwiseDecision, OVP_ClassId_Algorithm_PairwiseDecision_HT) - private: - size_t m_nClass = 0; - }; +private: + size_t m_nClass = 0; +}; - class CAlgorithmPairwiseDecisionHTDesc final : virtual public CAlgorithmPairwiseDecisionDesc - { - public: - void release() override { } - CString getName() const override { return CString("Pairwise decision strategy based on HT"); } - CString getAuthorName() const override { return CString("Serrière Guillaume"); } - CString getAuthorCompanyName() const override { return CString("Inria"); } - CString getShortDescription() const override { return CString("."); } +class CAlgorithmPairwiseDecisionHTDesc final : virtual public CAlgorithmPairwiseDecisionDesc +{ +public: + void release() override { } + CString getName() const override { return CString("Pairwise decision strategy based on HT"); } + CString getAuthorName() const override { return CString("Serrière Guillaume"); } + CString getAuthorCompanyName() const override { return CString("Inria"); } + CString getShortDescription() const override { return CString("."); } - CString getDetailedDescription() const override - { - return CString("This method is based on the method describe in the article " - "Hastie, Trevor; Tibshirani, Robert. Classification by pairwise coupling." - "The Annals of Statistics 26 (1998), no. 2, 451--471"); - } + CString getDetailedDescription() const override + { + return CString("This method is based on the method describe in the article " + "Hastie, Trevor; Tibshirani, Robert. Classification by pairwise coupling." + "The Annals of Statistics 26 (1998), no. 2, 451--471"); + } - CString getCategory() const override { return CString(""); } - CString getVersion() const override { return CString("0.1"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_Algorithm_PairwiseDecision_HT; } - IPluginObject* create() override { return new CAlgorithmPairwiseDecisionHT; } + CString getCategory() const override { return CString(""); } + CString getVersion() const override { return CString("0.1"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_Algorithm_PairwiseDecision_HT; } + IPluginObject* create() override { return new CAlgorithmPairwiseDecisionHT; } - bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override - { - CAlgorithmPairwiseDecisionDesc::getAlgorithmPrototype(prototype); - return true; - } + bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override + { + CAlgorithmPairwiseDecisionDesc::getAlgorithmPrototype(prototype); + return true; + } - _IsDerivedFromClass_Final_(CAlgorithmPairwiseDecisionDesc, OVP_ClassId_Algorithm_PairwiseDecision_HTDesc) - }; - } // namespace Classification - } // namespace Plugins + _IsDerivedFromClass_Final_(CAlgorithmPairwiseDecisionDesc, OVP_ClassId_Algorithm_PairwiseDecision_HTDesc) +}; +} // namespace Classification +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/classification/src/algorithms/ovpCAlgorithmPairwiseDecisionVoting.cpp b/plugins/processing/classification/src/algorithms/ovpCAlgorithmPairwiseDecisionVoting.cpp index 38fb1dd84e9d384a94959501c3fbb83e85773751..f3aa9c71736b659e0e473a6da18184256f85bfb8 100644 --- a/plugins/processing/classification/src/algorithms/ovpCAlgorithmPairwiseDecisionVoting.cpp +++ b/plugins/processing/classification/src/algorithms/ovpCAlgorithmPairwiseDecisionVoting.cpp @@ -5,9 +5,8 @@ #include <xml/IXMLNode.h> -namespace -{ - const char* const TYPE_NODE_NAME = "PairwiseDecision_Voting"; +namespace { +const char* const TYPE_NODE_NAME = "PairwiseDecision_Voting"; } using namespace OpenViBE; @@ -22,16 +21,14 @@ bool CAlgorithmPairwiseDecisionVoting::parameterize() TParameterHandler<uint64_t> ip_nClass(this->getInputParameter(OVP_Algorithm_Classifier_Pairwise_InputParameter_ClassCount)); m_nClass = size_t(ip_nClass); - OV_ERROR_UNLESS_KRF(m_nClass >= 2, "Pairwise decision Voting algorithm needs at least 2 classes [" << m_nClass << "] found", - ErrorType::BadInput); + OV_ERROR_UNLESS_KRF(m_nClass >= 2, "Pairwise decision Voting algorithm needs at least 2 classes [" << m_nClass << "] found", ErrorType::BadInput); return true; } bool CAlgorithmPairwiseDecisionVoting::compute(std::vector<classification_info_t>& classifications, IMatrix* probabilities) { - OV_ERROR_UNLESS_KRF(m_nClass >= 2, "Pairwise decision Voting algorithm needs at least 2 classes [" << m_nClass << "] found", - ErrorType::BadInput); + OV_ERROR_UNLESS_KRF(m_nClass >= 2, "Pairwise decision Voting algorithm needs at least 2 classes [" << m_nClass << "] found", ErrorType::BadInput); #if VOTING_DEBUG std::cout << classifications.size() << std::endl; diff --git a/plugins/processing/classification/src/algorithms/ovpCAlgorithmPairwiseDecisionVoting.h b/plugins/processing/classification/src/algorithms/ovpCAlgorithmPairwiseDecisionVoting.h index f3f85876166b173007e2ad0771aea1d732889248..8483576591531f76fe8a1bd572326a4e2372c35b 100644 --- a/plugins/processing/classification/src/algorithms/ovpCAlgorithmPairwiseDecisionVoting.h +++ b/plugins/processing/classification/src/algorithms/ovpCAlgorithmPairwiseDecisionVoting.h @@ -6,63 +6,60 @@ #include "ovpCAlgorithmPairwiseDecision.h" -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace Classification { +/** + * @brief The CAlgorithmPairwiseDecisionVoting class + * This strategy relies on a basic voting system. If class A beats class B, class A win 1 point and B 0 point. At the end, the vector of + * probability is composed by the normalized score of each class. + * + * Probability required. + */ +class CAlgorithmPairwiseDecisionVoting final : virtual public CAlgorithmPairwiseDecision { - namespace Plugins - { - namespace Classification - { - /** - * @brief The CAlgorithmPairwiseDecisionVoting class - * This strategy relies on a basic voting system. If class A beats class B, class A win 1 point and B 0 point. At the end, the vector of - * probability is composed by the normalized score of each class. - * - * Probability required. - */ - class CAlgorithmPairwiseDecisionVoting final : virtual public CAlgorithmPairwiseDecision - { - public: +public: - CAlgorithmPairwiseDecisionVoting() { } - void release() override { delete this; } - bool initialize() override { return true; } - bool uninitialize() override { return true; } - bool parameterize() override; - bool compute(std::vector<classification_info_t>& classifications, IMatrix* probabilities) override; - XML::IXMLNode* saveConfig() override; - bool loadConfig(XML::IXMLNode& /*node*/) override { return true; } + CAlgorithmPairwiseDecisionVoting() { } + void release() override { delete this; } + bool initialize() override { return true; } + bool uninitialize() override { return true; } + bool parameterize() override; + bool compute(std::vector<classification_info_t>& classifications, IMatrix* probabilities) override; + XML::IXMLNode* saveConfig() override; + bool loadConfig(XML::IXMLNode& /*node*/) override { return true; } - _IsDerivedFromClass_Final_(CAlgorithmPairwiseDecision, OVP_ClassId_Algorithm_PairwiseDecision_Voting) + _IsDerivedFromClass_Final_(CAlgorithmPairwiseDecision, OVP_ClassId_Algorithm_PairwiseDecision_Voting) - private: - size_t m_nClass = 0; - }; +private: + size_t m_nClass = 0; +}; - class CAlgorithmPairwiseDecisionVotingDesc final : virtual public CAlgorithmPairwiseDecisionDesc - { - public: - void release() override { } - CString getName() const override { return CString("Pairwise decision strategy based on Voting"); } - CString getAuthorName() const override { return CString("Serrière Guillaume"); } - CString getAuthorCompanyName() const override { return CString("Inria"); } - CString getShortDescription() const override { return CString("."); } - CString getDetailedDescription() const override { return CString(""); } - CString getCategory() const override { return CString(""); } - CString getVersion() const override { return CString("0.1"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_Algorithm_PairwiseDecision_Voting; } - IPluginObject* create() override { return new CAlgorithmPairwiseDecisionVoting; } +class CAlgorithmPairwiseDecisionVotingDesc final : virtual public CAlgorithmPairwiseDecisionDesc +{ +public: + void release() override { } + CString getName() const override { return CString("Pairwise decision strategy based on Voting"); } + CString getAuthorName() const override { return CString("Serrière Guillaume"); } + CString getAuthorCompanyName() const override { return CString("Inria"); } + CString getShortDescription() const override { return CString("."); } + CString getDetailedDescription() const override { return CString(""); } + CString getCategory() const override { return CString(""); } + CString getVersion() const override { return CString("0.1"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_Algorithm_PairwiseDecision_Voting; } + IPluginObject* create() override { return new CAlgorithmPairwiseDecisionVoting; } - bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override - { - CAlgorithmPairwiseDecisionDesc::getAlgorithmPrototype(prototype); - return true; - } + bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override + { + CAlgorithmPairwiseDecisionDesc::getAlgorithmPrototype(prototype); + return true; + } - _IsDerivedFromClass_Final_(CAlgorithmPairwiseDecisionDesc, OVP_ClassId_Algorithm_PairwiseDecision_VotingDesc) - }; - } // namespace Classification - } // namespace Plugins + _IsDerivedFromClass_Final_(CAlgorithmPairwiseDecisionDesc, OVP_ClassId_Algorithm_PairwiseDecision_VotingDesc) +}; +} // namespace Classification +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/classification/src/algorithms/ovpCAlgorithmPairwiseStrategyPKPD.cpp b/plugins/processing/classification/src/algorithms/ovpCAlgorithmPairwiseStrategyPKPD.cpp index d7c2c2b03954daf4fd8098ee54458d467ce1dd79..52670e3cec74a7392cd4ffff1be84e1396a0353d 100644 --- a/plugins/processing/classification/src/algorithms/ovpCAlgorithmPairwiseStrategyPKPD.cpp +++ b/plugins/processing/classification/src/algorithms/ovpCAlgorithmPairwiseStrategyPKPD.cpp @@ -4,9 +4,8 @@ #include <iostream> -namespace -{ - const char* const TYPE_NODE_NAME = "PairwiseDecision_PKDP"; +namespace { +const char* const TYPE_NODE_NAME = "PairwiseDecision_PKDP"; } @@ -22,16 +21,14 @@ bool CAlgorithmPairwiseStrategyPKPD::parameterize() TParameterHandler<uint64_t> ip_nClass(this->getInputParameter(OVP_Algorithm_Classifier_Pairwise_InputParameter_ClassCount)); m_nClass = size_t(ip_nClass); - OV_ERROR_UNLESS_KRF(m_nClass >= 2, "Pairwise decision PKPD algorithm needs at least 2 classes [" << m_nClass << "] found", - ErrorType::BadInput); + OV_ERROR_UNLESS_KRF(m_nClass >= 2, "Pairwise decision PKPD algorithm needs at least 2 classes [" << m_nClass << "] found", ErrorType::BadInput); return true; } bool CAlgorithmPairwiseStrategyPKPD::compute(std::vector<classification_info_t>& classifications, IMatrix* probabilities) { - OV_ERROR_UNLESS_KRF(m_nClass >= 2, "Pairwise decision PKPD algorithm needs at least 2 classes [" << m_nClass << "] found", - ErrorType::BadInput); + OV_ERROR_UNLESS_KRF(m_nClass >= 2, "Pairwise decision PKPD algorithm needs at least 2 classes [" << m_nClass << "] found", ErrorType::BadInput); std::vector<double> matrix(m_nClass * m_nClass); diff --git a/plugins/processing/classification/src/algorithms/ovpCAlgorithmPairwiseStrategyPKPD.h b/plugins/processing/classification/src/algorithms/ovpCAlgorithmPairwiseStrategyPKPD.h index 8d50ab53e812e31c77cf6fb0fc5b98eb7baebdc4..512c7b0d98345753520367a676a8335f94a3b763 100644 --- a/plugins/processing/classification/src/algorithms/ovpCAlgorithmPairwiseStrategyPKPD.h +++ b/plugins/processing/classification/src/algorithms/ovpCAlgorithmPairwiseStrategyPKPD.h @@ -7,71 +7,68 @@ #include "ovpCAlgorithmPairwiseDecision.h" -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace Classification { +/** + * @brief The CAlgorithmPairwiseStrategyPKPD class + * This strategy relies on the algorithm describe in the article . Price, S. Knerr, L. Personnaz, and G. Dreyfus. + * Pairwise neural network classifiers with probabilistic outputs. In G. Tesauro, D. Touretzky, and T. Leen (eds.) + * Advances in Neural Information Processing Systems 7 (NIPS-94), pp. 1109-1116. MIT Press, 1995. + */ +class CAlgorithmPairwiseStrategyPKPD final : virtual public CAlgorithmPairwiseDecision { - namespace Plugins - { - namespace Classification - { - /** - * @brief The CAlgorithmPairwiseStrategyPKPD class - * This strategy relies on the algorithm describe in the article . Price, S. Knerr, L. Personnaz, and G. Dreyfus. - * Pairwise neural network classifiers with probabilistic outputs. In G. Tesauro, D. Touretzky, and T. Leen (eds.) - * Advances in Neural Information Processing Systems 7 (NIPS-94), pp. 1109-1116. MIT Press, 1995. - */ - class CAlgorithmPairwiseStrategyPKPD final : virtual public CAlgorithmPairwiseDecision - { - public: +public: - CAlgorithmPairwiseStrategyPKPD() { } - void release() override { delete this; } - bool initialize() override { return true; } - bool uninitialize() override { return true; } - bool parameterize() override; - bool compute(std::vector<classification_info_t>& classifications, IMatrix* probabilities) override; - XML::IXMLNode* saveConfig() override; - bool loadConfig(XML::IXMLNode& /*node*/) override { return true; } + CAlgorithmPairwiseStrategyPKPD() { } + void release() override { delete this; } + bool initialize() override { return true; } + bool uninitialize() override { return true; } + bool parameterize() override; + bool compute(std::vector<classification_info_t>& classifications, IMatrix* probabilities) override; + XML::IXMLNode* saveConfig() override; + bool loadConfig(XML::IXMLNode& /*node*/) override { return true; } - _IsDerivedFromClass_Final_(CAlgorithmPairwiseDecision, OVP_ClassId_Algorithm_PairwiseStrategy_PKPD) + _IsDerivedFromClass_Final_(CAlgorithmPairwiseDecision, OVP_ClassId_Algorithm_PairwiseStrategy_PKPD) - private: - size_t m_nClass = 0; - }; +private: + size_t m_nClass = 0; +}; - class CAlgorithmPairwiseStrategyPKPDDesc final : virtual public CAlgorithmPairwiseDecisionDesc - { - public: - void release() override { } - CString getName() const override { return CString("Pairwise decision strategy based on PKPD"); } - CString getAuthorName() const override { return CString("Serrière Guillaume"); } - CString getAuthorCompanyName() const override { return CString("Inria"); } - CString getShortDescription() const override { return CString("."); } +class CAlgorithmPairwiseStrategyPKPDDesc final : virtual public CAlgorithmPairwiseDecisionDesc +{ +public: + void release() override { } + CString getName() const override { return CString("Pairwise decision strategy based on PKPD"); } + CString getAuthorName() const override { return CString("Serrière Guillaume"); } + CString getAuthorCompanyName() const override { return CString("Inria"); } + CString getShortDescription() const override { return CString("."); } - CString getDetailedDescription() const override - { - return CString("Price, S. Knerr, L. Personnaz, and G. Dreyfus." - "Pairwise neural network classifiers with probabilistic outputs." - " In G. Tesauro, D. Touretzky, and T. Leen (eds.)" - "Advances in Neural Information Processing Systems 7 (NIPS-94), pp." - " 1109-1116. MIT Press, 1995."); - } + CString getDetailedDescription() const override + { + return CString("Price, S. Knerr, L. Personnaz, and G. Dreyfus." + "Pairwise neural network classifiers with probabilistic outputs." + " In G. Tesauro, D. Touretzky, and T. Leen (eds.)" + "Advances in Neural Information Processing Systems 7 (NIPS-94), pp." + " 1109-1116. MIT Press, 1995."); + } - CString getCategory() const override { return CString(""); } - CString getVersion() const override { return CString("0.1"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_Algorithm_PairwiseStrategy_PKPD; } - IPluginObject* create() override { return new CAlgorithmPairwiseStrategyPKPD; } + CString getCategory() const override { return CString(""); } + CString getVersion() const override { return CString("0.1"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_Algorithm_PairwiseStrategy_PKPD; } + IPluginObject* create() override { return new CAlgorithmPairwiseStrategyPKPD; } - bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override - { - CAlgorithmPairwiseDecisionDesc::getAlgorithmPrototype(prototype); - return true; - } + bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override + { + CAlgorithmPairwiseDecisionDesc::getAlgorithmPrototype(prototype); + return true; + } - _IsDerivedFromClass_Final_(CAlgorithmPairwiseDecisionDesc, OVP_ClassId_Algorithm_PairwiseStrategy_PKPDDesc) - }; - } // namespace Classification - } // namespace Plugins + _IsDerivedFromClass_Final_(CAlgorithmPairwiseDecisionDesc, OVP_ClassId_Algorithm_PairwiseStrategy_PKPDDesc) +}; +} // namespace Classification +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/classification/src/box-algorithms/ovpCBoxAlgorithmClassifierProcessor.h b/plugins/processing/classification/src/box-algorithms/ovpCBoxAlgorithmClassifierProcessor.h index a9e9d9fd75e1a71997d87ec53a0c5b45e6f87e64..2bdd354f894ed90ce96a0e5cb4bd5dffe213d8a6 100644 --- a/plugins/processing/classification/src/box-algorithms/ovpCBoxAlgorithmClassifierProcessor.h +++ b/plugins/processing/classification/src/box-algorithms/ovpCBoxAlgorithmClassifierProcessor.h @@ -7,80 +7,73 @@ #include <map> -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace Classification { +class CBoxAlgorithmClassifierProcessor final : virtual public Toolkit::TBoxAlgorithm<IBoxAlgorithm> { - namespace Plugins +public: + void release() override { delete this; } + bool initialize() override; + bool uninitialize() override; + bool processInput(const size_t index) override; + bool process() override; + + _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_ClassifierProcessor) + +protected: + bool loadClassifier(const char* filename); + +private: + + Toolkit::TFeatureVectorDecoder<CBoxAlgorithmClassifierProcessor> m_sampleDecoder; + Toolkit::TStimulationDecoder<CBoxAlgorithmClassifierProcessor> m_stimDecoder; + Toolkit::TStimulationEncoder<CBoxAlgorithmClassifierProcessor> m_labelsEncoder; + Toolkit::TStreamedMatrixEncoder<CBoxAlgorithmClassifierProcessor> m_hyperplanesEncoder; + Toolkit::TStreamedMatrixEncoder<CBoxAlgorithmClassifierProcessor> m_probabilitiesEncoder; + + Kernel::IAlgorithmProxy* m_classifier = nullptr; + + std::map<double, uint64_t> m_stimulations; +}; + +class CBoxAlgorithmClassifierProcessorDesc final : virtual public IBoxAlgorithmDesc +{ +public: + void release() override { } + CString getName() const override { return CString("Classifier processor"); } + CString getAuthorName() const override { return CString("Yann Renard, Guillaume Serriere"); } + CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } + CString getShortDescription() const override { return CString("Generic classification, relying on several box algorithms"); } + + CString getDetailedDescription() const override { return CString("Classifies incoming feature vectors using a previously learned classifier."); } + + CString getCategory() const override { return CString("Classification"); } + CString getVersion() const override { return CString("2.1"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.1.0"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_ClassifierProcessor; } + IPluginObject* create() override { return new CBoxAlgorithmClassifierProcessor; } + + bool getBoxPrototype(Kernel::IBoxProto& prototype) const override { - namespace Classification - { - class CBoxAlgorithmClassifierProcessor final : virtual public Toolkit::TBoxAlgorithm<IBoxAlgorithm> - { - public: - void release() override { delete this; } - bool initialize() override; - bool uninitialize() override; - bool processInput(const size_t index) override; - bool process() override; - - _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_ClassifierProcessor) - - protected: - bool loadClassifier(const char* filename); - - private: - - Toolkit::TFeatureVectorDecoder<CBoxAlgorithmClassifierProcessor> m_sampleDecoder; - Toolkit::TStimulationDecoder<CBoxAlgorithmClassifierProcessor> m_stimDecoder; - - Toolkit::TStimulationEncoder<CBoxAlgorithmClassifierProcessor> m_labelsEncoder; - Toolkit::TStreamedMatrixEncoder<CBoxAlgorithmClassifierProcessor> m_hyperplanesEncoder; - Toolkit::TStreamedMatrixEncoder<CBoxAlgorithmClassifierProcessor> m_probabilitiesEncoder; - - Kernel::IAlgorithmProxy* m_classifier = nullptr; - - std::map<double, uint64_t> m_stimulations; - }; - - class CBoxAlgorithmClassifierProcessorDesc final : virtual public IBoxAlgorithmDesc - { - public: - void release() override { } - CString getName() const override { return CString("Classifier processor"); } - CString getAuthorName() const override { return CString("Yann Renard, Guillaume Serriere"); } - CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } - CString getShortDescription() const override { return CString("Generic classification, relying on several box algorithms"); } - - CString getDetailedDescription() const override - { - return CString("Classifies incoming feature vectors using a previously learned classifier."); - } - - CString getCategory() const override { return CString("Classification"); } - CString getVersion() const override { return CString("2.1"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.1.0"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_ClassifierProcessor; } - IPluginObject* create() override { return new CBoxAlgorithmClassifierProcessor; } - - bool getBoxPrototype(Kernel::IBoxProto& prototype) const override - { - prototype.addInput("Features", OV_TypeId_FeatureVector); - prototype.addInput("Commands", OV_TypeId_Stimulations); - prototype.addOutput("Labels", OV_TypeId_Stimulations); - prototype.addOutput("Hyperplane distance", OV_TypeId_StreamedMatrix); - prototype.addOutput("Probability values", OV_TypeId_StreamedMatrix); - - //We load everything in the save filed - prototype.addSetting("Filename to load configuration from", OV_TypeId_Filename, ""); - return true; - } - - // virtual IBoxListener* createBoxListener() const { return new CBoxAlgorithmCommonClassifierListener(5); } - void releaseBoxListener(IBoxListener* listener) const override { delete listener; } - - _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_ClassifierProcessorDesc) - }; - } // namespace Classification - } // namespace Plugins + prototype.addInput("Features", OV_TypeId_FeatureVector); + prototype.addInput("Commands", OV_TypeId_Stimulations); + prototype.addOutput("Labels", OV_TypeId_Stimulations); + prototype.addOutput("Hyperplane distance", OV_TypeId_StreamedMatrix); + prototype.addOutput("Probability values", OV_TypeId_StreamedMatrix); + + //We load everything in the save filed + prototype.addSetting("Filename to load configuration from", OV_TypeId_Filename, ""); + return true; + } + + // virtual IBoxListener* createBoxListener() const { return new CBoxAlgorithmCommonClassifierListener(5); } + void releaseBoxListener(IBoxListener* listener) const override { delete listener; } + + _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_ClassifierProcessorDesc) +}; +} // namespace Classification +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/classification/src/box-algorithms/ovpCBoxAlgorithmClassifierTrainer.cpp b/plugins/processing/classification/src/box-algorithms/ovpCBoxAlgorithmClassifierTrainer.cpp index 8a93c8fa5c1c7ec8caabd50f48ad1f7c541c02c8..e86a66d457586921dfe9e944c2cfb8bac69f4520 100644 --- a/plugins/processing/classification/src/box-algorithms/ovpCBoxAlgorithmClassifierTrainer.cpp +++ b/plugins/processing/classification/src/box-algorithms/ovpCBoxAlgorithmClassifierTrainer.cpp @@ -95,7 +95,7 @@ bool CBoxAlgorithmClassifierTrainer::initialize() } //We link the parameters to the extra parameters input parameter to transmit them - TParameterHandler<map<CString, CString> *> ip_parameter(m_classifier->getInputParameter(OVTK_Algorithm_Classifier_InputParameterId_ExtraParameter)); + TParameterHandler<map<CString, CString>*> ip_parameter(m_classifier->getInputParameter(OVTK_Algorithm_Classifier_InputParameterId_ExtraParameter)); ip_parameter = m_parameter; m_encoder.initialize(*this, 0); diff --git a/plugins/processing/classification/src/box-algorithms/ovpCBoxAlgorithmClassifierTrainer.h b/plugins/processing/classification/src/box-algorithms/ovpCBoxAlgorithmClassifierTrainer.h index c2e63c7143e414e6772bf557b8b9e7e95daa8ba1..a9736b4534eb9e3d8024678e0cc9e1a60bbf5dc6 100644 --- a/plugins/processing/classification/src/box-algorithms/ovpCBoxAlgorithmClassifierTrainer.h +++ b/plugins/processing/classification/src/box-algorithms/ovpCBoxAlgorithmClassifierTrainer.h @@ -11,128 +11,121 @@ #include <iostream> -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace Classification { +const char* const TRAIN_TRIGGER_SETTING_NAME = "Train trigger"; +const char* const FILENAME_SETTING_NAME = "Filename to save configuration to"; +const char* const MULTICLASS_STRATEGY_SETTING_NAME = "Multiclass strategy to apply"; +const char* const ALGORITHM_SETTING_NAME = "Algorithm to use"; +const char* const FOLD_SETTING_NAME = "Number of partitions for k-fold cross-validation test"; +const char* const BALANCE_SETTING_NAME = "Balance classes"; + +class CBoxAlgorithmClassifierTrainer final : virtual public Toolkit::TBoxAlgorithm<IBoxAlgorithm> { - namespace Plugins +public: + void release() override { delete this; } + bool initialize() override; + bool uninitialize() override; + bool processInput(const size_t index) override; + bool process() override; + + _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_ClassifierTrainer) + +protected: + + typedef struct { - namespace Classification - { - const char* const TRAIN_TRIGGER_SETTING_NAME = "Train trigger"; - const char* const FILENAME_SETTING_NAME = "Filename to save configuration to"; - const char* const MULTICLASS_STRATEGY_SETTING_NAME = "Multiclass strategy to apply"; - const char* const ALGORITHM_SETTING_NAME = "Algorithm to use"; - const char* const FOLD_SETTING_NAME = "Number of partitions for k-fold cross-validation test"; - const char* const BALANCE_SETTING_NAME = "Balance classes"; - - class CBoxAlgorithmClassifierTrainer final : virtual public Toolkit::TBoxAlgorithm<IBoxAlgorithm> - { - public: - void release() override { delete this; } - bool initialize() override; - bool uninitialize() override; - bool processInput(const size_t index) override; - bool process() override; - - _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_ClassifierTrainer) - - protected: - - typedef struct - { - CMatrix* sampleMatrix; - uint64_t startTime; - uint64_t endTime; - size_t inputIdx; - } sample_t; - - bool train(const std::vector<sample_t>& dataset, const std::vector<size_t>& permutation, size_t startIdx, size_t stopIdx); - double getAccuracy(const std::vector<sample_t>& dataset, const std::vector<size_t>& permutation, size_t startIdx, size_t stopIdx, - CMatrix& confusionMatrix); - bool printConfusionMatrix(const CMatrix& oMatrix); - bool balanceDataset(); - - private: - bool saveConfig(); - - protected: - - std::map<size_t, size_t> m_nFeatures; - - Kernel::IAlgorithmProxy* m_classifier = nullptr; - uint64_t m_trainStimulation = 0; - size_t m_nPartition = 0; - - Toolkit::TStimulationDecoder<CBoxAlgorithmClassifierTrainer> m_stimDecoder; - std::vector<Toolkit::TFeatureVectorDecoder<CBoxAlgorithmClassifierTrainer>*> m_sampleDecoder; - - Toolkit::TStimulationEncoder<CBoxAlgorithmClassifierTrainer> m_encoder; - - std::map<CString, CString>* m_parameter = nullptr; - - std::vector<sample_t> m_datasets; - std::vector<sample_t> m_balancedDatasets; - }; - - class CBoxAlgorithmClassifierTrainerDesc final : virtual public IBoxAlgorithmDesc - { - public: - void release() override { } - CString getName() const override { return CString("Classifier trainer"); } - CString getAuthorName() const override { return CString("Yann Renard, Guillaume Serriere"); } - CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } - - CString getShortDescription() const override { return CString("Generic classifier trainer, relying on several box algorithms"); } - - CString getDetailedDescription() const override - { - return CString("Performs classifier training with cross-validation -based error estimation"); - } - - CString getCategory() const override { return CString("Classification"); } - CString getVersion() const override { return CString("2.0"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.1.0"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_ClassifierTrainer; } - IPluginObject* create() override { return new CBoxAlgorithmClassifierTrainer; } - - bool getBoxPrototype(Kernel::IBoxProto& prototype) const override - { - prototype.addInput("Stimulations", OV_TypeId_Stimulations); - prototype.addInput("Features for class 1", OV_TypeId_FeatureVector); - prototype.addInput("Features for class 2", OV_TypeId_FeatureVector); - - prototype.addOutput("Train-completed Flag", OV_TypeId_Stimulations); - - prototype.addSetting(TRAIN_TRIGGER_SETTING_NAME, OV_TypeId_Stimulation, "OVTK_StimulationId_Train"); - prototype.addSetting(FILENAME_SETTING_NAME, OV_TypeId_Filename, "${Path_UserData}/my-classifier.xml"); - - prototype.addSetting(MULTICLASS_STRATEGY_SETTING_NAME, OVTK_TypeId_ClassificationStrategy, "Native"); - //Pairing startegy argument - //Class label - - prototype.addSetting(ALGORITHM_SETTING_NAME, OVTK_TypeId_ClassificationAlgorithm, "Linear Discrimimant Analysis (LDA)"); - //Argument of algorithm - - prototype.addSetting(FOLD_SETTING_NAME, OV_TypeId_Integer, "10"); - prototype.addSetting(BALANCE_SETTING_NAME, OV_TypeId_Boolean, "false"); - - prototype.addFlag(Kernel::BoxFlag_CanAddInput); - - // prototype.addFlag(Kernel::BoxFlag_ManualUpdate); - return true; - } + CMatrix* sampleMatrix; + uint64_t startTime; + uint64_t endTime; + size_t inputIdx; + } sample_t; + + bool train(const std::vector<sample_t>& dataset, const std::vector<size_t>& permutation, size_t startIdx, size_t stopIdx); + double getAccuracy(const std::vector<sample_t>& dataset, const std::vector<size_t>& permutation, size_t startIdx, size_t stopIdx, CMatrix& confusionMatrix); + bool printConfusionMatrix(const CMatrix& oMatrix); + bool balanceDataset(); + +private: + bool saveConfig(); + +protected: + + std::map<size_t, size_t> m_nFeatures; + + Kernel::IAlgorithmProxy* m_classifier = nullptr; + uint64_t m_trainStimulation = 0; + size_t m_nPartition = 0; + + Toolkit::TStimulationDecoder<CBoxAlgorithmClassifierTrainer> m_stimDecoder; + std::vector<Toolkit::TFeatureVectorDecoder<CBoxAlgorithmClassifierTrainer>*> m_sampleDecoder; + + Toolkit::TStimulationEncoder<CBoxAlgorithmClassifierTrainer> m_encoder; + + std::map<CString, CString>* m_parameter = nullptr; + + std::vector<sample_t> m_datasets; + std::vector<sample_t> m_balancedDatasets; +}; + +class CBoxAlgorithmClassifierTrainerDesc final : virtual public IBoxAlgorithmDesc +{ +public: + void release() override { } + CString getName() const override { return CString("Classifier trainer"); } + CString getAuthorName() const override { return CString("Yann Renard, Guillaume Serriere"); } + CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } - IBoxListener* createBoxListener() const override - { - const size_t nCommonSetting = 6; - return new CBoxAlgorithmCommonClassifierListener(nCommonSetting); - } + CString getShortDescription() const override { return CString("Generic classifier trainer, relying on several box algorithms"); } + + CString getDetailedDescription() const override { return CString("Performs classifier training with cross-validation -based error estimation"); } + + CString getCategory() const override { return CString("Classification"); } + CString getVersion() const override { return CString("2.0"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.1.0"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_ClassifierTrainer; } + IPluginObject* create() override { return new CBoxAlgorithmClassifierTrainer; } + + bool getBoxPrototype(Kernel::IBoxProto& prototype) const override + { + prototype.addInput("Stimulations", OV_TypeId_Stimulations); + prototype.addInput("Features for class 1", OV_TypeId_FeatureVector); + prototype.addInput("Features for class 2", OV_TypeId_FeatureVector); + + prototype.addOutput("Train-completed Flag", OV_TypeId_Stimulations); + + prototype.addSetting(TRAIN_TRIGGER_SETTING_NAME, OV_TypeId_Stimulation, "OVTK_StimulationId_Train"); + prototype.addSetting(FILENAME_SETTING_NAME, OV_TypeId_Filename, "${Path_UserData}/my-classifier.xml"); + + prototype.addSetting(MULTICLASS_STRATEGY_SETTING_NAME, OVTK_TypeId_ClassificationStrategy, "Native"); + //Pairing startegy argument + //Class label + + prototype.addSetting(ALGORITHM_SETTING_NAME, OVTK_TypeId_ClassificationAlgorithm, "Linear Discrimimant Analysis (LDA)"); + //Argument of algorithm + + prototype.addSetting(FOLD_SETTING_NAME, OV_TypeId_Integer, "10"); + prototype.addSetting(BALANCE_SETTING_NAME, OV_TypeId_Boolean, "false"); + + prototype.addFlag(Kernel::BoxFlag_CanAddInput); + + // prototype.addFlag(Kernel::BoxFlag_ManualUpdate); + return true; + } + + IBoxListener* createBoxListener() const override + { + const size_t nCommonSetting = 6; + return new CBoxAlgorithmCommonClassifierListener(nCommonSetting); + } - void releaseBoxListener(IBoxListener* listener) const override { delete listener; } + void releaseBoxListener(IBoxListener* listener) const override { delete listener; } - _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_ClassifierTrainerDesc) - }; - } // namespace Classification - } // namespace Plugins + _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_ClassifierTrainerDesc) +}; +} // namespace Classification +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/classification/src/box-algorithms/ovpCBoxAlgorithmCommonClassifierListener.inl b/plugins/processing/classification/src/box-algorithms/ovpCBoxAlgorithmCommonClassifierListener.inl index 3e3ad69d70d686ba7c97fcee6d892b542f8c28e7..822befa2be6288413d9d465cb98e85882ea3f416 100755 --- a/plugins/processing/classification/src/box-algorithms/ovpCBoxAlgorithmCommonClassifierListener.inl +++ b/plugins/processing/classification/src/box-algorithms/ovpCBoxAlgorithmCommonClassifierListener.inl @@ -15,366 +15,361 @@ #define DEBUG_PRINT(x) #endif -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace Classification { +class CBoxAlgorithmCommonClassifierListener final : public Toolkit::TBoxListener<IBoxListener> { - namespace Plugins - { - namespace Classification - { - class CBoxAlgorithmCommonClassifierListener final : public Toolkit::TBoxListener<IBoxListener> - { - public: +public: - explicit CBoxAlgorithmCommonClassifierListener(const size_t customSettingBase) : m_customSettingBase(customSettingBase) { } + explicit CBoxAlgorithmCommonClassifierListener(const size_t customSettingBase) : m_customSettingBase(customSettingBase) { } - bool initialize() override - { - //Even if everything should have been set in constructor, we still set everything in initialize (in case of) - m_classifierClassID = OV_UndefinedIdentifier; - m_classifier = nullptr; + bool initialize() override + { + //Even if everything should have been set in constructor, we still set everything in initialize (in case of) + m_classifierClassID = OV_UndefinedIdentifier; + m_classifier = nullptr; - //OV_UndefinedIdentifier is already use for the native, We initialize to an unused identifier in the strategy list - m_strategyClassID = 0x0; - m_strategy = nullptr; + //OV_UndefinedIdentifier is already use for the native, We initialize to an unused identifier in the strategy list + m_strategyClassID = 0x0; + m_strategy = nullptr; - //This value means that we need to calculate it - m_strategyAmountSettings = -1; - return true; - } + //This value means that we need to calculate it + m_strategyAmountSettings = -1; + return true; + } - bool uninitialize() override - { - if (m_classifier) - { - m_classifier->uninitialize(); - this->getAlgorithmManager().releaseAlgorithm(*m_classifier); - m_classifier = nullptr; - } - if (m_strategy) - { - m_strategy->uninitialize(); - this->getAlgorithmManager().releaseAlgorithm(*m_strategy); - m_strategy = nullptr; - } - return true; - } - - bool initializedStrategy(Kernel::IBox& box) - { - CString name; - box.getSettingName(getStrategyIndex() + 1, name); - if (name == CString(PAIRWISE_STRATEGY_ENUMERATION_NAME)) { m_strategyAmountSettings = 1; } - else { m_strategyAmountSettings = 0; } - return true; - } + bool uninitialize() override + { + if (m_classifier) + { + m_classifier->uninitialize(); + this->getAlgorithmManager().releaseAlgorithm(*m_classifier); + m_classifier = nullptr; + } + if (m_strategy) + { + m_strategy->uninitialize(); + this->getAlgorithmManager().releaseAlgorithm(*m_strategy); + m_strategy = nullptr; + } + return true; + } + + bool initializedStrategy(Kernel::IBox& box) + { + CString name; + box.getSettingName(getStrategyIndex() + 1, name); + if (name == CString(PAIRWISE_STRATEGY_ENUMERATION_NAME)) { m_strategyAmountSettings = 1; } + else { m_strategyAmountSettings = 0; } + return true; + } + + //virtual bool onAlgorithmClassIdentifierChanged(Kernel::IBox &box) + //{ + //this->initializedStrategy(box); + //return true; + //} + + int getStrategySettingsCount(Kernel::IBox& box) + { + if (m_strategyAmountSettings < 0) { initializedStrategy(box); } //The value have never been initialized + return m_strategyAmountSettings; + } - //virtual bool onAlgorithmClassIdentifierChanged(Kernel::IBox &box) - //{ - //this->initializedStrategy(box); - //return true; - //} + static bool onInputAddedOrRemoved(Kernel::IBox& box) + { + box.setInputType(0, OV_TypeId_Stimulations); + box.setInputName(0, "Stimulations"); + for (size_t i = 1; i < box.getInputCount(); ++i) + { + box.setInputName(i, ("Features for class " + std::to_string(i)).c_str()); + box.setInputType(i, OV_TypeId_FeatureVector); + } + return true; + } - int getStrategySettingsCount(Kernel::IBox& box) - { - if (m_strategyAmountSettings < 0) { initializedStrategy(box); } //The value have never been initialized - return m_strategyAmountSettings; - } + bool onInputAdded(Kernel::IBox& box, const size_t index) override + { + //index represent the number of the class (because of rejected offset) + const std::string name = "Class " + std::to_string(index) + " label"; + std::stringstream stim; + stim.fill('0'); + stim << "OVTK_StimulationId_Label_" << std::setw(2) << index; + box.addSetting(name.c_str(), OV_TypeId_Stimulation, stim.str().c_str(), 3 - 1 + getStrategySettingsCount(box) + index); + + //Rename input + return onInputAddedOrRemoved(box); + } + + bool onInputRemoved(Kernel::IBox& box, const size_t index) override + { + //First remove the removed input from settings + box.removeSetting(3 - 1 + getStrategySettingsCount(box) + index); - static bool onInputAddedOrRemoved(Kernel::IBox& box) - { - box.setInputType(0, OV_TypeId_Stimulations); - box.setInputName(0, "Stimulations"); - for (size_t i = 1; i < box.getInputCount(); ++i) - { - box.setInputName(i, ("Features for class " + std::to_string(i)).c_str()); - box.setInputType(i, OV_TypeId_FeatureVector); - } - return true; - } + //Then rename the remains inputs in settings + for (size_t i = 1; i < box.getInputCount(); ++i) + { + const std::string name = "Class " + std::to_string(i) + " label"; + box.setSettingName(3 - 1 + getStrategySettingsCount(box) + i, name.c_str()); + } - bool onInputAdded(Kernel::IBox& box, const size_t index) override - { - //index represent the number of the class (because of rejected offset) - const std::string name = "Class " + std::to_string(index) + " label"; - std::stringstream stim; - stim.fill('0'); - stim << "OVTK_StimulationId_Label_" << std::setw(2) << index; - box.addSetting(name.c_str(), OV_TypeId_Stimulation, stim.str().c_str(), 3 - 1 + getStrategySettingsCount(box) + index); - - //Rename input - return onInputAddedOrRemoved(box); - } + //Then rename input + return onInputAddedOrRemoved(box); + } - bool onInputRemoved(Kernel::IBox& box, const size_t index) override - { - //First remove the removed input from settings - box.removeSetting(3 - 1 + getStrategySettingsCount(box) + index); + bool onInitialized(Kernel::IBox& box) override + { + //We need to know if the box is already initialized (can be called after a restore state) + CString strategyName; + box.getSettingName(getStrategyIndex() + 2, strategyName);//this one is a class label + const std::string settingName(strategyName.toASCIIString()); - //Then rename the remains inputs in settings - for (size_t i = 1; i < box.getInputCount(); ++i) - { - const std::string name = "Class " + std::to_string(i) + " label"; - box.setSettingName(3 - 1 + getStrategySettingsCount(box) + i, name.c_str()); - } + if (settingName.find("Class ") == std::string::npos)//We haven't initialized the box so let's do it + { + //Now added Settings for classes + for (size_t i = 1; i < box.getInputCount(); ++i) + { + const std::string name = "Class " + std::to_string(i) + " label"; + std::stringstream stim; + stim.fill('0'); + stim << "OVTK_StimulationId_Label_" << std::setw(2) << i; + box.addSetting(name.c_str(), OV_TypeId_Stimulation, stim.str().c_str(), 3 - 1 + getStrategySettingsCount(box) + i); + DEBUG_PRINT(std::cout << "Add setting (type D) " << buffer << " " << stimulation << "\n";) + } + return this->onAlgorithmClassifierChanged(box); + } + return true; + //return this->onAlgorithmClassifierChanged(box); + } + + //Return the index of the combo box used to select the strategy (native/ OnevsOne...) + static size_t getStrategyIndex() { return 2; } + + //Return the index of the combo box used to select the classification algorithm + size_t getClassifierIndex(Kernel::IBox& box) { return getStrategySettingsCount(box) + 3 + box.getInputCount() - 1; } + + bool onSettingValueChanged(Kernel::IBox& box, const size_t index) override + { + if (index == getClassifierIndex(box)) { return this->onAlgorithmClassifierChanged(box); } + if (index == getStrategyIndex()) { return this->onStrategyChanged(box); } + return true; + } - //Then rename input - return onInputAddedOrRemoved(box); - } - bool onInitialized(Kernel::IBox& box) override - { - //We need to know if the box is already initialized (can be called after a restore state) - CString strategyName; - box.getSettingName(getStrategyIndex() + 2, strategyName);//this one is a class label - const std::string settingName(strategyName.toASCIIString()); + bool updateDecision(Kernel::IBox& box) + { + const size_t i = getStrategyIndex() + 1; + if (m_strategyClassID == OVP_ClassId_Algorithm_ClassifierOneVsOne) + { + CString classifierName = "Unknown"; + box.getSettingValue(getClassifierIndex(box), classifierName); + const CIdentifier typeID = this->getTypeManager().getEnumerationEntryValueFromName( + OVP_TypeId_OneVsOne_DecisionAlgorithms, classifierName); - if (settingName.find("Class ") == std::string::npos)//We haven't initialized the box so let's do it - { - //Now added Settings for classes - for (size_t i = 1; i < box.getInputCount(); ++i) - { - const std::string name = "Class " + std::to_string(i) + " label"; - std::stringstream stim; - stim.fill('0'); - stim << "OVTK_StimulationId_Label_" << std::setw(2) << i; - box.addSetting(name.c_str(), OV_TypeId_Stimulation, stim.str().c_str(), 3 - 1 + getStrategySettingsCount(box) + i); - DEBUG_PRINT(std::cout << "Add setting (type D) " << buffer << " " << stimulation << "\n";) - } - return this->onAlgorithmClassifierChanged(box); - } - return true; - //return this->onAlgorithmClassifierChanged(box); - } + OV_ERROR_UNLESS_KRF(typeID != OV_UndefinedIdentifier, + "Unable to find Pairwise Decision for the algorithm [" << m_classifierClassID.str() << "] (" << classifierName << ")", + Kernel::ErrorType::BadConfig); - //Return the index of the combo box used to select the strategy (native/ OnevsOne...) - static size_t getStrategyIndex() { return 2; } + Kernel::IParameter* param = m_strategy->getInputParameter(OVP_Algorithm_OneVsOneStrategy_InputParameterId_DecisionType); + Kernel::TParameterHandler<uint64_t> ip_parameter(param); - //Return the index of the combo box used to select the classification algorithm - size_t getClassifierIndex(Kernel::IBox& box) { return getStrategySettingsCount(box) + 3 + box.getInputCount() - 1; } + const CString entry = this->getTypeManager().getTypeName(typeID); + uint64_t value = ip_parameter; + uint64_t idx; + CString name; - bool onSettingValueChanged(Kernel::IBox& box, const size_t index) override - { - if (index == getClassifierIndex(box)) { return this->onAlgorithmClassifierChanged(box); } - if (index == getStrategyIndex()) { return this->onStrategyChanged(box); } - return true; - } + box.getSettingValue(i, name); + const uint64_t oldID = this->getTypeManager().getEnumerationEntryValueFromName(typeID, name); + if (oldID == OV_UndefinedIdentifier + ) { idx = 0; } //The previous strategy does not exists in the new enum, let's switch to the default value (the first) + else { idx = oldID; } - bool updateDecision(Kernel::IBox& box) - { - const size_t i = getStrategyIndex() + 1; - if (m_strategyClassID == OVP_ClassId_Algorithm_ClassifierOneVsOne) - { - CString classifierName = "Unknown"; - box.getSettingValue(getClassifierIndex(box), classifierName); - const CIdentifier typeID = this->getTypeManager().getEnumerationEntryValueFromName( - OVP_TypeId_OneVsOne_DecisionAlgorithms, classifierName); + this->getTypeManager().getEnumerationEntry(typeID, idx, name, value); + ip_parameter = value; - OV_ERROR_UNLESS_KRF(typeID != OV_UndefinedIdentifier, - "Unable to find Pairwise Decision for the algorithm [" << m_classifierClassID.str() << "] (" << classifierName << - ")", - Kernel::ErrorType::BadConfig); + box.setSettingType(i, typeID); + box.setSettingName(i, entry); + box.setSettingValue(i, name); + } + return true; + } - Kernel::IParameter* param = m_strategy->getInputParameter(OVP_Algorithm_OneVsOneStrategy_InputParameterId_DecisionType); - Kernel::TParameterHandler<uint64_t> ip_parameter(param); + bool onStrategyChanged(Kernel::IBox& box) + { + CString name; - const CString entry = this->getTypeManager().getTypeName(typeID); - uint64_t value = ip_parameter; - uint64_t idx; - CString name; + box.getSettingValue(getStrategyIndex(), name); - box.getSettingValue(i, name); + const CIdentifier id = this->getTypeManager().getEnumerationEntryValueFromName( + OVTK_TypeId_ClassificationStrategy, name); + if (id != m_strategyClassID) + { + if (m_strategy) + { + m_strategy->uninitialize(); + this->getAlgorithmManager().releaseAlgorithm(*m_strategy); + m_strategy = nullptr; + m_strategyClassID = OV_UndefinedIdentifier; + } + if (id != OV_UndefinedIdentifier) + { + m_strategy = &this->getAlgorithmManager().getAlgorithm(this->getAlgorithmManager().createAlgorithm(id)); + m_strategy->initialize(); + m_strategyClassID = id; + } - const uint64_t oldID = this->getTypeManager().getEnumerationEntryValueFromName(typeID, name); - if (oldID == OV_UndefinedIdentifier - ) { idx = 0; } //The previous strategy does not exists in the new enum, let's switch to the default value (the first) - else { idx = oldID; } + for (size_t i = getStrategyIndex() + getStrategySettingsCount(box); i > getStrategyIndex(); --i) + { + DEBUG_PRINT(std::cout << "Remove pairing strategy setting at idx " << i-1 << "\n";) + box.removeSetting(i); + } + m_strategyAmountSettings = 0; + } + else { return true; } //If we don't change the strategy we just have to return + + if (m_strategy) + { + box.getSettingValue(getClassifierIndex(box), name); + const size_t i = getStrategyIndex() + 1; + if (m_strategyClassID == OVP_ClassId_Algorithm_ClassifierOneVsOne) + { + const CIdentifier typeID = this->getTypeManager().getEnumerationEntryValueFromName( + OVP_TypeId_OneVsOne_DecisionAlgorithms, name); + OV_ERROR_UNLESS_KRF(typeID != OV_UndefinedIdentifier, + "Unable to find Pairwise Decision for the algorithm [" << m_classifierClassID.str() << "]", + Kernel::ErrorType::BadConfig); - this->getTypeManager().getEnumerationEntry(typeID, idx, name, value); - ip_parameter = value; + //As we just switch to this strategy, we take the default value set in the strategy to initialize the value + Kernel::IParameter* param = m_strategy->getInputParameter(OVP_Algorithm_OneVsOneStrategy_InputParameterId_DecisionType); + const Kernel::TParameterHandler<uint64_t> ip_param(param); + const uint64_t value = ip_param; + name = this->getTypeManager().getEnumerationEntryNameFromValue(typeID, value); - box.setSettingType(i, typeID); - box.setSettingName(i, entry); - box.setSettingValue(i, name); - } - return true; - } + const CString paramName = this->getTypeManager().getTypeName(typeID); - bool onStrategyChanged(Kernel::IBox& box) - { - CString name; + DEBUG_PRINT(std::cout << "Adding setting (case C) " << paramName << " : '" << name << "' to index " << i << "\n";) + box.addSetting(paramName, typeID, name, i); - box.getSettingValue(getStrategyIndex(), name); + m_strategyAmountSettings = 1; + } + } - const CIdentifier id = this->getTypeManager().getEnumerationEntryValueFromName( - OVTK_TypeId_ClassificationStrategy, name); - if (id != m_strategyClassID) - { - if (m_strategy) - { - m_strategy->uninitialize(); - this->getAlgorithmManager().releaseAlgorithm(*m_strategy); - m_strategy = nullptr; - m_strategyClassID = OV_UndefinedIdentifier; - } - if (id != OV_UndefinedIdentifier) - { - m_strategy = &this->getAlgorithmManager().getAlgorithm(this->getAlgorithmManager().createAlgorithm(id)); - m_strategy->initialize(); - m_strategyClassID = id; - } - - for (size_t i = getStrategyIndex() + getStrategySettingsCount(box); i > getStrategyIndex(); --i) - { - DEBUG_PRINT(std::cout << "Remove pairing strategy setting at idx " << i-1 << "\n";) - box.removeSetting(i); - } - m_strategyAmountSettings = 0; - } - else { return true; } //If we don't change the strategy we just have to return + return true; + } - if (m_strategy) - { - box.getSettingValue(getClassifierIndex(box), name); - const size_t i = getStrategyIndex() + 1; - if (m_strategyClassID == OVP_ClassId_Algorithm_ClassifierOneVsOne) - { - const CIdentifier typeID = this->getTypeManager().getEnumerationEntryValueFromName( - OVP_TypeId_OneVsOne_DecisionAlgorithms, name); - OV_ERROR_UNLESS_KRF(typeID != OV_UndefinedIdentifier, - "Unable to find Pairwise Decision for the algorithm [" << m_classifierClassID.str() << "]", - Kernel::ErrorType::BadConfig); - - //As we just switch to this strategy, we take the default value set in the strategy to initialize the value - Kernel::IParameter* param = m_strategy->getInputParameter(OVP_Algorithm_OneVsOneStrategy_InputParameterId_DecisionType); - const Kernel::TParameterHandler<uint64_t> ip_param(param); - const uint64_t value = ip_param; - name = this->getTypeManager().getEnumerationEntryNameFromValue(typeID, value); - - const CString paramName = this->getTypeManager().getTypeName(typeID); - - DEBUG_PRINT(std::cout << "Adding setting (case C) " << paramName << " : '" << name << "' to index " << i << "\n";) - box.addSetting(paramName, typeID, name, i); - - m_strategyAmountSettings = 1; - } - } + bool onAlgorithmClassifierChanged(Kernel::IBox& box) + { + CString name; + box.getSettingValue(getClassifierIndex(box), name); + CIdentifier id = this->getTypeManager().getEnumerationEntryValueFromName(OVTK_TypeId_ClassificationAlgorithm, name); + if (id != m_classifierClassID) + { + if (m_classifier) + { + m_classifier->uninitialize(); + this->getAlgorithmManager().releaseAlgorithm(*m_classifier); + m_classifier = nullptr; + m_classifierClassID = OV_UndefinedIdentifier; + } + if (id != OV_UndefinedIdentifier) + { + m_classifier = &this->getAlgorithmManager().getAlgorithm(this->getAlgorithmManager().createAlgorithm(id)); + m_classifier->initialize(); + m_classifierClassID = id; + } - return true; - } + //Disable the graphical refresh to avoid abusive redraw (not really a problem) + while (box.getSettingCount() >= m_customSettingBase + box.getInputCount() + getStrategySettingsCount(box)) + { + box.removeSetting(getClassifierIndex(box) + 1); + } + } + else { return true; }//If we don't change the algorithm we just have to return - bool onAlgorithmClassifierChanged(Kernel::IBox& box) + if (m_classifier) + { + size_t i = getClassifierIndex(box) + 1; + while ((id = m_classifier->getNextInputParameterIdentifier(id)) != OV_UndefinedIdentifier) + { + if ((id != OVTK_Algorithm_Classifier_InputParameterId_FeatureVector) + && (id != OVTK_Algorithm_Classifier_InputParameterId_FeatureVectorSet) + && (id != OVTK_Algorithm_Classifier_InputParameterId_Config) + && (id != OVTK_Algorithm_Classifier_InputParameterId_NClasses) + && (id != OVTK_Algorithm_Classifier_InputParameterId_ExtraParameter)) { - CString name; - box.getSettingValue(getClassifierIndex(box), name); - CIdentifier id = this->getTypeManager().getEnumerationEntryValueFromName(OVTK_TypeId_ClassificationAlgorithm, name); - if (id != m_classifierClassID) + CIdentifier typeID; + CString paramName = m_classifier->getInputParameterName(id); + Kernel::IParameter* param = m_classifier->getInputParameter(id); + Kernel::TParameterHandler<int64_t> ip_iParameter(param); + Kernel::TParameterHandler<uint64_t> ip_uiParameter(param); + Kernel::TParameterHandler<double> ip_dParameter(param); + Kernel::TParameterHandler<bool> ip_bParameter(param); + Kernel::TParameterHandler<CString*> ip_sParameter(param); + std::string buffer; + bool valid = true; + switch (param->getType()) { - if (m_classifier) - { - m_classifier->uninitialize(); - this->getAlgorithmManager().releaseAlgorithm(*m_classifier); - m_classifier = nullptr; - m_classifierClassID = OV_UndefinedIdentifier; - } - if (id != OV_UndefinedIdentifier) - { - m_classifier = &this->getAlgorithmManager().getAlgorithm(this->getAlgorithmManager().createAlgorithm(id)); - m_classifier->initialize(); - m_classifierClassID = id; - } - - //Disable the graphical refresh to avoid abusive redraw (not really a problem) - while (box.getSettingCount() >= m_customSettingBase + box.getInputCount() + getStrategySettingsCount(box)) - { - box.removeSetting(getClassifierIndex(box) + 1); - } + case Kernel::ParameterType_Enumeration: + buffer = this->getTypeManager().getEnumerationEntryNameFromValue(param->getSubTypeIdentifier(), ip_uiParameter).toASCIIString(); + typeID = param->getSubTypeIdentifier(); + break; + + case Kernel::ParameterType_Integer: + case Kernel::ParameterType_UInteger: + buffer = std::to_string(int64_t(ip_iParameter)); + typeID = OV_TypeId_Integer; + break; + + case Kernel::ParameterType_Boolean: + buffer = (bool(ip_bParameter)) ? "true" : "false"; + typeID = OV_TypeId_Boolean; + break; + + case Kernel::ParameterType_Float: + buffer = std::to_string(double(ip_dParameter)); + typeID = OV_TypeId_Float; + break; + case Kernel::ParameterType_String: + buffer = static_cast<CString*>(ip_sParameter)->toASCIIString(); + typeID = OV_TypeId_String; + break; + default: + std::cout << "Invalid parameter type " << param->getType() << "\n"; + valid = false; + break; } - else { return true; }//If we don't change the algorithm we just have to return - if (m_classifier) + if (valid) { - size_t i = getClassifierIndex(box) + 1; - while ((id = m_classifier->getNextInputParameterIdentifier(id)) != OV_UndefinedIdentifier) - { - if ((id != OVTK_Algorithm_Classifier_InputParameterId_FeatureVector) - && (id != OVTK_Algorithm_Classifier_InputParameterId_FeatureVectorSet) - && (id != OVTK_Algorithm_Classifier_InputParameterId_Config) - && (id != OVTK_Algorithm_Classifier_InputParameterId_NClasses) - && (id != OVTK_Algorithm_Classifier_InputParameterId_ExtraParameter)) - { - CIdentifier typeID; - CString paramName = m_classifier->getInputParameterName(id); - Kernel::IParameter* param = m_classifier->getInputParameter(id); - Kernel::TParameterHandler<int64_t> ip_iParameter(param); - Kernel::TParameterHandler<uint64_t> ip_uiParameter(param); - Kernel::TParameterHandler<double> ip_dParameter(param); - Kernel::TParameterHandler<bool> ip_bParameter(param); - Kernel::TParameterHandler<CString*> ip_sParameter(param); - std::string buffer; - bool valid = true; - switch (param->getType()) - { - case Kernel::ParameterType_Enumeration: - buffer = this->getTypeManager().getEnumerationEntryNameFromValue(param->getSubTypeIdentifier(), ip_uiParameter). - toASCIIString(); - typeID = param->getSubTypeIdentifier(); - break; - - case Kernel::ParameterType_Integer: - case Kernel::ParameterType_UInteger: - buffer = std::to_string(int64_t(ip_iParameter)); - typeID = OV_TypeId_Integer; - break; - - case Kernel::ParameterType_Boolean: - buffer = (bool(ip_bParameter)) ? "true" : "false"; - typeID = OV_TypeId_Boolean; - break; - - case Kernel::ParameterType_Float: - buffer = std::to_string(double(ip_dParameter)); - typeID = OV_TypeId_Float; - break; - case Kernel::ParameterType_String: - buffer = static_cast<CString*>(ip_sParameter)->toASCIIString(); - typeID = OV_TypeId_String; - break; - default: - std::cout << "Invalid parameter type " << param->getType() << "\n"; - valid = false; - break; - } - - if (valid) - { - // @FIXME argh, the -2 is a hard coding that the classifier trainer has 2 settings after the classifier setting... ouch - DEBUG_PRINT(std::cout << "Adding setting (case A) " << paramName << " : " << buffer << " to slot " - << box.getSettingCount() - 2 << "\n";) - box.addSetting(paramName, typeID, buffer.c_str(), box.getSettingCount() - 2); - i++; - } - } - } + // @FIXME argh, the -2 is a hard coding that the classifier trainer has 2 settings after the classifier setting... ouch + DEBUG_PRINT(std::cout << "Adding setting (case A) " << paramName << " : " << buffer << " to slot " + << box.getSettingCount() - 2 << "\n";) + box.addSetting(paramName, typeID, buffer.c_str(), box.getSettingCount() - 2); + i++; } - // This changes the pairwise strategy decision voting type of the box settings allowing - // designer to list the correct choices in the combo box. - updateDecision(box); - return true; } - - _IsDerivedFromClass_Final_(Toolkit::TBoxListener<IBoxListener>, OV_UndefinedIdentifier) - - protected: - - CIdentifier m_classifierClassID = OV_UndefinedIdentifier; - CIdentifier m_strategyClassID = - 0x0; // OV_UndefinedIdentifier is already use, We initialize to an unused identifier in the strategy list - Kernel::IAlgorithmProxy* m_classifier = nullptr; - Kernel::IAlgorithmProxy* m_strategy = nullptr; - const size_t m_customSettingBase = 0; - int m_strategyAmountSettings = -1; - }; - } // namespace Classification - } // namespace Plugins + } + } + // This changes the pairwise strategy decision voting type of the box settings allowing + // designer to list the correct choices in the combo box. + updateDecision(box); + return true; + } + + _IsDerivedFromClass_Final_(Toolkit::TBoxListener<IBoxListener>, OV_UndefinedIdentifier) + +protected: + + CIdentifier m_classifierClassID = OV_UndefinedIdentifier; + CIdentifier m_strategyClassID = + 0x0; // OV_UndefinedIdentifier is already use, We initialize to an unused identifier in the strategy list + Kernel::IAlgorithmProxy* m_classifier = nullptr; + Kernel::IAlgorithmProxy* m_strategy = nullptr; + const size_t m_customSettingBase = 0; + int m_strategyAmountSettings = -1; +}; +} // namespace Classification +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/classification/src/box-algorithms/ovpCBoxAlgorithmVotingClassifier.h b/plugins/processing/classification/src/box-algorithms/ovpCBoxAlgorithmVotingClassifier.h index 985cf9335a5b8cb35fd2ce4f4dff8fe9bd2671f5..8c9ef8f0d7aa111cbfab739516b41eebf76ee7cf 100644 --- a/plugins/processing/classification/src/box-algorithms/ovpCBoxAlgorithmVotingClassifier.h +++ b/plugins/processing/classification/src/box-algorithms/ovpCBoxAlgorithmVotingClassifier.h @@ -7,133 +7,130 @@ #include <vector> #include <map> -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace Classification { +class CBoxAlgorithmVotingClassifier final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm> { - namespace Plugins +public: + void release() override { delete this; } + bool initialize() override; + bool uninitialize() override; + bool processInput(const size_t index) override; + bool process() override; + + _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_VotingClassifier) + +protected: + + size_t m_nRepetitions = 0; + size_t m_targetClassLabel = 0; + size_t m_nonTargetClassLabel = 0; + size_t m_rejectClassLabel = 0; + size_t m_resultClassLabelBase = 0; + bool m_chooseOneIfExAequo = false; + +private: + + typedef struct { - namespace Classification + Toolkit::TDecoder<CBoxAlgorithmVotingClassifier>* decoder = nullptr; + Kernel::TParameterHandler<IStimulationSet*> op_stimSet; + Kernel::TParameterHandler<IMatrix*> op_matrix; + bool twoValueInput; + std::vector<std::pair<double, uint64_t>> scores; + } input_t; + + std::map<uint32_t, input_t> m_results; + + Toolkit::TStimulationEncoder<CBoxAlgorithmVotingClassifier> m_classificationChoiceEncoder; + Kernel::TParameterHandler<const IStimulationSet*> ip_classificationChoiceStimSet; + + uint64_t m_lastTime = 0; + bool m_matrixBased = false; +}; + + +class CBoxAlgorithmVotingClassifierListener final : public Toolkit::TBoxListener<IBoxListener> +{ +public: + + CBoxAlgorithmVotingClassifierListener() : m_inputTypeID(OV_TypeId_Stimulations) { } + + bool onInputTypeChanged(Kernel::IBox& box, const size_t index) override + { + CIdentifier id = OV_UndefinedIdentifier; + box.getInputType(index, id); + if (id == OV_TypeId_Stimulations || id == OV_TypeId_StreamedMatrix) + { + m_inputTypeID = id; + for (size_t i = 0; i < box.getInputCount(); ++i) { box.setInputType(i, m_inputTypeID); } + } + else { box.setInputType(index, m_inputTypeID); } + return true; + } + + bool onInputAdded(Kernel::IBox& box, const size_t /*index*/) override + { + for (size_t i = 0; i < box.getInputCount(); ++i) { - class CBoxAlgorithmVotingClassifier final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm> - { - public: - void release() override { delete this; } - bool initialize() override; - bool uninitialize() override; - bool processInput(const size_t index) override; - bool process() override; - - _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_VotingClassifier) - - protected: - - size_t m_nRepetitions = 0; - size_t m_targetClassLabel = 0; - size_t m_nonTargetClassLabel = 0; - size_t m_rejectClassLabel = 0; - size_t m_resultClassLabelBase = 0; - bool m_chooseOneIfExAequo = false; - - private: - - typedef struct - { - Toolkit::TDecoder<CBoxAlgorithmVotingClassifier>* decoder = nullptr; - Kernel::TParameterHandler<IStimulationSet*> op_stimSet; - Kernel::TParameterHandler<IMatrix*> op_matrix; - bool twoValueInput; - std::vector<std::pair<double, uint64_t>> scores; - } input_t; - - std::map<uint32_t, input_t> m_results; - - Toolkit::TStimulationEncoder<CBoxAlgorithmVotingClassifier> m_classificationChoiceEncoder; - Kernel::TParameterHandler<const IStimulationSet*> ip_classificationChoiceStimSet; - - uint64_t m_lastTime = 0; - bool m_matrixBased = false; - }; - - - class CBoxAlgorithmVotingClassifierListener final : public Toolkit::TBoxListener<IBoxListener> - { - public: - - CBoxAlgorithmVotingClassifierListener() : m_inputTypeID(OV_TypeId_Stimulations) { } - - bool onInputTypeChanged(Kernel::IBox& box, const size_t index) override - { - CIdentifier id = OV_UndefinedIdentifier; - box.getInputType(index, id); - if (id == OV_TypeId_Stimulations || id == OV_TypeId_StreamedMatrix) - { - m_inputTypeID = id; - for (size_t i = 0; i < box.getInputCount(); ++i) { box.setInputType(i, m_inputTypeID); } - } - else { box.setInputType(index, m_inputTypeID); } - return true; - } - - bool onInputAdded(Kernel::IBox& box, const size_t /*index*/) override - { - for (size_t i = 0; i < box.getInputCount(); ++i) - { - box.setInputType(i, m_inputTypeID); - box.setInputName(i, ("Classification result " + std::to_string(i)).c_str()); - } - return true; - } - - _IsDerivedFromClass_Final_(Toolkit::TBoxListener<IBoxListener>, OV_UndefinedIdentifier) - - protected: - - CIdentifier m_inputTypeID = OV_UndefinedIdentifier; - }; - - class CBoxAlgorithmVotingClassifierDesc final : public IBoxAlgorithmDesc - { - public: - void release() override { } - CString getName() const override { return CString("Voting Classifier"); } - CString getAuthorName() const override { return CString("Yann Renard"); } - CString getAuthorCompanyName() const override { return CString("INRIA"); } - CString getShortDescription() const override { return CString("Majority voting classifier. Returns the chosen class."); } - - CString getDetailedDescription() const override - { - return CString( - "Each classifier used as input is assumed to have its own two-class output stream. Mainly designed for P300 scenario use."); - } - - CString getCategory() const override { return CString("Classification"); } - CString getVersion() const override { return CString("1.0"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_VotingClassifier; } - IPluginObject* create() override { return new CBoxAlgorithmVotingClassifier; } - - bool getBoxPrototype(Kernel::IBoxProto& prototype) const override - { - prototype.addInput("Classification result 1", OV_TypeId_Stimulations); - prototype.addInput("Classification result 2", OV_TypeId_Stimulations); - prototype.addOutput("Classification choice", OV_TypeId_Stimulations); - prototype.addSetting("Number of repetitions", OV_TypeId_Integer, "12"); - prototype.addSetting("Target class label", OV_TypeId_Stimulation, "OVTK_StimulationId_Target"); - prototype.addSetting("Non target class label", OV_TypeId_Stimulation, "OVTK_StimulationId_NonTarget"); - prototype.addSetting("Reject class label", OV_TypeId_Stimulation, "OVTK_StimulationId_Label_00"); - prototype.addSetting("Result class label base", OV_TypeId_Stimulation, "OVTK_StimulationId_Label_01"); - prototype.addSetting("Choose one if ex-aequo", OV_TypeId_Boolean, "false"); - prototype.addFlag(Kernel::BoxFlag_CanAddInput); - prototype.addFlag(Kernel::BoxFlag_CanModifyInput); - return true; - } - - IBoxListener* createBoxListener() const override { return new CBoxAlgorithmVotingClassifierListener; } - void releaseBoxListener(IBoxListener* listener) const override { delete listener; } - - _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_VotingClassifierDesc) - }; - } // namespace Classification - } // namespace Plugins + box.setInputType(i, m_inputTypeID); + box.setInputName(i, ("Classification result " + std::to_string(i)).c_str()); + } + return true; + } + + _IsDerivedFromClass_Final_(Toolkit::TBoxListener<IBoxListener>, OV_UndefinedIdentifier) + +protected: + + CIdentifier m_inputTypeID = OV_UndefinedIdentifier; +}; + +class CBoxAlgorithmVotingClassifierDesc final : public IBoxAlgorithmDesc +{ +public: + void release() override { } + CString getName() const override { return CString("Voting Classifier"); } + CString getAuthorName() const override { return CString("Yann Renard"); } + CString getAuthorCompanyName() const override { return CString("INRIA"); } + CString getShortDescription() const override { return CString("Majority voting classifier. Returns the chosen class."); } + + CString getDetailedDescription() const override + { + return CString( + "Each classifier used as input is assumed to have its own two-class output stream. Mainly designed for P300 scenario use."); + } + + CString getCategory() const override { return CString("Classification"); } + CString getVersion() const override { return CString("1.0"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_VotingClassifier; } + IPluginObject* create() override { return new CBoxAlgorithmVotingClassifier; } + + bool getBoxPrototype(Kernel::IBoxProto& prototype) const override + { + prototype.addInput("Classification result 1", OV_TypeId_Stimulations); + prototype.addInput("Classification result 2", OV_TypeId_Stimulations); + prototype.addOutput("Classification choice", OV_TypeId_Stimulations); + prototype.addSetting("Number of repetitions", OV_TypeId_Integer, "12"); + prototype.addSetting("Target class label", OV_TypeId_Stimulation, "OVTK_StimulationId_Target"); + prototype.addSetting("Non target class label", OV_TypeId_Stimulation, "OVTK_StimulationId_NonTarget"); + prototype.addSetting("Reject class label", OV_TypeId_Stimulation, "OVTK_StimulationId_Label_00"); + prototype.addSetting("Result class label base", OV_TypeId_Stimulation, "OVTK_StimulationId_Label_01"); + prototype.addSetting("Choose one if ex-aequo", OV_TypeId_Boolean, "false"); + prototype.addFlag(Kernel::BoxFlag_CanAddInput); + prototype.addFlag(Kernel::BoxFlag_CanModifyInput); + return true; + } + + IBoxListener* createBoxListener() const override { return new CBoxAlgorithmVotingClassifierListener; } + void releaseBoxListener(IBoxListener* listener) const override { delete listener; } + + _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_VotingClassifierDesc) +}; +} // namespace Classification +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/data-generation/CMakeLists.txt b/plugins/processing/data-generation/CMakeLists.txt index 4377f7383f2df01d57b1504e73052cbbb22ff8d2..dea937576d19ea499ed239089adc5135c29ba907 100644 --- a/plugins/processing/data-generation/CMakeLists.txt +++ b/plugins/processing/data-generation/CMakeLists.txt @@ -11,6 +11,7 @@ ADD_LIBRARY(${PROJECT_NAME} SHARED ${SRC_FILES}) SET_TARGET_PROPERTIES(${PROJECT_NAME} PROPERTIES VERSION ${PROJECT_VERSION} SOVERSION ${PROJECT_VERSION_MAJOR} + FOLDER ${PLUGINS_FOLDER} COMPILE_FLAGS "-DOVP_Exports -DOVP_Shared") # --------------------------------- @@ -22,9 +23,7 @@ INCLUDE("FindOpenViBEModuleXML") # --------------------------------- # Target macros -# Defines target operating system -# Defines target architecture -# Defines target compiler +# Defines target operating system, architecture and compiler # --------------------------------- SET_BUILD_PLATFORM() diff --git a/plugins/processing/data-generation/src/box-algorithms/ovpCBoxAlgorithmTimeSignalGenerator.cpp b/plugins/processing/data-generation/src/box-algorithms/ovpCBoxAlgorithmTimeSignalGenerator.cpp index fb54b7d1acaf6c9ed3d80a8da3cb32a61bbfa419..ac398eed0e6127bc4bd2fd686a666ce70bc75643 100644 --- a/plugins/processing/data-generation/src/box-algorithms/ovpCBoxAlgorithmTimeSignalGenerator.cpp +++ b/plugins/processing/data-generation/src/box-algorithms/ovpCBoxAlgorithmTimeSignalGenerator.cpp @@ -32,7 +32,7 @@ bool CBoxAlgorithmTimeSignalGenerator::uninitialize() return true; } -bool CBoxAlgorithmTimeSignalGenerator::processClock(CMessageClock& /*messageClock*/) +bool CBoxAlgorithmTimeSignalGenerator::processClock(CMessageClock& /*msg*/) { this->getBoxAlgorithmContext()->markAlgorithmAsReadyToProcess(); return true; diff --git a/plugins/processing/data-generation/src/box-algorithms/ovpCBoxAlgorithmTimeSignalGenerator.h b/plugins/processing/data-generation/src/box-algorithms/ovpCBoxAlgorithmTimeSignalGenerator.h index 620d814937fc99f06334d35c9bb2976a38158baf..7580ee2602968883e0a6d1887289e517ef59b4d4 100644 --- a/plugins/processing/data-generation/src/box-algorithms/ovpCBoxAlgorithmTimeSignalGenerator.h +++ b/plugins/processing/data-generation/src/box-algorithms/ovpCBoxAlgorithmTimeSignalGenerator.h @@ -5,71 +5,68 @@ #include <toolkit/ovtk_all.h> -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace DataGeneration { +class CBoxAlgorithmTimeSignalGenerator final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm> { - namespace Plugins - { - namespace DataGeneration - { - class CBoxAlgorithmTimeSignalGenerator final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm> - { - public: - - CBoxAlgorithmTimeSignalGenerator(); - - void release() override; +public: - uint64_t getClockFrequency() override { return 128LL << 32; } + CBoxAlgorithmTimeSignalGenerator(); - bool initialize() override; - bool uninitialize() override; + void release() override; - bool processClock(Kernel::IMessageClock& messageClock) override; - bool process() override; + uint64_t getClockFrequency() override { return 128LL << 32; } - _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_TimeSignalGenerator) + bool initialize() override; + bool uninitialize() override; - protected: + bool processClock(Kernel::CMessageClock& msg) override; + bool process() override; - Toolkit::TSignalEncoder<CBoxAlgorithmTimeSignalGenerator> m_encoder; + _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_TimeSignalGenerator) - bool m_headerSent = false; - size_t m_sampling = 0; - size_t m_nGeneratedEpochSample = 0; - size_t m_nSentSample = 0; - }; +protected: - class CBoxAlgorithmTimeSignalGeneratorDesc final : public IBoxAlgorithmDesc - { - public: + Toolkit::TSignalEncoder<CBoxAlgorithmTimeSignalGenerator> m_encoder; - void release() override { } - CString getName() const override { return CString("Time signal"); } - CString getAuthorName() const override { return CString("Yann Renard"); } - CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } - CString getShortDescription() const override { return CString("Simple time signal generator (for use with DSP)"); } - CString getDetailedDescription() const override { return CString(""); } - CString getCategory() const override { return CString("Data generation"); } - CString getVersion() const override { return CString("1.1"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.4.0"); } + bool m_headerSent = false; + size_t m_sampling = 0; + size_t m_nGeneratedEpochSample = 0; + size_t m_nSentSample = 0; +}; - CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_TimeSignalGenerator; } - IPluginObject* create() override { return new CBoxAlgorithmTimeSignalGenerator(); } - - bool getBoxPrototype(Kernel::IBoxProto& prototype) const override - { - prototype.addOutput("Generated signal", OV_TypeId_Signal); +class CBoxAlgorithmTimeSignalGeneratorDesc final : public IBoxAlgorithmDesc +{ +public: + + void release() override { } + CString getName() const override { return CString("Time signal"); } + CString getAuthorName() const override { return CString("Yann Renard"); } + CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } + CString getShortDescription() const override { return CString("Simple time signal generator (for use with DSP)"); } + CString getDetailedDescription() const override { return CString(""); } + CString getCategory() const override { return CString("Data generation"); } + CString getVersion() const override { return CString("1.1"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.4.0"); } + + CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_TimeSignalGenerator; } + IPluginObject* create() override { return new CBoxAlgorithmTimeSignalGenerator(); } + + bool getBoxPrototype(Kernel::IBoxProto& prototype) const override + { + prototype.addOutput("Generated signal", OV_TypeId_Signal); - prototype.addSetting("Sampling frequency", OV_TypeId_Integer, "512"); - prototype.addSetting("Generated epoch sample count", OV_TypeId_Integer, "32"); + prototype.addSetting("Sampling frequency", OV_TypeId_Integer, "512"); + prototype.addSetting("Generated epoch sample count", OV_TypeId_Integer, "32"); - return true; - } + return true; + } - _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_TimeSignalGeneratorDesc) - }; - } // namespace DataGeneration - } // namespace Plugins + _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_TimeSignalGeneratorDesc) +}; +} // namespace DataGeneration +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/data-generation/src/ovp_main.cpp b/plugins/processing/data-generation/src/ovp_main.cpp index 7a50ad6437dace2cad272dc6f0e33ed97ad208af..514153dd0bfeacf61614dd4cf846a9daf50dfdf9 100644 --- a/plugins/processing/data-generation/src/ovp_main.cpp +++ b/plugins/processing/data-generation/src/ovp_main.cpp @@ -8,5 +8,4 @@ using namespace /*OpenViBE::*/Plugins; OVP_Declare_Begin() OVP_Declare_New(DataGeneration::CBoxAlgorithmTimeSignalGeneratorDesc); - OVP_Declare_End() diff --git a/plugins/processing/feature-extraction/CMakeLists.txt b/plugins/processing/feature-extraction/CMakeLists.txt index 512ab9550a2340145fee1881ff2682230128476e..cc13fca0087ed3602576e3f31385389ae182b6ec 100644 --- a/plugins/processing/feature-extraction/CMakeLists.txt +++ b/plugins/processing/feature-extraction/CMakeLists.txt @@ -10,6 +10,7 @@ ADD_LIBRARY(${PROJECT_NAME} SHARED ${SRC_FILES}) SET_TARGET_PROPERTIES(${PROJECT_NAME} PROPERTIES VERSION ${PROJECT_VERSION} SOVERSION ${PROJECT_VERSION_MAJOR} + FOLDER ${PLUGINS_FOLDER} COMPILE_FLAGS "-DOVP_Exports -DOVP_Shared") # --------------------------------- @@ -20,9 +21,7 @@ INCLUDE("FindOpenViBEModuleEBML") # --------------------------------- # Target macros -# Defines target operating system -# Defines target architecture -# Defines target compiler +# Defines target operating system, architecture and compiler # --------------------------------- SET_BUILD_PLATFORM() diff --git a/plugins/processing/feature-extraction/src/box-algorithms/ovpCBoxAlgorithmFeatureAggregator.cpp b/plugins/processing/feature-extraction/src/box-algorithms/ovpCBoxAlgorithmFeatureAggregator.cpp index bed0320ed595be91a8529aa1df87b51553db4798..928008044be1e25491d4bf0075b5a2af27a9b61d 100644 --- a/plugins/processing/feature-extraction/src/box-algorithms/ovpCBoxAlgorithmFeatureAggregator.cpp +++ b/plugins/processing/feature-extraction/src/box-algorithms/ovpCBoxAlgorithmFeatureAggregator.cpp @@ -11,159 +11,155 @@ using namespace /*OpenViBE::*/Toolkit; using namespace std; -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace FeatureExtraction { +bool CBoxAlgorithmFeatureAggregator::initialize() { - namespace Plugins + m_nInput = getBoxAlgorithmContext()->getStaticBoxContext()->getInputCount(); + + // Prepares decoders + for (size_t i = 0; i < m_nInput; ++i) { - namespace FeatureExtraction - { - bool CBoxAlgorithmFeatureAggregator::initialize() - { - m_nInput = getBoxAlgorithmContext()->getStaticBoxContext()->getInputCount(); + TStreamedMatrixDecoder<CBoxAlgorithmFeatureAggregator>* streamedMatrixDecoder = new TStreamedMatrixDecoder<CBoxAlgorithmFeatureAggregator>(); + m_decoder.push_back(streamedMatrixDecoder); + m_decoder.back()->initialize(*this, i); + } + m_encoder = new TFeatureVectorEncoder<CBoxAlgorithmFeatureAggregator>; + m_encoder->initialize(*this, 0); - // Prepares decoders - for (size_t i = 0; i < m_nInput; ++i) - { - TStreamedMatrixDecoder<CBoxAlgorithmFeatureAggregator>* streamedMatrixDecoder = new TStreamedMatrixDecoder<CBoxAlgorithmFeatureAggregator> - (); - m_decoder.push_back(streamedMatrixDecoder); - m_decoder.back()->initialize(*this, i); - } - m_encoder = new TFeatureVectorEncoder<CBoxAlgorithmFeatureAggregator>; - m_encoder->initialize(*this, 0); + //resizes everything as needed + m_iBufferSizes.resize(m_nInput); + m_dimSize.resize(m_nInput); + m_featureNames.resize(m_nInput); - //resizes everything as needed - m_iBufferSizes.resize(m_nInput); - m_dimSize.resize(m_nInput); - m_featureNames.resize(m_nInput); + m_headerSent = false; - m_headerSent = false; + return true; +} - return true; - } +bool CBoxAlgorithmFeatureAggregator::uninitialize() +{ + for (size_t i = 0; i < m_nInput; ++i) + { + if (m_decoder.back()) + { + m_decoder.back()->uninitialize(); + delete m_decoder.back(); + m_decoder.pop_back(); + } + } - bool CBoxAlgorithmFeatureAggregator::uninitialize() - { - for (size_t i = 0; i < m_nInput; ++i) - { - if (m_decoder.back()) - { - m_decoder.back()->uninitialize(); - delete m_decoder.back(); - m_decoder.pop_back(); - } - } + if (m_encoder) + { + m_encoder->uninitialize(); + delete m_encoder; + } - if (m_encoder) - { - m_encoder->uninitialize(); - delete m_encoder; - } + return true; +} - return true; - } +bool CBoxAlgorithmFeatureAggregator::processInput(const size_t index) +{ + IBoxIO* boxIO = getBoxAlgorithmContext()->getDynamicBoxContext(); - bool CBoxAlgorithmFeatureAggregator::processInput(const size_t index) - { - IBoxIO* boxIO = getBoxAlgorithmContext()->getDynamicBoxContext(); + size_t lastBufferChunkSize; + const uint8_t* lastBuffer; - size_t lastBufferChunkSize; - const uint8_t* lastBuffer; + size_t bufferChunkSize; + const uint8_t* buffer; - size_t bufferChunkSize; - const uint8_t* buffer; + //gets the first buffer from the concerned input + boxIO->getInputChunk(index, 0, m_lastChunkStartTime, m_lastChunkEndTime, lastBufferChunkSize, lastBuffer); - //gets the first buffer from the concerned input - boxIO->getInputChunk(index, 0, m_lastChunkStartTime, m_lastChunkEndTime, lastBufferChunkSize, lastBuffer); + uint64_t tStart = 0, tEnd = 0; - uint64_t tStart = 0, tEnd = 0; + bool readyToProcess = true; - bool readyToProcess = true; + //checks every input's first chunk's dates + for (size_t i = 0; i < m_nInput && readyToProcess; ++i) + { + if (boxIO->getInputChunkCount(i) != 0) + { + boxIO->getInputChunk(i, 0, tStart, tEnd, bufferChunkSize, buffer); + //if the first buffers don't have the same starting/ending dates, stop + if (tStart != m_lastChunkStartTime || tEnd != m_lastChunkEndTime) { readyToProcess = false; } - //checks every input's first chunk's dates - for (size_t i = 0; i < m_nInput && readyToProcess; ++i) + //checks for problems, buffer lengths differents... + if (tEnd - tStart != m_lastChunkEndTime - m_lastChunkStartTime) + { + //marks everything as deprecated and sends a error + for (size_t input = 0; input < m_nInput; ++input) { - if (boxIO->getInputChunkCount(i) != 0) - { - boxIO->getInputChunk(i, 0, tStart, tEnd, bufferChunkSize, buffer); - //if the first buffers don't have the same starting/ending dates, stop - if (tStart != m_lastChunkStartTime || tEnd != m_lastChunkEndTime) { readyToProcess = false; } - - //checks for problems, buffer lengths differents... - if (tEnd - tStart != m_lastChunkEndTime - m_lastChunkStartTime) - { - //marks everything as deprecated and sends a error - for (size_t input = 0; input < m_nInput; ++input) - { - for (size_t chunk = 0; chunk < boxIO->getInputChunkCount(input); ++chunk) { boxIO->markInputAsDeprecated(input, chunk); } - } - - //readyToProcess = false; - OV_ERROR_KRF("Invalid incoming input chunks: duration differs between chunks", ErrorType::BadInput); - } - } - else { readyToProcess = false; } + for (size_t chunk = 0; chunk < boxIO->getInputChunkCount(input); ++chunk) { boxIO->markInputAsDeprecated(input, chunk); } } - //If there is one buffer of the same time period per input, process - if (readyToProcess) { getBoxAlgorithmContext()->markAlgorithmAsReadyToProcess(); } - - return true; + //readyToProcess = false; + OV_ERROR_KRF("Invalid incoming input chunks: duration differs between chunks", ErrorType::BadInput); } + } + else { readyToProcess = false; } + } - bool CBoxAlgorithmFeatureAggregator::process() - { - const IBox* boxContext = getBoxAlgorithmContext()->getStaticBoxContext(); - IBoxIO* boxIO = getBoxAlgorithmContext()->getDynamicBoxContext(); + //If there is one buffer of the same time period per input, process + if (readyToProcess) { getBoxAlgorithmContext()->markAlgorithmAsReadyToProcess(); } - IMatrix* oMatrix = m_encoder->getInputMatrix(); - std::vector<double> bufferElements; - size_t totalBufferSize = 0; - bool bufferReceived = false; + return true; +} - for (size_t input = 0; input < boxContext->getInputCount(); ++input) - { - m_decoder[input]->decode(0); - //* - if ((m_decoder[input]->isHeaderReceived()) && !m_headerSent) - { - //getBoxAlgorithmContext()->getPlayerContext()->getLogManager() << LogLevel_Warning << "header " << input << "\n"; - IMatrix* iMatrix = m_decoder[input]->getOutputMatrix(); - totalBufferSize += iMatrix->getBufferElementCount(); - if (input == boxContext->getInputCount() - 1) - { - oMatrix->setDimensionCount(1); - oMatrix->setDimensionSize(0, totalBufferSize); - - for (size_t i = 0; i < totalBufferSize; ++i) { oMatrix->setDimensionLabel(0, i, ("Feature " + std::to_string(i + 1)).c_str()); } - - m_encoder->encodeHeader(); - boxIO->markOutputAsReadyToSend(0, m_lastChunkStartTime, m_lastChunkEndTime); - m_headerSent = true; - } - } - //*/ - if (m_decoder[input]->isBufferReceived()) - { - bufferReceived = true; - IMatrix* iMatrix = m_decoder[input]->getOutputMatrix(); - const size_t size = iMatrix->getBufferElementCount(); - - double* buffer = iMatrix->getBuffer(); - for (size_t i = 0; i < size; ++i) { bufferElements.push_back(buffer[i]); } - } - } +bool CBoxAlgorithmFeatureAggregator::process() +{ + const IBox* boxContext = getBoxAlgorithmContext()->getStaticBoxContext(); + IBoxIO* boxIO = getBoxAlgorithmContext()->getDynamicBoxContext(); - if (m_headerSent && bufferReceived) - { - double* oBuffer = oMatrix->getBuffer(); - for (size_t i = 0; i < bufferElements.size(); ++i) { oBuffer[i] = bufferElements[i]; } - m_encoder->encodeBuffer(); - boxIO->markOutputAsReadyToSend(0, m_lastChunkStartTime, m_lastChunkEndTime); - } + IMatrix* oMatrix = m_encoder->getInputMatrix(); + std::vector<double> bufferElements; + size_t totalBufferSize = 0; + bool bufferReceived = false; - return true; + for (size_t input = 0; input < boxContext->getInputCount(); ++input) + { + m_decoder[input]->decode(0); + //* + if ((m_decoder[input]->isHeaderReceived()) && !m_headerSent) + { + //getBoxAlgorithmContext()->getPlayerContext()->getLogManager() << LogLevel_Warning << "header " << input << "\n"; + IMatrix* iMatrix = m_decoder[input]->getOutputMatrix(); + totalBufferSize += iMatrix->getBufferElementCount(); + if (input == boxContext->getInputCount() - 1) + { + oMatrix->setDimensionCount(1); + oMatrix->setDimensionSize(0, totalBufferSize); + + for (size_t i = 0; i < totalBufferSize; ++i) { oMatrix->setDimensionLabel(0, i, ("Feature " + std::to_string(i + 1)).c_str()); } + + m_encoder->encodeHeader(); + boxIO->markOutputAsReadyToSend(0, m_lastChunkStartTime, m_lastChunkEndTime); + m_headerSent = true; } - } // namespace FeatureExtraction - } // namespace Plugins + } + //*/ + if (m_decoder[input]->isBufferReceived()) + { + bufferReceived = true; + IMatrix* iMatrix = m_decoder[input]->getOutputMatrix(); + const size_t size = iMatrix->getBufferElementCount(); + + double* buffer = iMatrix->getBuffer(); + for (size_t i = 0; i < size; ++i) { bufferElements.push_back(buffer[i]); } + } + } + + if (m_headerSent && bufferReceived) + { + double* oBuffer = oMatrix->getBuffer(); + for (size_t i = 0; i < bufferElements.size(); ++i) { oBuffer[i] = bufferElements[i]; } + m_encoder->encodeBuffer(); + boxIO->markOutputAsReadyToSend(0, m_lastChunkStartTime, m_lastChunkEndTime); + } + + return true; +} +} // namespace FeatureExtraction +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/feature-extraction/src/box-algorithms/ovpCBoxAlgorithmFeatureAggregator.h b/plugins/processing/feature-extraction/src/box-algorithms/ovpCBoxAlgorithmFeatureAggregator.h index 8b72c465e337e2c8beab6de09f6d6cce094c76b4..176e8b0d0a5d0579049840f99102839619c60c92 100644 --- a/plugins/processing/feature-extraction/src/box-algorithms/ovpCBoxAlgorithmFeatureAggregator.h +++ b/plugins/processing/feature-extraction/src/box-algorithms/ovpCBoxAlgorithmFeatureAggregator.h @@ -9,110 +9,107 @@ #include <vector> #include <queue> -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace FeatureExtraction { +/** + * Main plugin class of the feature aggregator plugins. + * Aggregates the features received in a feature vector then outputs it. + * */ +class CBoxAlgorithmFeatureAggregator final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm> { - namespace Plugins +public: + + CBoxAlgorithmFeatureAggregator() { } + void release() override { delete this; } + bool initialize() override; + bool uninitialize() override; + bool processInput(const size_t index) override; + bool process() override; + + _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_FeatureAggregator) + +protected: + //codecs + Toolkit::TFeatureVectorEncoder<CBoxAlgorithmFeatureAggregator>* m_encoder = nullptr; + std::vector<Toolkit::TStreamedMatrixDecoder<CBoxAlgorithmFeatureAggregator>*> m_decoder; + + // contains the labels for each dimension for each input + std::vector<std::vector<std::vector<std::string>>> m_featureNames; + + // contains the dimension size for each dimension of each input + std::vector<std::vector<size_t>> m_dimSize; + + // contains the input buffer's total size for each input + std::vector<size_t> m_iBufferSizes; + + //start time and end time of the last arrived chunk + uint64_t m_lastChunkStartTime = 0; + uint64_t m_lastChunkEndTime = 0; + + // number of inputs + size_t m_nInput = 0; + + bool m_headerSent = false; +}; + +class CBoxAlgorithmFeatureAggregatorListener final : public Toolkit::TBoxListener<IBoxListener> +{ +public: + + bool check(Kernel::IBox& box) const { - namespace FeatureExtraction + for (size_t i = 0; i < box.getInputCount(); ++i) { - /** - * Main plugin class of the feature aggregator plugins. - * Aggregates the features received in a feature vector then outputs it. - * */ - class CBoxAlgorithmFeatureAggregator final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm> - { - public: - - CBoxAlgorithmFeatureAggregator() { } - void release() override { delete this; } - bool initialize() override; - bool uninitialize() override; - bool processInput(const size_t index) override; - bool process() override; - - _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_FeatureAggregator) - - protected: - //codecs - Toolkit::TFeatureVectorEncoder<CBoxAlgorithmFeatureAggregator>* m_encoder = nullptr; - std::vector<Toolkit::TStreamedMatrixDecoder<CBoxAlgorithmFeatureAggregator>*> m_decoder; - - // contains the labels for each dimension for each input - std::vector<std::vector<std::vector<std::string>>> m_featureNames; - - // contains the dimension size for each dimension of each input - std::vector<std::vector<size_t>> m_dimSize; - - // contains the input buffer's total size for each input - std::vector<size_t> m_iBufferSizes; - - //start time and end time of the last arrived chunk - uint64_t m_lastChunkStartTime = 0; - uint64_t m_lastChunkEndTime = 0; - - // number of inputs - size_t m_nInput = 0; - - bool m_headerSent = false; - }; - - class CBoxAlgorithmFeatureAggregatorListener final : public Toolkit::TBoxListener<IBoxListener> - { - public: - - bool check(Kernel::IBox& box) const - { - for (size_t i = 0; i < box.getInputCount(); ++i) - { - box.setInputName(i, ("Input stream " + std::to_string(i + 1)).c_str()); - box.setInputType(i, OV_TypeId_StreamedMatrix); - } - - return true; - } - - bool onInputRemoved(Kernel::IBox& box, const size_t /*index*/) override { return this->check(box); } - bool onInputAdded(Kernel::IBox& box, const size_t /*index*/) override { return this->check(box); } - - _IsDerivedFromClass_Final_(Toolkit::TBoxListener<IBoxListener>, OV_UndefinedIdentifier) - }; - - /** - * Plugin's description - */ - class CBoxAlgorithmFeatureAggregatorDesc final : public IBoxAlgorithmDesc - { - public: - CString getName() const override { return CString("Feature aggregator"); } - CString getAuthorName() const override { return CString("Bruno Renier"); } - CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } - CString getShortDescription() const override { return CString("Aggregates input to feature vectors"); } - - CString getDetailedDescription() const override { return CString("Each chunk of input will be catenated into one feature vector."); } - - CString getCategory() const override { return CString("Feature extraction"); } - CString getVersion() const override { return CString("1.0"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } - void release() override { } - CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_FeatureAggregator; } - IPluginObject* create() override { return new CBoxAlgorithmFeatureAggregator(); } - IBoxListener* createBoxListener() const override { return new CBoxAlgorithmFeatureAggregatorListener; } - void releaseBoxListener(IBoxListener* listener) const override { delete listener; } - - bool getBoxPrototype(Kernel::IBoxProto& prototype) const override - { - prototype.addInput("Input stream 1", OV_TypeId_StreamedMatrix); - // prototype.addInput("Input stream 2", OV_TypeId_StreamedMatrix); - prototype.addOutput("Feature vector stream", OV_TypeId_FeatureVector); - prototype.addFlag(Kernel::BoxFlag_CanAddInput); - - return true; - } - - _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_FeatureAggregatorDesc) - }; - } // namespace FeatureExtraction - } // namespace Plugins + box.setInputName(i, ("Input stream " + std::to_string(i + 1)).c_str()); + box.setInputType(i, OV_TypeId_StreamedMatrix); + } + + return true; + } + + bool onInputRemoved(Kernel::IBox& box, const size_t /*index*/) override { return this->check(box); } + bool onInputAdded(Kernel::IBox& box, const size_t /*index*/) override { return this->check(box); } + + _IsDerivedFromClass_Final_(Toolkit::TBoxListener<IBoxListener>, OV_UndefinedIdentifier) +}; + +/** +* Plugin's description +*/ +class CBoxAlgorithmFeatureAggregatorDesc final : public IBoxAlgorithmDesc +{ +public: + CString getName() const override { return CString("Feature aggregator"); } + CString getAuthorName() const override { return CString("Bruno Renier"); } + CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } + CString getShortDescription() const override { return CString("Aggregates input to feature vectors"); } + + CString getDetailedDescription() const override { return CString("Each chunk of input will be catenated into one feature vector."); } + + CString getCategory() const override { return CString("Feature extraction"); } + CString getVersion() const override { return CString("1.0"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } + void release() override { } + CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_FeatureAggregator; } + IPluginObject* create() override { return new CBoxAlgorithmFeatureAggregator(); } + IBoxListener* createBoxListener() const override { return new CBoxAlgorithmFeatureAggregatorListener; } + void releaseBoxListener(IBoxListener* listener) const override { delete listener; } + + bool getBoxPrototype(Kernel::IBoxProto& prototype) const override + { + prototype.addInput("Input stream 1", OV_TypeId_StreamedMatrix); + // prototype.addInput("Input stream 2", OV_TypeId_StreamedMatrix); + prototype.addOutput("Feature vector stream", OV_TypeId_FeatureVector); + prototype.addFlag(Kernel::BoxFlag_CanAddInput); + + return true; + } + + _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_FeatureAggregatorDesc) +}; +} // namespace FeatureExtraction +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/file-io/CMakeLists.txt b/plugins/processing/file-io/CMakeLists.txt index 92b9e2df39895b53cdb23eef2d8d6295ad2a67e7..1c29722ec5a7f5b1e61195d7cdd707206918ae2c 100755 --- a/plugins/processing/file-io/CMakeLists.txt +++ b/plugins/processing/file-io/CMakeLists.txt @@ -16,6 +16,7 @@ ADD_LIBRARY(${PROJECT_NAME} SHARED ${SRC_FILES}) SET_TARGET_PROPERTIES(${PROJECT_NAME} PROPERTIES VERSION ${PROJECT_VERSION} SOVERSION ${PROJECT_VERSION_MAJOR} + FOLDER ${PLUGINS_FOLDER} COMPILE_FLAGS "-DOVP_Exports -DOVP_Shared -D_LARGEFILE64_SOURCE -D_LARGEFILE_SOURCE") # --------------------------------- @@ -31,9 +32,7 @@ INCLUDE("FindThirdPartyXerces") # --------------------------------- # Target macros -# Defines target operating system -# Defines target architecture -# Defines target compiler +# Defines target operating system, architecture and compiler # --------------------------------- SET_BUILD_PLATFORM() diff --git a/plugins/processing/file-io/src/algorithms/ovpCAlgorithmOVMatrixFileReader.cpp b/plugins/processing/file-io/src/algorithms/ovpCAlgorithmOVMatrixFileReader.cpp index cbd0a6ab3b4d04b9adfa2814d10efe5619135074..370d0eaa6d5b8dda0710b836b2b56f5e21916c11 100644 --- a/plugins/processing/file-io/src/algorithms/ovpCAlgorithmOVMatrixFileReader.cpp +++ b/plugins/processing/file-io/src/algorithms/ovpCAlgorithmOVMatrixFileReader.cpp @@ -8,26 +8,21 @@ using namespace FileIO; bool CAlgorithmOVMatrixFileReader::initialize() { ip_sFilename.initialize(getInputParameter(OVP_Algorithm_OVMatrixFileReader_InputParameterId_Filename)); - op_pMatrix.initialize(getOutputParameter(OVP_Algorithm_OVMatrixFileReader_OutputParameterId_Matrix)); - return true; } bool CAlgorithmOVMatrixFileReader::uninitialize() { op_pMatrix.uninitialize(); - ip_sFilename.uninitialize(); - return true; } bool CAlgorithmOVMatrixFileReader::process() { OV_ERROR_UNLESS_KRF(Toolkit::Matrix::loadFromTextFile(*op_pMatrix, ip_sFilename->toASCIIString()), - "Reading matrix file " << *ip_sFilename << " failed", - ErrorType::BadFileRead); + "Reading matrix file " << *ip_sFilename << " failed", ErrorType::BadFileRead); return true; } diff --git a/plugins/processing/file-io/src/algorithms/ovpCAlgorithmOVMatrixFileReader.h b/plugins/processing/file-io/src/algorithms/ovpCAlgorithmOVMatrixFileReader.h index 10c85e2c3a0bf2be2cd87d31c63c020ad4966ec3..25d7a793e0ffddf96c44753c01ef0c9e4ce08109 100644 --- a/plugins/processing/file-io/src/algorithms/ovpCAlgorithmOVMatrixFileReader.h +++ b/plugins/processing/file-io/src/algorithms/ovpCAlgorithmOVMatrixFileReader.h @@ -5,56 +5,51 @@ #include <toolkit/ovtk_all.h> -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace FileIO { +class CAlgorithmOVMatrixFileReader final : public Toolkit::TAlgorithm<IAlgorithm> { - namespace Plugins +public: + void release() override { delete this; } + bool initialize() override; + bool uninitialize() override; + bool process() override; + + _IsDerivedFromClass_Final_(Toolkit::TAlgorithm<IAlgorithm>, OVP_ClassId_Algorithm_OVMatrixFileReader) + +protected: + + Kernel::TParameterHandler<CString*> ip_sFilename; + Kernel::TParameterHandler<IMatrix*> op_pMatrix; +}; + +class CAlgorithmOVMatrixFileReaderDesc final : public IAlgorithmDesc +{ +public: + void release() override { } + CString getName() const override { return CString("OpenViBE Matrix file reader"); } + CString getAuthorName() const override { return CString("Vincent Delannoy"); } + CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } + CString getShortDescription() const override { return CString(""); } + CString getDetailedDescription() const override { return CString(""); } + CString getCategory() const override { return CString("File reading and writing"); } + CString getVersion() const override { return CString("1.1"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_Algorithm_OVMatrixFileReader; } + IPluginObject* create() override { return new CAlgorithmOVMatrixFileReader; } + + bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override { - namespace FileIO - { - class CAlgorithmOVMatrixFileReader final : public Toolkit::TAlgorithm<IAlgorithm> - { - public: - void release() override { delete this; } - bool initialize() override; - bool uninitialize() override; - bool process() override; - - _IsDerivedFromClass_Final_(Toolkit::TAlgorithm<IAlgorithm>, OVP_ClassId_Algorithm_OVMatrixFileReader) - - protected: - - Kernel::TParameterHandler<CString*> ip_sFilename; - Kernel::TParameterHandler<IMatrix*> op_pMatrix; - }; - - class CAlgorithmOVMatrixFileReaderDesc final : public IAlgorithmDesc - { - public: - void release() override { } - CString getName() const override { return CString("OpenViBE Matrix file reader"); } - CString getAuthorName() const override { return CString("Vincent Delannoy"); } - CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } - CString getShortDescription() const override { return CString(""); } - CString getDetailedDescription() const override { return CString(""); } - CString getCategory() const override { return CString("File reading and writing"); } - CString getVersion() const override { return CString("1.1"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_Algorithm_OVMatrixFileReader; } - IPluginObject* create() override { return new CAlgorithmOVMatrixFileReader; } - - bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override - { - prototype.addInputParameter( - OVP_Algorithm_OVMatrixFileReader_InputParameterId_Filename, "Filename", Kernel::ParameterType_String); - prototype.addOutputParameter( - OVP_Algorithm_OVMatrixFileReader_OutputParameterId_Matrix, "Matrix", Kernel::ParameterType_Matrix); - return true; - } - - _IsDerivedFromClass_Final_(IAlgorithmDesc, OVP_ClassId_Algorithm_OVMatrixFileReaderDesc) - }; - } // namespace FileIO - } // namespace Plugins + prototype.addInputParameter(OVP_Algorithm_OVMatrixFileReader_InputParameterId_Filename, "Filename", Kernel::ParameterType_String); + prototype.addOutputParameter(OVP_Algorithm_OVMatrixFileReader_OutputParameterId_Matrix, "Matrix", Kernel::ParameterType_Matrix); + return true; + } + + _IsDerivedFromClass_Final_(IAlgorithmDesc, OVP_ClassId_Algorithm_OVMatrixFileReaderDesc) +}; +} // namespace FileIO +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/file-io/src/algorithms/ovpCAlgorithmOVMatrixFileWriter.cpp b/plugins/processing/file-io/src/algorithms/ovpCAlgorithmOVMatrixFileWriter.cpp index 25a91115dad795c93d315eee7ec725afbadc02ab..88e12db11a9c0f28841815b12e1fcb16044b2853 100644 --- a/plugins/processing/file-io/src/algorithms/ovpCAlgorithmOVMatrixFileWriter.cpp +++ b/plugins/processing/file-io/src/algorithms/ovpCAlgorithmOVMatrixFileWriter.cpp @@ -9,7 +9,6 @@ bool CAlgorithmOVMatrixFileWriter::initialize() { ip_sFilename.initialize(getInputParameter(OVP_Algorithm_OVMatrixFileWriter_InputParameterId_Filename)); ip_pMatrix.initialize(getInputParameter(OVP_Algorithm_OVMatrixFileWriter_InputParameterId_Matrix)); - return true; } @@ -17,7 +16,6 @@ bool CAlgorithmOVMatrixFileWriter::uninitialize() { ip_sFilename.uninitialize(); ip_pMatrix.uninitialize(); - return true; } diff --git a/plugins/processing/file-io/src/algorithms/ovpCAlgorithmOVMatrixFileWriter.h b/plugins/processing/file-io/src/algorithms/ovpCAlgorithmOVMatrixFileWriter.h index 95e90e65ffb877ed27af87c32b3f1e6c1ed2d910..629185eb678e9fc4e4d83d612c8f6550fb6d471c 100644 --- a/plugins/processing/file-io/src/algorithms/ovpCAlgorithmOVMatrixFileWriter.h +++ b/plugins/processing/file-io/src/algorithms/ovpCAlgorithmOVMatrixFileWriter.h @@ -4,56 +4,51 @@ #include <openvibe/ov_all.h> #include <toolkit/ovtk_all.h> -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace FileIO { +class CAlgorithmOVMatrixFileWriter final : public Toolkit::TAlgorithm<IAlgorithm> { - namespace Plugins +public: + void release() override { delete this; } + bool initialize() override; + bool uninitialize() override; + bool process() override; + + _IsDerivedFromClass_Final_(Toolkit::TAlgorithm<IAlgorithm>, OVP_ClassId_Algorithm_OVMatrixFileWriter) + +protected: + + Kernel::TParameterHandler<CString*> ip_sFilename; + Kernel::TParameterHandler<CMatrix*> ip_pMatrix; +}; + +class CAlgorithmOVMatrixFileWriterDesc final : public IAlgorithmDesc +{ +public: + void release() override { } + CString getName() const override { return CString("OpenViBE Matrix file writer"); } + CString getAuthorName() const override { return CString("Vincent Delannoy"); } + CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } + CString getShortDescription() const override { return CString(""); } + CString getDetailedDescription() const override { return CString(""); } + CString getCategory() const override { return CString("File reading and writing"); } + CString getVersion() const override { return CString("1.1"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_Algorithm_OVMatrixFileWriter; } + IPluginObject* create() override { return new CAlgorithmOVMatrixFileWriter; } + + bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override { - namespace FileIO - { - class CAlgorithmOVMatrixFileWriter final : public Toolkit::TAlgorithm<IAlgorithm> - { - public: - void release() override { delete this; } - bool initialize() override; - bool uninitialize() override; - bool process() override; - - _IsDerivedFromClass_Final_(Toolkit::TAlgorithm<IAlgorithm>, OVP_ClassId_Algorithm_OVMatrixFileWriter) - - protected: - - Kernel::TParameterHandler<CString*> ip_sFilename; - Kernel::TParameterHandler<CMatrix*> ip_pMatrix; - }; - - class CAlgorithmOVMatrixFileWriterDesc final : public IAlgorithmDesc - { - public: - void release() override { } - CString getName() const override { return CString("OpenViBE Matrix file writer"); } - CString getAuthorName() const override { return CString("Vincent Delannoy"); } - CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } - CString getShortDescription() const override { return CString(""); } - CString getDetailedDescription() const override { return CString(""); } - CString getCategory() const override { return CString("File reading and writing"); } - CString getVersion() const override { return CString("1.1"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_Algorithm_OVMatrixFileWriter; } - IPluginObject* create() override { return new CAlgorithmOVMatrixFileWriter; } - - bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override - { - prototype.addInputParameter( - OVP_Algorithm_OVMatrixFileWriter_InputParameterId_Filename, "Filename", Kernel::ParameterType_String); - prototype.addInputParameter( - OVP_Algorithm_OVMatrixFileWriter_InputParameterId_Matrix, "Matrix", Kernel::ParameterType_Matrix); - return true; - } - - _IsDerivedFromClass_Final_(IAlgorithmDesc, OVP_ClassId_Algorithm_OVMatrixFileWriterDesc) - }; - } // namespace FileIO - } // namespace Plugins + prototype.addInputParameter(OVP_Algorithm_OVMatrixFileWriter_InputParameterId_Filename, "Filename", Kernel::ParameterType_String); + prototype.addInputParameter(OVP_Algorithm_OVMatrixFileWriter_InputParameterId_Matrix, "Matrix", Kernel::ParameterType_Matrix); + return true; + } + + _IsDerivedFromClass_Final_(IAlgorithmDesc, OVP_ClassId_Algorithm_OVMatrixFileWriterDesc) +}; +} // namespace FileIO +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/file-io/src/algorithms/xml-scenario/ovpCAlgorithmXMLScenarioExporter.cpp b/plugins/processing/file-io/src/algorithms/xml-scenario/ovpCAlgorithmXMLScenarioExporter.cpp index 71aaf22ef3b329ab27912468c773b26a043ffdfc..29841ae0ee47ad911db8251bad5c7221fc972c47 100755 --- a/plugins/processing/file-io/src/algorithms/xml-scenario/ovpCAlgorithmXMLScenarioExporter.cpp +++ b/plugins/processing/file-io/src/algorithms/xml-scenario/ovpCAlgorithmXMLScenarioExporter.cpp @@ -15,7 +15,6 @@ using namespace std; // // CAlgorithmXMLScenarioExporter::CAlgorithmXMLScenarioExporter() { m_writer = createWriter(*this); } - CAlgorithmXMLScenarioExporter::~CAlgorithmXMLScenarioExporter() { m_writer->release(); } void CAlgorithmXMLScenarioExporter::write(const char* str) { m_pMemoryBuffer->append(reinterpret_cast<const uint8_t*>(str), strlen(str)); } @@ -128,24 +127,18 @@ bool CAlgorithmXMLScenarioExporter::exportStart(IMemoryBuffer& memoryBuffer, con bool CAlgorithmXMLScenarioExporter::exportIdentifier(IMemoryBuffer& memoryBuffer, const CIdentifier& id, const CIdentifier& value) { m_pMemoryBuffer = &memoryBuffer; - OV_ERROR_UNLESS_KRF(this->exportStart(memoryBuffer, id), "Exporting identifier failed", ErrorType::Internal); - m_writer->setChildData(value.str().c_str()); this->exportStop(memoryBuffer); - return true; } bool CAlgorithmXMLScenarioExporter::exportString(IMemoryBuffer& memoryBuffer, const CIdentifier& id, const CString& value) { m_pMemoryBuffer = &memoryBuffer; - OV_ERROR_UNLESS_KRF(this->exportStart(memoryBuffer, id), "Exporting string failed", ErrorType::Internal); - m_writer->setChildData(value.toASCIIString()); this->exportStop(memoryBuffer); - return true; } @@ -155,7 +148,6 @@ bool CAlgorithmXMLScenarioExporter::exportUInteger(IMemoryBuffer& memoryBuffer, OV_ERROR_UNLESS_KRF(this->exportStart(memoryBuffer, id), "Exporting uint failed", ErrorType::Internal); m_writer->setChildData(std::to_string(value).c_str()); this->exportStop(memoryBuffer); - return true; } diff --git a/plugins/processing/file-io/src/algorithms/xml-scenario/ovpCAlgorithmXMLScenarioExporter.h b/plugins/processing/file-io/src/algorithms/xml-scenario/ovpCAlgorithmXMLScenarioExporter.h index 604ef86960f50b4932461eed2cf4499a1c7617ee..4b6257e0ea99ef9bf0d20b6f19e2c34574978f04 100644 --- a/plugins/processing/file-io/src/algorithms/xml-scenario/ovpCAlgorithmXMLScenarioExporter.h +++ b/plugins/processing/file-io/src/algorithms/xml-scenario/ovpCAlgorithmXMLScenarioExporter.h @@ -6,55 +6,52 @@ #include <toolkit/ovtk_all.h> #include <xml/IWriter.h> -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace FileIO { +class CAlgorithmXMLScenarioExporter final : public Toolkit::CAlgorithmScenarioExporter, public XML::IWriterCallback { - namespace Plugins - { - namespace FileIO - { - class CAlgorithmXMLScenarioExporter final : public Toolkit::CAlgorithmScenarioExporter, public XML::IWriterCallback - { - public: - - CAlgorithmXMLScenarioExporter(); - ~CAlgorithmXMLScenarioExporter() override; - bool exportStart(IMemoryBuffer& memoryBuffer, const CIdentifier& id) override; - bool exportIdentifier(IMemoryBuffer& memoryBuffer, const CIdentifier& id, const CIdentifier& value) override; - bool exportString(IMemoryBuffer& memoryBuffer, const CIdentifier& id, const CString& value) override; - bool exportUInteger(IMemoryBuffer& memoryBuffer, const CIdentifier& id, uint64_t value) override; - bool exportStop(IMemoryBuffer& memoryBuffer) override; - - _IsDerivedFromClass_Final_(Toolkit::CAlgorithmScenarioExporter, OVP_ClassId_Algorithm_XMLScenarioExporter) - - protected: - void write(const char* str) override; // XML::IWriterCallback - - XML::IWriter* m_writer = nullptr; - IMemoryBuffer* m_pMemoryBuffer = nullptr; - }; - - class CAlgorithmXMLScenarioExporterDesc final : public Toolkit::CAlgorithmScenarioExporterDesc - { - public: - void release() override { } - CString getName() const override { return CString("XML Scenario exporter"); } - CString getAuthorName() const override { return CString("Yann Renard"); } - CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } - CString getShortDescription() const override { return CString("A sample XML scenario exporter"); } - - CString getDetailedDescription() const override { return CString("This scenario exporter uses simple XML format to output the scenario"); } - - CString getCategory() const override { return CString("File reading and writing/XML Scenario"); } - CString getVersion() const override { return CString("1.0"); } - // virtual CString getFileExtension() const { return CString("xml;XML"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_Algorithm_XMLScenarioExporter; } - IPluginObject* create() override { return new CAlgorithmXMLScenarioExporter(); } - - _IsDerivedFromClass_Final_(Toolkit::CAlgorithmScenarioExporterDesc, OVP_ClassId_Algorithm_XMLScenarioExporterDesc) - }; - } // namespace FileIO - } // namespace Plugins +public: + + CAlgorithmXMLScenarioExporter(); + ~CAlgorithmXMLScenarioExporter() override; + bool exportStart(IMemoryBuffer& memoryBuffer, const CIdentifier& id) override; + bool exportIdentifier(IMemoryBuffer& memoryBuffer, const CIdentifier& id, const CIdentifier& value) override; + bool exportString(IMemoryBuffer& memoryBuffer, const CIdentifier& id, const CString& value) override; + bool exportUInteger(IMemoryBuffer& memoryBuffer, const CIdentifier& id, uint64_t value) override; + bool exportStop(IMemoryBuffer& memoryBuffer) override; + + _IsDerivedFromClass_Final_(Toolkit::CAlgorithmScenarioExporter, OVP_ClassId_Algorithm_XMLScenarioExporter) + +protected: + void write(const char* str) override; // XML::IWriterCallback + + XML::IWriter* m_writer = nullptr; + IMemoryBuffer* m_pMemoryBuffer = nullptr; +}; + +class CAlgorithmXMLScenarioExporterDesc final : public Toolkit::CAlgorithmScenarioExporterDesc +{ +public: + void release() override { } + CString getName() const override { return CString("XML Scenario exporter"); } + CString getAuthorName() const override { return CString("Yann Renard"); } + CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } + CString getShortDescription() const override { return CString("A sample XML scenario exporter"); } + + CString getDetailedDescription() const override { return CString("This scenario exporter uses simple XML format to output the scenario"); } + + CString getCategory() const override { return CString("File reading and writing/XML Scenario"); } + CString getVersion() const override { return CString("1.0"); } + // virtual CString getFileExtension() const { return CString("xml;XML"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_Algorithm_XMLScenarioExporter; } + IPluginObject* create() override { return new CAlgorithmXMLScenarioExporter(); } + + _IsDerivedFromClass_Final_(Toolkit::CAlgorithmScenarioExporterDesc, OVP_ClassId_Algorithm_XMLScenarioExporterDesc) +}; +} // namespace FileIO +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/file-io/src/algorithms/xml-scenario/ovpCAlgorithmXMLScenarioImporter.cpp b/plugins/processing/file-io/src/algorithms/xml-scenario/ovpCAlgorithmXMLScenarioImporter.cpp index 1387f46ecc14d11bbecb7642693ec5d15a5134de..f158fd3280e5f73d022b6a1813ed09e841dd2485 100644 --- a/plugins/processing/file-io/src/algorithms/xml-scenario/ovpCAlgorithmXMLScenarioImporter.cpp +++ b/plugins/processing/file-io/src/algorithms/xml-scenario/ovpCAlgorithmXMLScenarioImporter.cpp @@ -20,63 +20,61 @@ using namespace /*OpenViBE::*/Plugins; using namespace FileIO; using namespace /*OpenViBE::*/Toolkit; -namespace +namespace { +class _AutoBind_ { - class _AutoBind_ - { - public: - explicit _AutoBind_(const std::string& value) : m_value(value) { } - operator CString() const { return CString(m_value.c_str()); } - - operator CIdentifier() const - { - CIdentifier res; - res.fromString(m_value.c_str()); - return res; - } +public: + explicit _AutoBind_(const std::string& value) : m_value(value) { } + operator CString() const { return CString(m_value.c_str()); } - operator size_t() { return atoi(m_value.c_str()); } - protected: - const std::string& m_value; - }; - - std::string xercesToString(const XMLCh* xercesString) + operator CIdentifier() const { - const std::unique_ptr<char[]> charArray(XMLString::transcode(xercesString)); - return std::string(charArray.get()); + CIdentifier res; + res.fromString(m_value.c_str()); + return res; } - class CErrorHandler final : public HandlerBase - { - public: + operator size_t() { return atoi(m_value.c_str()); } +protected: + const std::string& m_value; +}; + +std::string xercesToString(const XMLCh* xercesString) +{ + const std::unique_ptr<char[]> charArray(XMLString::transcode(xercesString)); + return std::string(charArray.get()); +} - explicit CErrorHandler(IAlgorithmContext& algorithmCtx) - : m_algorithmContext(algorithmCtx) { } +class CErrorHandler final : public HandlerBase +{ +public: - void fatalError(const SAXParseException& exception) override { this->error(exception); } + explicit CErrorHandler(IAlgorithmContext& algorithmCtx) + : m_algorithmContext(algorithmCtx) { } - void error(const SAXParseException& exception) override - { - // we just issue a trace here because the calling method - // implements a fallback mechanism and we don't want to populate - // the error manager if the importer returns gracefully. - m_algorithmContext.getLogManager() << LogLevel_Trace << "Failed to validate xml: error [" << xercesToString(exception.getMessage()) - << "], line number [" << size_t(exception.getLineNumber()) << "]" << "\n"; - } + void fatalError(const SAXParseException& exception) override { this->error(exception); } - void warning(const SAXParseException& exception) override - { - OV_WARNING("Warning while validating xml: warning [" << xercesToString(exception.getMessage()) << "], line number [" - << size_t(exception.getLineNumber()) << "]", m_algorithmContext.getLogManager()); - } + void error(const SAXParseException& exception) override + { + // we just issue a trace here because the calling method + // implements a fallback mechanism and we don't want to populate + // the error manager if the importer returns gracefully. + m_algorithmContext.getLogManager() << LogLevel_Trace << "Failed to validate xml: error [" << xercesToString(exception.getMessage()) + << "], line number [" << size_t(exception.getLineNumber()) << "]" << "\n"; + } - private: - IAlgorithmContext& m_algorithmContext; - }; + void warning(const SAXParseException& exception) override + { + OV_WARNING("Warning while validating xml: warning [" << xercesToString(exception.getMessage()) << "], line number [" + << size_t(exception.getLineNumber()) << "]", m_algorithmContext.getLogManager()); + } + +private: + IAlgorithmContext& m_algorithmContext; +}; } //namespace CAlgorithmXMLScenarioImporter::CAlgorithmXMLScenarioImporter() { m_reader = createReader(*this); } - CAlgorithmXMLScenarioImporter::~CAlgorithmXMLScenarioImporter() { m_reader->release(); } void CAlgorithmXMLScenarioImporter::openChild(const char* name, const char** /*attributeName*/, const char** /*attributeValue*/, const size_t /*nAttribute*/) diff --git a/plugins/processing/file-io/src/algorithms/xml-scenario/ovpCAlgorithmXMLScenarioImporter.h b/plugins/processing/file-io/src/algorithms/xml-scenario/ovpCAlgorithmXMLScenarioImporter.h index 61c45f7fb5c0c1a34dd64041ddce2458cb0ee3e6..fe911499be62a67998bd48c536c9353d93d126d9 100644 --- a/plugins/processing/file-io/src/algorithms/xml-scenario/ovpCAlgorithmXMLScenarioImporter.h +++ b/plugins/processing/file-io/src/algorithms/xml-scenario/ovpCAlgorithmXMLScenarioImporter.h @@ -8,68 +8,65 @@ #include <string> -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace FileIO { +class CAlgorithmXMLScenarioImporter final : public Toolkit::CAlgorithmScenarioImporter, public XML::IReaderCallback { - namespace Plugins - { - namespace FileIO - { - class CAlgorithmXMLScenarioImporter final : public Toolkit::CAlgorithmScenarioImporter, public XML::IReaderCallback - { - public: +public: - CAlgorithmXMLScenarioImporter(); - ~CAlgorithmXMLScenarioImporter() override; - bool import(IAlgorithmScenarioImporterContext& rContext, const IMemoryBuffer& memoryBuffer) override; - void openChild(const char* name, const char** attributeName, const char** sAttributeValue, const size_t nAttribute) - override; // XML::IReaderCallback - void processChildData(const char* data) override; // XML::IReaderCallback - void closeChild() override; // XML::IReaderCallback + CAlgorithmXMLScenarioImporter(); + ~CAlgorithmXMLScenarioImporter() override; + bool import(IAlgorithmScenarioImporterContext& rContext, const IMemoryBuffer& memoryBuffer) override; + void openChild(const char* name, const char** attributeName, const char** sAttributeValue, const size_t nAttribute) + override; // XML::IReaderCallback + void processChildData(const char* data) override; // XML::IReaderCallback + void closeChild() override; // XML::IReaderCallback - _IsDerivedFromClass_Final_(Toolkit::CAlgorithmScenarioImporter, OVP_ClassId_Algorithm_XMLScenarioImporter) + _IsDerivedFromClass_Final_(Toolkit::CAlgorithmScenarioImporter, OVP_ClassId_Algorithm_XMLScenarioImporter) - protected: - enum class EParsingStatus - { - Nothing, - Scenario, ScenarioAttribute, ScenarioInput, ScenarioOutput, ScenarioSetting, - Box, BoxInput, BoxOutput, BoxSetting, BoxAttribute, - Comment, CommentAttribute, - MetadataEntry, - Link, LinkSource, LinkTarget, LinkAttribute - }; +protected: + enum class EParsingStatus + { + Nothing, + Scenario, ScenarioAttribute, ScenarioInput, ScenarioOutput, ScenarioSetting, + Box, BoxInput, BoxOutput, BoxSetting, BoxAttribute, + Comment, CommentAttribute, + MetadataEntry, + Link, LinkSource, LinkTarget, LinkAttribute + }; - bool validateXML(const unsigned char* buffer, size_t size); - bool validateXMLAgainstSchema(const char* validationSchema, const unsigned char* buffer, size_t size); + bool validateXML(const unsigned char* buffer, size_t size); + bool validateXMLAgainstSchema(const char* validationSchema, const unsigned char* buffer, size_t size); - IAlgorithmScenarioImporterContext* m_ctx = nullptr; - EParsingStatus m_status = EParsingStatus::Nothing; - XML::IReader* m_reader = nullptr; - std::stack<std::string> m_nodes; - }; + IAlgorithmScenarioImporterContext* m_ctx = nullptr; + EParsingStatus m_status = EParsingStatus::Nothing; + XML::IReader* m_reader = nullptr; + std::stack<std::string> m_nodes; +}; - class CAlgorithmXMLScenarioImporterDesc final : public Toolkit::CAlgorithmScenarioImporterDesc - { - public: - void release() override { } - CString getName() const override { return CString("XML Scenario importer"); } - CString getAuthorName() const override { return CString("Yann Renard"); } - CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } - CString getShortDescription() const override { return CString("A sample XML scenario importer"); } +class CAlgorithmXMLScenarioImporterDesc final : public Toolkit::CAlgorithmScenarioImporterDesc +{ +public: + void release() override { } + CString getName() const override { return CString("XML Scenario importer"); } + CString getAuthorName() const override { return CString("Yann Renard"); } + CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } + CString getShortDescription() const override { return CString("A sample XML scenario importer"); } - CString getDetailedDescription() const override { return CString("This scenario importer uses simple XML format to input the scenario"); } + CString getDetailedDescription() const override { return CString("This scenario importer uses simple XML format to input the scenario"); } - CString getCategory() const override { return CString("Samples"); } - CString getVersion() const override { return CString("1.0"); } - // virtual CString getFileExtension() const { return CString("xml;XML"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_Algorithm_XMLScenarioImporter; } - IPluginObject* create() override { return new CAlgorithmXMLScenarioImporter(); } + CString getCategory() const override { return CString("Samples"); } + CString getVersion() const override { return CString("1.0"); } + // virtual CString getFileExtension() const { return CString("xml;XML"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_Algorithm_XMLScenarioImporter; } + IPluginObject* create() override { return new CAlgorithmXMLScenarioImporter(); } - _IsDerivedFromClass_Final_(Toolkit::CAlgorithmScenarioImporterDesc, OVP_ClassId_Algorithm_XMLScenarioImporterDesc) - }; - } // namespace FileIO - } // namespace Plugins + _IsDerivedFromClass_Final_(Toolkit::CAlgorithmScenarioImporterDesc, OVP_ClassId_Algorithm_XMLScenarioImporterDesc) +}; +} // namespace FileIO +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/file-io/src/box-algorithms/csv/ovpCBoxAlgorithmCSVFileReader.cpp b/plugins/processing/file-io/src/box-algorithms/csv/ovpCBoxAlgorithmCSVFileReader.cpp index c0a71e654480f333db446f4b111495dfb8ded51c..413d9100fe1160281e98b1f49428640dba6c6a59 100755 --- a/plugins/processing/file-io/src/box-algorithms/csv/ovpCBoxAlgorithmCSVFileReader.cpp +++ b/plugins/processing/file-io/src/box-algorithms/csv/ovpCBoxAlgorithmCSVFileReader.cpp @@ -12,30 +12,29 @@ using namespace /*OpenViBE::*/Plugins; using namespace FileIO; using namespace std; -namespace +namespace { +vector<string> split(const string& sString, const string& c) { - vector<string> split(const string& sString, const string& c) + vector<string> result; + size_t i = 0; + size_t j; + while ((j = sString.find(c, i)) != string::npos) { - vector<string> result; - size_t i = 0; - size_t j; - while ((j = sString.find(c, i)) != string::npos) - { - result.push_back(string(sString, i, j - i)); - i = j + c.size(); - } - //the last element without the \n character - result.push_back(string(sString, i, sString.size() - 1 - i)); - - return result; + result.push_back(string(sString, i, j - i)); + i = j + c.size(); } + //the last element without the \n character + result.push_back(string(sString, i, sString.size() - 1 - i)); - void clearMatrix(vector<vector<string>>& vMatrix) - { - for (size_t i = 0; i < vMatrix.size(); ++i) { vMatrix[i].clear(); } - vMatrix.clear(); - } -} // namespace + return result; +} + +void clearMatrix(vector<vector<string>>& vMatrix) +{ + for (size_t i = 0; i < vMatrix.size(); ++i) { vMatrix[i].clear(); } + vMatrix.clear(); +} +} // namespace bool CBoxAlgorithmCSVFileReader::initialize() { @@ -194,7 +193,7 @@ bool CBoxAlgorithmCSVFileReader::initializeFile() return true; } -bool CBoxAlgorithmCSVFileReader::processClock(IMessageClock& /*messageClock*/) +bool CBoxAlgorithmCSVFileReader::processClock(Kernel::CMessageClock& /*msg*/) { getBoxAlgorithmContext()->markAlgorithmAsReadyToProcess(); return true; diff --git a/plugins/processing/file-io/src/box-algorithms/csv/ovpCBoxAlgorithmCSVFileReader.h b/plugins/processing/file-io/src/box-algorithms/csv/ovpCBoxAlgorithmCSVFileReader.h index 55c7684e3ed39b8dc6071edc7a03106c12b4a211..8bc7c94175a7d5d8e01c7cba05b365da2921948d 100755 --- a/plugins/processing/file-io/src/box-algorithms/csv/ovpCBoxAlgorithmCSVFileReader.h +++ b/plugins/processing/file-io/src/box-algorithms/csv/ovpCBoxAlgorithmCSVFileReader.h @@ -8,152 +8,149 @@ #include <cstdio> -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace FileIO { +class CBoxAlgorithmCSVFileReader final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm> { - namespace Plugins +public: + + CBoxAlgorithmCSVFileReader() {} + void release() override { delete this; } + uint64_t getClockFrequency() override { return 128LL << 32; } // the box clock frequency + bool initialize() override; + bool uninitialize() override; + bool processClock(Kernel::CMessageClock& msg) override; + bool process() override; + + bool processStreamedMatrix(); + bool processStimulation(); + bool processSignal(); + bool processChannelLocalisation(); + bool processFeatureVector(); + bool processSpectrum(); + bool convertVectorDataToMatrix(IMatrix* matrix); + + _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_CSVFileReader) + + +protected: + bool initializeFile(); + + FILE* m_file = nullptr; + std::string m_separator; + bool m_doNotUseFileTime = false; + CString m_filename; + + CIdentifier m_typeID = OV_UndefinedIdentifier; + size_t m_nCol = 0; + size_t m_sampling = 0; + size_t m_samplesPerBuffer = 0; + size_t m_channelsPerBuffer = 0; + + bool (CBoxAlgorithmCSVFileReader::*m_realProcess)() = nullptr; + + Toolkit::TEncoder<CBoxAlgorithmCSVFileReader>* m_encoder = nullptr; + + bool m_headerSent = false; + std::vector<std::string> m_lastLineSplits; + std::vector<std::string> m_headerFiles; + std::vector<std::vector<std::string>> m_dataMatrices; + + double m_nextTime = 0; + + uint64_t m_startTime = 0; + uint64_t m_endTime = 0; + + static const size_t BUFFER_LEN = 16384; // Side-effect: a maximum allowed length for a line of a CSV file +}; + +class CBoxAlgorithmCSVFileReaderListener final : public Toolkit::TBoxListener<IBoxListener> +{ +public: + bool onOutputTypeChanged(Kernel::IBox& box, const size_t index) override { - namespace FileIO + CIdentifier typeID = OV_UndefinedIdentifier; + box.getOutputType(index, typeID); + if (typeID == OV_TypeId_Spectrum) + { + box.setSettingName(3, "Unused parameter"); + box.setSettingValue(3, "0"); + } + else if (typeID == OV_TypeId_ChannelLocalisation) + { + box.setSettingName(3, "Channels number"); + box.setSettingValue(3, "32"); + } + else if (typeID == OV_TypeId_FeatureVector) + { + box.setSettingName(3, "Unused parameter"); + box.setSettingValue(3, "0"); + } + else if (typeID == OV_TypeId_StreamedMatrix) + { + box.setSettingName(3, "Samples per buffer"); + box.setSettingValue(3, "32"); + } + else if (typeID == OV_TypeId_Stimulations) { - class CBoxAlgorithmCSVFileReader final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm> - { - public: - - CBoxAlgorithmCSVFileReader() {} - void release() override { delete this; } - uint64_t getClockFrequency() override { return 128LL << 32; } // the box clock frequency - bool initialize() override; - bool uninitialize() override; - bool processClock(CMessageClock& messageClock) override; - bool process() override; - - bool processStreamedMatrix(); - bool processStimulation(); - bool processSignal(); - bool processChannelLocalisation(); - bool processFeatureVector(); - bool processSpectrum(); - bool convertVectorDataToMatrix(IMatrix* matrix); - - _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_CSVFileReader) - - - protected: - bool initializeFile(); - - FILE* m_file = nullptr; - std::string m_separator; - bool m_doNotUseFileTime = false; - CString m_filename; - - CIdentifier m_typeID = OV_UndefinedIdentifier; - size_t m_nCol = 0; - size_t m_sampling = 0; - size_t m_samplesPerBuffer = 0; - size_t m_channelsPerBuffer = 0; - - bool (CBoxAlgorithmCSVFileReader::*m_realProcess)() = nullptr; - - Toolkit::TEncoder<CBoxAlgorithmCSVFileReader>* m_encoder = nullptr; - - bool m_headerSent = false; - std::vector<std::string> m_lastLineSplits; - std::vector<std::string> m_headerFiles; - std::vector<std::vector<std::string>> m_dataMatrices; - - double m_nextTime = 0; - - uint64_t m_startTime = 0; - uint64_t m_endTime = 0; - - static const size_t BUFFER_LEN = 16384; // Side-effect: a maximum allowed length for a line of a CSV file - }; - - class CBoxAlgorithmCSVFileReaderListener final : public Toolkit::TBoxListener<IBoxListener> - { - public: - bool onOutputTypeChanged(Kernel::IBox& box, const size_t index) override - { - CIdentifier typeID = OV_UndefinedIdentifier; - box.getOutputType(index, typeID); - if (typeID == OV_TypeId_Spectrum) - { - box.setSettingName(3, "Unused parameter"); - box.setSettingValue(3, "0"); - } - else if (typeID == OV_TypeId_ChannelLocalisation) - { - box.setSettingName(3, "Channels number"); - box.setSettingValue(3, "32"); - } - else if (typeID == OV_TypeId_FeatureVector) - { - box.setSettingName(3, "Unused parameter"); - box.setSettingValue(3, "0"); - } - else if (typeID == OV_TypeId_StreamedMatrix) - { - box.setSettingName(3, "Samples per buffer"); - box.setSettingValue(3, "32"); - } - else if (typeID == OV_TypeId_Stimulations) - { - box.setSettingName(3, "Unused parameter"); - box.setSettingValue(3, "0"); - } - else - { - box.setOutputType(index, OV_TypeId_Signal); - box.setSettingName(3, "Samples per buffer"); - box.setSettingValue(3, "32"); - - OV_ERROR_KRF("Unsupported stream type " << typeID.str(), Kernel::ErrorType::BadOutput); - } - return true; - } - - _IsDerivedFromClass_Final_(Toolkit::TBoxListener<IBoxListener>, OV_UndefinedIdentifier) - }; - - class CBoxAlgorithmCSVFileReaderDesc final : virtual public IBoxAlgorithmDesc - { - public: - void release() override { } - CString getName() const override { return CString("CSV File Reader (Deprecated)"); } - CString getAuthorName() const override { return CString("Baptiste Payan"); } - CString getAuthorCompanyName() const override { return CString("INRIA"); } - CString getShortDescription() const override { return CString("Read signal in a CSV (text based) file"); } - CString getDetailedDescription() const override { return CString(""); } - CString getCategory() const override { return CString("File reading and writing/CSV"); } - CString getVersion() const override { return CString("1.0"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_CSVFileReader; } - IPluginObject* create() override { return new CBoxAlgorithmCSVFileReader; } - IBoxListener* createBoxListener() const override { return new CBoxAlgorithmCSVFileReaderListener; } - void releaseBoxListener(IBoxListener* listener) const override { delete listener; } - - bool getBoxPrototype(Kernel::IBoxProto& prototype) const override - { - prototype.addOutput("Output stream", OV_TypeId_Signal); - prototype.addSetting("Filename", OV_TypeId_Filename, ""); - prototype.addSetting("Column separator", OV_TypeId_String, ";"); - prototype.addSetting("Don't use the file time",OV_TypeId_Boolean, "false"); - prototype.addSetting("Samples per buffer", OV_TypeId_Integer, "32"); - - prototype.addFlag(Kernel::BoxFlag_CanModifyOutput); - - prototype.addOutputSupport(OV_TypeId_StreamedMatrix); - prototype.addOutputSupport(OV_TypeId_FeatureVector); - prototype.addOutputSupport(OV_TypeId_ChannelLocalisation); - prototype.addOutputSupport(OV_TypeId_Signal); - prototype.addOutputSupport(OV_TypeId_Spectrum); - prototype.addOutputSupport(OV_TypeId_Stimulations); - return true; - } - - _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_CSVFileReaderDesc) - }; - } // namespace FileIO - } // namespace Plugins + box.setSettingName(3, "Unused parameter"); + box.setSettingValue(3, "0"); + } + else + { + box.setOutputType(index, OV_TypeId_Signal); + box.setSettingName(3, "Samples per buffer"); + box.setSettingValue(3, "32"); + + OV_ERROR_KRF("Unsupported stream type " << typeID.str(), Kernel::ErrorType::BadOutput); + } + return true; + } + + _IsDerivedFromClass_Final_(Toolkit::TBoxListener<IBoxListener>, OV_UndefinedIdentifier) +}; + +class CBoxAlgorithmCSVFileReaderDesc final : virtual public IBoxAlgorithmDesc +{ +public: + void release() override { } + CString getName() const override { return CString("CSV File Reader (Deprecated)"); } + CString getAuthorName() const override { return CString("Baptiste Payan"); } + CString getAuthorCompanyName() const override { return CString("INRIA"); } + CString getShortDescription() const override { return CString("Read signal in a CSV (text based) file"); } + CString getDetailedDescription() const override { return CString(""); } + CString getCategory() const override { return CString("File reading and writing/CSV"); } + CString getVersion() const override { return CString("1.0"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_CSVFileReader; } + IPluginObject* create() override { return new CBoxAlgorithmCSVFileReader; } + IBoxListener* createBoxListener() const override { return new CBoxAlgorithmCSVFileReaderListener; } + void releaseBoxListener(IBoxListener* listener) const override { delete listener; } + + bool getBoxPrototype(Kernel::IBoxProto& prototype) const override + { + prototype.addOutput("Output stream", OV_TypeId_Signal); + prototype.addSetting("Filename", OV_TypeId_Filename, ""); + prototype.addSetting("Column separator", OV_TypeId_String, ";"); + prototype.addSetting("Don't use the file time",OV_TypeId_Boolean, "false"); + prototype.addSetting("Samples per buffer", OV_TypeId_Integer, "32"); + + prototype.addFlag(Kernel::BoxFlag_CanModifyOutput); + + prototype.addOutputSupport(OV_TypeId_StreamedMatrix); + prototype.addOutputSupport(OV_TypeId_FeatureVector); + prototype.addOutputSupport(OV_TypeId_ChannelLocalisation); + prototype.addOutputSupport(OV_TypeId_Signal); + prototype.addOutputSupport(OV_TypeId_Spectrum); + prototype.addOutputSupport(OV_TypeId_Stimulations); + return true; + } + + _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_CSVFileReaderDesc) +}; +} // namespace FileIO +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/file-io/src/box-algorithms/csv/ovpCBoxAlgorithmCSVFileWriter.h b/plugins/processing/file-io/src/box-algorithms/csv/ovpCBoxAlgorithmCSVFileWriter.h index 22cc418e660ea9303e2a5a55bdddbe2ce70e031f..ff1100f3758695a0345a43dc6552aff4d4d8d5c9 100755 --- a/plugins/processing/file-io/src/box-algorithms/csv/ovpCBoxAlgorithmCSVFileWriter.h +++ b/plugins/processing/file-io/src/box-algorithms/csv/ovpCBoxAlgorithmCSVFileWriter.h @@ -9,92 +9,89 @@ #include <fstream> -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace FileIO { +class CBoxAlgorithmCSVFileWriter final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm> { - namespace Plugins +public: + + CBoxAlgorithmCSVFileWriter() { } + void release() override { delete this; } + bool initialize() override; + bool uninitialize() override; + bool processInput(const size_t index) override; + bool process() override; + + bool processStreamedMatrix(); + bool processStimulation(); + + _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_CSVFileWriter) + + +protected: + bool initializeFile(); + + std::ofstream m_fileStream; + + CString m_separator; + CIdentifier m_typeID = OV_UndefinedIdentifier; + bool m_firstBuffer = false; + bool (CBoxAlgorithmCSVFileWriter::*m_realProcess)() = nullptr; + + Toolkit::TDecoder<CBoxAlgorithmCSVFileWriter>* m_decoder = nullptr; + CMatrix m_oMatrix; // This represents the properties of the input, no data + + uint64_t m_nSample = 0; + + bool m_headerReceived = false; +}; + +class CBoxAlgorithmCSVFileWriterListener final : public Toolkit::TBoxListener<IBoxListener> +{ +public: + + _IsDerivedFromClass_Final_(Toolkit::TBoxListener<IBoxListener>, OV_UndefinedIdentifier) +}; + +class CBoxAlgorithmCSVFileWriterDesc final : public IBoxAlgorithmDesc +{ +public: + void release() override { } + CString getName() const override { return CString("CSV File Writer (Deprecated)"); } + CString getAuthorName() const override { return CString("Yann Renard"); } + CString getAuthorCompanyName() const override { return CString("INRIA"); } + CString getShortDescription() const override { return CString("Writes signal in a CSV (text based) file"); } + CString getDetailedDescription() const override { return CString(""); } + CString getCategory() const override { return CString("File reading and writing/CSV"); } + CString getVersion() const override { return CString("1.0"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_CSVFileWriter; } + IPluginObject* create() override { return new CBoxAlgorithmCSVFileWriter; } + IBoxListener* createBoxListener() const override { return new CBoxAlgorithmCSVFileWriterListener; } + void releaseBoxListener(IBoxListener* listener) const override { delete listener; } + + bool getBoxPrototype(Kernel::IBoxProto& prototype) const override { - namespace FileIO - { - class CBoxAlgorithmCSVFileWriter final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm> - { - public: - - CBoxAlgorithmCSVFileWriter() { } - void release() override { delete this; } - bool initialize() override; - bool uninitialize() override; - bool processInput(const size_t index) override; - bool process() override; - - bool processStreamedMatrix(); - bool processStimulation(); - - _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_CSVFileWriter) - - - protected: - bool initializeFile(); - - std::ofstream m_fileStream; - - CString m_separator; - CIdentifier m_typeID = OV_UndefinedIdentifier; - bool m_firstBuffer = false; - bool (CBoxAlgorithmCSVFileWriter::*m_realProcess)() = nullptr; - - Toolkit::TDecoder<CBoxAlgorithmCSVFileWriter>* m_decoder = nullptr; - CMatrix m_oMatrix; // This represents the properties of the input, no data - - uint64_t m_nSample = 0; - - bool m_headerReceived = false; - }; - - class CBoxAlgorithmCSVFileWriterListener final : public Toolkit::TBoxListener<IBoxListener> - { - public: - - _IsDerivedFromClass_Final_(Toolkit::TBoxListener<IBoxListener>, OV_UndefinedIdentifier) - }; - - class CBoxAlgorithmCSVFileWriterDesc final : public IBoxAlgorithmDesc - { - public: - void release() override { } - CString getName() const override { return CString("CSV File Writer (Deprecated)"); } - CString getAuthorName() const override { return CString("Yann Renard"); } - CString getAuthorCompanyName() const override { return CString("INRIA"); } - CString getShortDescription() const override { return CString("Writes signal in a CSV (text based) file"); } - CString getDetailedDescription() const override { return CString(""); } - CString getCategory() const override { return CString("File reading and writing/CSV"); } - CString getVersion() const override { return CString("1.0"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_CSVFileWriter; } - IPluginObject* create() override { return new CBoxAlgorithmCSVFileWriter; } - IBoxListener* createBoxListener() const override { return new CBoxAlgorithmCSVFileWriterListener; } - void releaseBoxListener(IBoxListener* listener) const override { delete listener; } - - bool getBoxPrototype(Kernel::IBoxProto& prototype) const override - { - prototype.addInput("Input stream", OV_TypeId_Signal); - prototype.addSetting("Filename", OV_TypeId_Filename, "record-[$core{date}-$core{time}].csv"); - prototype.addSetting("Column separator", OV_TypeId_String, ";"); - prototype.addSetting("Precision", OV_TypeId_Integer, "10"); - prototype.addFlag(Kernel::BoxFlag_CanModifyInput); - - prototype.addInputSupport(OV_TypeId_Signal); - prototype.addInputSupport(OV_TypeId_StreamedMatrix); - prototype.addInputSupport(OV_TypeId_Spectrum); - prototype.addInputSupport(OV_TypeId_Stimulations); - prototype.addInputSupport(OV_TypeId_FeatureVector); - - return true; - } - - _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_CSVFileWriterDesc) - }; - } // namespace FileIO - } // namespace Plugins + prototype.addInput("Input stream", OV_TypeId_Signal); + prototype.addSetting("Filename", OV_TypeId_Filename, "record-[$core{date}-$core{time}].csv"); + prototype.addSetting("Column separator", OV_TypeId_String, ";"); + prototype.addSetting("Precision", OV_TypeId_Integer, "10"); + prototype.addFlag(Kernel::BoxFlag_CanModifyInput); + + prototype.addInputSupport(OV_TypeId_Signal); + prototype.addInputSupport(OV_TypeId_StreamedMatrix); + prototype.addInputSupport(OV_TypeId_Spectrum); + prototype.addInputSupport(OV_TypeId_Stimulations); + prototype.addInputSupport(OV_TypeId_FeatureVector); + + return true; + } + + _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_CSVFileWriterDesc) +}; +} // namespace FileIO +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/file-io/src/box-algorithms/csv/ovpCBoxAlgorithmOVCSVFileReader.cpp b/plugins/processing/file-io/src/box-algorithms/csv/ovpCBoxAlgorithmOVCSVFileReader.cpp index 4d265bb1af0b498814d783bec62a6e07c6af9ee6..c25182119faeebc06e7e1b14d47cfaadf630fceb 100755 --- a/plugins/processing/file-io/src/box-algorithms/csv/ovpCBoxAlgorithmOVCSVFileReader.cpp +++ b/plugins/processing/file-io/src/box-algorithms/csv/ovpCBoxAlgorithmOVCSVFileReader.cpp @@ -82,7 +82,7 @@ bool CBoxAlgorithmOVCSVFileReader::uninitialize() return true; } -bool CBoxAlgorithmOVCSVFileReader::processClock(IMessageClock& /*messageClock*/) +bool CBoxAlgorithmOVCSVFileReader::processClock(Kernel::CMessageClock& /*msg*/) { OV_ERROR_UNLESS_KRF(getBoxAlgorithmContext()->markAlgorithmAsReadyToProcess(), "Failed to mark clock algorithm as ready to process", ErrorType::Internal); return true; @@ -233,8 +233,7 @@ bool CBoxAlgorithmOVCSVFileReader::process() OV_ERROR_UNLESS_KRF( boxContext.markOutputAsReadyToSend(0, CTime(m_savedChunks.back().startTime).time(), CTime(m_savedChunks.back().endTime).time()), - "Failed to mark signal output as ready to send", - ErrorType::Internal); + "Failed to mark signal output as ready to send", ErrorType::Internal); } if (chunksToRemove != 0) { m_savedChunks.erase(m_savedChunks.begin(), m_savedChunks.begin() + chunksToRemove); } diff --git a/plugins/processing/file-io/src/box-algorithms/csv/ovpCBoxAlgorithmOVCSVFileReader.h b/plugins/processing/file-io/src/box-algorithms/csv/ovpCBoxAlgorithmOVCSVFileReader.h index e3c8fc1f050d26958bd8e4a47f9c80c800012d19..643c7a6fda5d51bcbc28da3476f9808edf095227 100755 --- a/plugins/processing/file-io/src/box-algorithms/csv/ovpCBoxAlgorithmOVCSVFileReader.h +++ b/plugins/processing/file-io/src/box-algorithms/csv/ovpCBoxAlgorithmOVCSVFileReader.h @@ -9,113 +9,109 @@ #include "csv/ovICSV.h" -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace FileIO { +class CBoxAlgorithmOVCSVFileReader final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm> { - namespace Plugins +public: + + CBoxAlgorithmOVCSVFileReader() : m_readerLib(CSV::createCSVHandler(), CSV::releaseCSVHandler) { } + void release() override { delete this; } + uint64_t getClockFrequency() override { return 128LL << 32; } + bool initialize() override; + bool uninitialize() override; + bool processClock(Kernel::CMessageClock& msg) override; + bool process() override; + + _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_OVCSVFileReader) + +private: + bool processStimulation(double startTime, double endTime); + + std::unique_ptr<CSV::ICSVHandler, decltype(&CSV::releaseCSVHandler)> m_readerLib; + + Toolkit::TGenericEncoder<CBoxAlgorithmOVCSVFileReader> m_algorithmEncoder; + Toolkit::TStimulationEncoder<CBoxAlgorithmOVCSVFileReader> m_stimEncoder; + + std::deque<CSV::SMatrixChunk> m_savedChunks; + std::deque<CSV::SStimulationChunk> m_savedStimulations; + + uint64_t m_lastStimulationDate = 0; + + CIdentifier m_typeID = OV_UndefinedIdentifier; + std::vector<std::string> m_channelNames; + std::vector<size_t> m_dimSizes; + size_t m_sampling = 0; + size_t m_nSamplePerBuffer = 0; + + bool m_isHeaderSent = false; + bool m_isStimulationHeaderSent = false; + std::vector<double> m_frequencyAbscissa; +}; + +class CBoxAlgorithmOVCSVFileReaderListener final : public Toolkit::TBoxListener<IBoxListener> +{ +public: + bool onOutputTypeChanged(Kernel::IBox& box, const size_t index) override { - namespace FileIO + CIdentifier typeID = OV_UndefinedIdentifier; + box.getOutputType(index, typeID); + + if (index == 0 && typeID == OV_TypeId_Stimulations) { - class CBoxAlgorithmOVCSVFileReader final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm> - { - public: - - CBoxAlgorithmOVCSVFileReader() : m_readerLib(CSV::createCSVHandler(), CSV::releaseCSVHandler) { } - void release() override { delete this; } - uint64_t getClockFrequency() override { return 128LL << 32; } - bool initialize() override; - bool uninitialize() override; - bool processClock(CMessageClock& messageClock) override; - bool process() override; - - _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_OVCSVFileReader) - - private: - bool processStimulation(double startTime, double endTime); - - std::unique_ptr<CSV::ICSVHandler, decltype(&CSV::releaseCSVHandler)> m_readerLib; - - Toolkit::TGenericEncoder<CBoxAlgorithmOVCSVFileReader> m_algorithmEncoder; - Toolkit::TStimulationEncoder<CBoxAlgorithmOVCSVFileReader> m_stimEncoder; - - std::deque<CSV::SMatrixChunk> m_savedChunks; - std::deque<CSV::SStimulationChunk> m_savedStimulations; - - uint64_t m_lastStimulationDate = 0; - - CIdentifier m_typeID = OV_UndefinedIdentifier; - std::vector<std::string> m_channelNames; - std::vector<size_t> m_dimSizes; - size_t m_sampling = 0; - size_t m_nSamplePerBuffer = 0; - - bool m_isHeaderSent = false; - bool m_isStimulationHeaderSent = false; - std::vector<double> m_frequencyAbscissa; - }; - - class CBoxAlgorithmOVCSVFileReaderListener final : public Toolkit::TBoxListener<IBoxListener> - { - public: - bool onOutputTypeChanged(Kernel::IBox& box, const size_t index) override - { - CIdentifier typeID = OV_UndefinedIdentifier; - box.getOutputType(index, typeID); - - if (index == 0 && typeID == OV_TypeId_Stimulations) - { - OV_ERROR_UNLESS_KRF(box.setOutputType(index, OV_TypeId_Signal), "Failed to reset output type to signal", Kernel::ErrorType::Internal); - } - else if (index == 1 && typeID != OV_TypeId_Stimulations) - { - OV_ERROR_UNLESS_KRF(box.setOutputType(index, OV_TypeId_Stimulations), "Failed to reset output type to stimulations", - Kernel::ErrorType::Internal); - } - else if (index > 1) { OV_ERROR_UNLESS_KRF(false, "The index of the output does not exist", Kernel::ErrorType::Internal); } - - return true; - } - - _IsDerivedFromClass_Final_(Toolkit::TBoxListener<IBoxListener>, OV_UndefinedIdentifier) - }; - - class CBoxAlgorithmOVCSVFileReaderDesc final : virtual public IBoxAlgorithmDesc - { - public: - void release() override { } - CString getName() const override { return CString("CSV File Reader"); } - CString getAuthorName() const override { return CString("Victor Herlin"); } - CString getAuthorCompanyName() const override { return CString("Mensia Technologies SA"); } - CString getShortDescription() const override { return CString("Read signal in a CSV (text based) file"); } - CString getDetailedDescription() const override { return CString(""); } - CString getCategory() const override { return CString("File reading and writing/CSV"); } - CString getVersion() const override { return CString("1.1"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.1.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.3.3"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_OVCSVFileReader; } - IPluginObject* create() override { return new CBoxAlgorithmOVCSVFileReader; } - IBoxListener* createBoxListener() const override { return new CBoxAlgorithmOVCSVFileReaderListener; } - void releaseBoxListener(IBoxListener* listener) const override { delete listener; } - - bool getBoxPrototype(Kernel::IBoxProto& BoxAlgorithmPrototype) const override - { - BoxAlgorithmPrototype.addOutput("Output stream", OV_TypeId_Signal); - BoxAlgorithmPrototype.addOutput("Output stimulation", OV_TypeId_Stimulations); - BoxAlgorithmPrototype.addSetting("Filename", OV_TypeId_Filename, ""); - - BoxAlgorithmPrototype.addFlag(Kernel::BoxFlag_CanModifyOutput); - - BoxAlgorithmPrototype.addOutputSupport(OV_TypeId_Signal); - BoxAlgorithmPrototype.addOutputSupport(OV_TypeId_Spectrum); - BoxAlgorithmPrototype.addOutputSupport(OV_TypeId_FeatureVector); - BoxAlgorithmPrototype.addOutputSupport(OV_TypeId_StreamedMatrix); - BoxAlgorithmPrototype.addOutputSupport(OV_TypeId_CovarianceMatrix); - BoxAlgorithmPrototype.addOutputSupport(OV_TypeId_Stimulations); - return true; - } - - _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_OVCSVFileReaderDesc) - }; - } // namespace FileIO - } // namespace Plugins + OV_ERROR_UNLESS_KRF(box.setOutputType(index, OV_TypeId_Signal), "Failed to reset output type to signal", Kernel::ErrorType::Internal); + } + else if (index == 1 && typeID != OV_TypeId_Stimulations) + { + OV_ERROR_UNLESS_KRF(box.setOutputType(index, OV_TypeId_Stimulations), "Failed to reset output type to stimulations", Kernel::ErrorType::Internal); + } + else if (index > 1) { OV_ERROR_UNLESS_KRF(false, "The index of the output does not exist", Kernel::ErrorType::Internal); } + + return true; + } + + _IsDerivedFromClass_Final_(Toolkit::TBoxListener<IBoxListener>, OV_UndefinedIdentifier) +}; + +class CBoxAlgorithmOVCSVFileReaderDesc final : virtual public IBoxAlgorithmDesc +{ +public: + void release() override { } + CString getName() const override { return CString("CSV File Reader"); } + CString getAuthorName() const override { return CString("Victor Herlin"); } + CString getAuthorCompanyName() const override { return CString("Mensia Technologies SA"); } + CString getShortDescription() const override { return CString("Read signal in a CSV (text based) file"); } + CString getDetailedDescription() const override { return CString(""); } + CString getCategory() const override { return CString("File reading and writing/CSV"); } + CString getVersion() const override { return CString("1.1"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.1.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.3.3"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_OVCSVFileReader; } + IPluginObject* create() override { return new CBoxAlgorithmOVCSVFileReader; } + IBoxListener* createBoxListener() const override { return new CBoxAlgorithmOVCSVFileReaderListener; } + void releaseBoxListener(IBoxListener* listener) const override { delete listener; } + + bool getBoxPrototype(Kernel::IBoxProto& BoxAlgorithmPrototype) const override + { + BoxAlgorithmPrototype.addOutput("Output stream", OV_TypeId_Signal); + BoxAlgorithmPrototype.addOutput("Output stimulation", OV_TypeId_Stimulations); + BoxAlgorithmPrototype.addSetting("Filename", OV_TypeId_Filename, ""); + + BoxAlgorithmPrototype.addFlag(Kernel::BoxFlag_CanModifyOutput); + + BoxAlgorithmPrototype.addOutputSupport(OV_TypeId_Signal); + BoxAlgorithmPrototype.addOutputSupport(OV_TypeId_Spectrum); + BoxAlgorithmPrototype.addOutputSupport(OV_TypeId_FeatureVector); + BoxAlgorithmPrototype.addOutputSupport(OV_TypeId_StreamedMatrix); + BoxAlgorithmPrototype.addOutputSupport(OV_TypeId_CovarianceMatrix); + BoxAlgorithmPrototype.addOutputSupport(OV_TypeId_Stimulations); + return true; + } + + _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_OVCSVFileReaderDesc) +}; +} // namespace FileIO +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/file-io/src/box-algorithms/csv/ovpCBoxAlgorithmOVCSVFileWriter.cpp b/plugins/processing/file-io/src/box-algorithms/csv/ovpCBoxAlgorithmOVCSVFileWriter.cpp index 5d79974801a428acfc2ae96cec38349ab032b02b..6ab2c76e5e63b61e725104795644e2ee9de2ede4 100755 --- a/plugins/processing/file-io/src/box-algorithms/csv/ovpCBoxAlgorithmOVCSVFileWriter.cpp +++ b/plugins/processing/file-io/src/box-algorithms/csv/ovpCBoxAlgorithmOVCSVFileWriter.cpp @@ -41,9 +41,7 @@ bool CBoxAlgorithmOVCSVFileWriter::initialize() } else { OV_ERROR_KRF("Input is a type derived from matrix that the box doesn't recognize", ErrorType::BadInput); } - OV_ERROR_UNLESS_KRF(m_stimDecoder.initialize(*this, 1), - "Error while stimulation decoder initialization", - ErrorType::Internal); + OV_ERROR_UNLESS_KRF(m_stimDecoder.initialize(*this, 1), "Error while stimulation decoder initialization", ErrorType::Internal); const CString filename = FSettingValueAutoCast(*this->getBoxAlgorithmContext(), 0); @@ -56,8 +54,7 @@ bool CBoxAlgorithmOVCSVFileWriter::initialize() { OV_ERROR_UNLESS_KRF(m_writerLib->openFile(filename.toASCIIString(), CSV::EFileAccessMode::Write), (CSV::ICSVHandler::getLogError(m_writerLib->getLastLogError()) + (m_writerLib->getLastErrorString().empty() ? "" : - "Details: " + m_writerLib->getLastErrorString())).c_str(), - ErrorType::Internal); + "Details: " + m_writerLib->getLastErrorString())).c_str(), ErrorType::Internal); m_writeHeader = true; } else @@ -73,8 +70,7 @@ bool CBoxAlgorithmOVCSVFileWriter::initialize() OV_ERROR_UNLESS_KRF(m_writerLib->openFile(filename.toASCIIString(), CSV::EFileAccessMode::Append), (CSV::ICSVHandler::getLogError(m_writerLib->getLastLogError()) + (m_writerLib->getLastErrorString().empty() ? "" : - "Details: " + m_writerLib->getLastErrorString())).c_str(), - ErrorType::Internal); + "Details: " + m_writerLib->getLastErrorString())).c_str(), ErrorType::Internal); } m_isHeaderReceived = false; @@ -89,18 +85,15 @@ bool CBoxAlgorithmOVCSVFileWriter::uninitialize() OV_ERROR_UNLESS_KRF(m_writerLib->noEventsUntilDate(std::numeric_limits<double>::max()), (CSV::ICSVHandler::getLogError(m_writerLib->getLastLogError()) + (m_writerLib->getLastErrorString().empty() ? "" : "Details: " - + m_writerLib->getLastErrorString())).c_str(), - ErrorType::Internal); + + m_writerLib->getLastErrorString())).c_str(), ErrorType::Internal); OV_ERROR_UNLESS_KRF(m_writerLib->writeAllDataToFile(), (CSV::ICSVHandler::getLogError(m_writerLib->getLastLogError()) + (m_writerLib->getLastErrorString().empty() ? "" : "Details: " - + m_writerLib->getLastErrorString())).c_str(), - ErrorType::Internal); + + m_writerLib->getLastErrorString())).c_str(), ErrorType::Internal); OV_ERROR_UNLESS_KRF(m_writerLib->closeFile(), (CSV::ICSVHandler::getLogError(m_writerLib->getLastLogError()) + (m_writerLib->getLastErrorString().empty() ? "" : "Details: " - + m_writerLib->getLastErrorString())).c_str(), - ErrorType::Internal); + + m_writerLib->getLastErrorString())).c_str(), ErrorType::Internal); return true; } @@ -113,20 +106,15 @@ bool CBoxAlgorithmOVCSVFileWriter::processInput(const size_t /*index*/) bool CBoxAlgorithmOVCSVFileWriter::process() { - OV_ERROR_UNLESS_KRF(this->processStreamedMatrix(), - "Error have been thrown during streamed matrix process", - ErrorType::Internal); - OV_ERROR_UNLESS_KRF(this->processStimulation(), - "Error have been thrown during stimulation process", - ErrorType::Internal); + OV_ERROR_UNLESS_KRF(this->processStreamedMatrix(), "Error have been thrown during streamed matrix process", ErrorType::Internal); + OV_ERROR_UNLESS_KRF(this->processStimulation(), "Error have been thrown during stimulation process", ErrorType::Internal); // write into the library if (!m_lastMatrixOnly) { OV_ERROR_UNLESS_KRF(m_writerLib->writeDataToFile(), (CSV::ICSVHandler::getLogError(m_writerLib->getLastLogError()) + (m_writerLib->getLastErrorString().empty() ? "" : - "Details: " + m_writerLib->getLastErrorString())).c_str(), - ErrorType::Internal); + "Details: " + m_writerLib->getLastErrorString())).c_str(), ErrorType::Internal); } return true; @@ -181,15 +169,13 @@ bool CBoxAlgorithmOVCSVFileWriter::processStreamedMatrix() OV_ERROR_UNLESS_KRF(m_writerLib->setStreamedMatrixInformation(dimensionSizes, dimensionLabels), (CSV::ICSVHandler::getLogError(m_writerLib->getLastLogError()) + (m_writerLib->getLastErrorString().empty() ? "" : - "Details: " + m_writerLib->getLastErrorString())).c_str(), - ErrorType::Internal); + "Details: " + m_writerLib->getLastErrorString())).c_str(), ErrorType::Internal); if (m_writeHeader) { OV_ERROR_UNLESS_KRF(m_writerLib->writeHeaderToFile(), (CSV::ICSVHandler::getLogError(m_writerLib->getLastLogError()) + (m_writerLib->getLastErrorString().empty() ? - "" : "Details: " + m_writerLib->getLastErrorString())).c_str(), - ErrorType::Internal); + "" : "Details: " + m_writerLib->getLastErrorString())).c_str(), ErrorType::Internal); } } else if (m_typeID == OV_TypeId_FeatureVector) @@ -200,15 +186,13 @@ bool CBoxAlgorithmOVCSVFileWriter::processStreamedMatrix() OV_ERROR_UNLESS_KRF(m_writerLib->setFeatureVectorInformation(channelsLabels), (CSV::ICSVHandler::getLogError(m_writerLib->getLastLogError()) + (m_writerLib->getLastErrorString().empty() ? "" : - "Details: " + m_writerLib->getLastErrorString())).c_str(), - ErrorType::Internal); + "Details: " + m_writerLib->getLastErrorString())).c_str(), ErrorType::Internal); if (m_writeHeader) { OV_ERROR_UNLESS_KRF(m_writerLib->writeHeaderToFile(), (CSV::ICSVHandler::getLogError(m_writerLib->getLastLogError()) + (m_writerLib->getLastErrorString().empty() ? - "" : "Details: " + m_writerLib->getLastErrorString())).c_str(), - ErrorType::Internal); + "" : "Details: " + m_writerLib->getLastErrorString())).c_str(), ErrorType::Internal); } } else if (m_typeID == OV_TypeId_Spectrum) @@ -268,8 +252,7 @@ bool CBoxAlgorithmOVCSVFileWriter::processStreamedMatrix() // add sample to the library OV_ERROR_UNLESS_KRF(m_writerLib->addSample({ startTime, endTime, matrixValues, m_epoch }), (CSV::ICSVHandler::getLogError(m_writerLib->getLastLogError()) + (m_writerLib->getLastErrorString().empty() ? - "" : "Details: " + m_writerLib->getLastErrorString())).c_str(), - ErrorType::Internal); + "" : "Details: " + m_writerLib->getLastErrorString())).c_str(), ErrorType::Internal); } } else if (m_typeID == OV_TypeId_StreamedMatrix || m_typeID == OV_TypeId_CovarianceMatrix) @@ -280,8 +263,7 @@ bool CBoxAlgorithmOVCSVFileWriter::processStreamedMatrix() OV_ERROR_UNLESS_KRF(m_writerLib->addSample({ startTime, endTime, streamedMatrixValues, m_epoch }), (CSV::ICSVHandler::getLogError(m_writerLib->getLastLogError()) + (m_writerLib->getLastErrorString().empty() ? "" : - "Details: " + m_writerLib->getLastErrorString())).c_str(), - ErrorType::Internal); + "Details: " + m_writerLib->getLastErrorString())).c_str(), ErrorType::Internal); } else if (m_typeID == OV_TypeId_FeatureVector) { @@ -293,8 +275,7 @@ bool CBoxAlgorithmOVCSVFileWriter::processStreamedMatrix() OV_ERROR_UNLESS_KRF(m_writerLib->addSample({ startTime, endTime, streamedMatrixValues, m_epoch }), (CSV::ICSVHandler::getLogError(m_writerLib->getLastLogError()) + (m_writerLib->getLastErrorString().empty() ? "" : - "Details: " + m_writerLib->getLastErrorString())).c_str(), - ErrorType::Internal); + "Details: " + m_writerLib->getLastErrorString())).c_str(), ErrorType::Internal); } else if (m_typeID == OV_TypeId_Spectrum) { @@ -304,8 +285,7 @@ bool CBoxAlgorithmOVCSVFileWriter::processStreamedMatrix() OV_ERROR_UNLESS_KRF(m_writerLib->addSample({ startTime, endTime, streamedMatrixValues, m_epoch }), (CSV::ICSVHandler::getLogError(m_writerLib->getLastLogError()) + (m_writerLib->getLastErrorString().empty() ? "" : - "Details: " + m_writerLib->getLastErrorString())).c_str(), - ErrorType::Internal); + "Details: " + m_writerLib->getLastErrorString())).c_str(), ErrorType::Internal); } m_epoch++; @@ -337,16 +317,14 @@ bool CBoxAlgorithmOVCSVFileWriter::processStimulation() CTime(stimulationSet->getStimulationDate(j)).toSeconds(), CTime(stimulationSet->getStimulationDuration(j)).toSeconds() }), (CSV::ICSVHandler::getLogError(m_writerLib->getLastLogError()) + (m_writerLib->getLastErrorString().empty() ? "" : - "Details: " + m_writerLib->getLastErrorString())).c_str(), - ErrorType::Internal); + "Details: " + m_writerLib->getLastErrorString())).c_str(), ErrorType::Internal); } - + // set NoEventUntilDate to prevent time that will be empty of stimulations until the end of the last chunk OV_ERROR_UNLESS_KRF( m_writerLib->noEventsUntilDate(CTime(dynamicBoxContext.getInputChunkEndTime(1, (dynamicBoxContext.getInputChunkCount(1) - 1))).toSeconds()), (CSV::ICSVHandler::getLogError(m_writerLib->getLastLogError()) + (m_writerLib->getLastErrorString().empty() ? "" : "Details: " + m_writerLib-> - getLastErrorString())).c_str(), - ErrorType::Internal); + getLastErrorString())).c_str(), ErrorType::Internal); } OV_ERROR_UNLESS_KRF(dynamicBoxContext.markInputAsDeprecated(1, i), "Failed to mark stimulations input as deprecated", ErrorType::Internal); diff --git a/plugins/processing/file-io/src/box-algorithms/csv/ovpCBoxAlgorithmOVCSVFileWriter.h b/plugins/processing/file-io/src/box-algorithms/csv/ovpCBoxAlgorithmOVCSVFileWriter.h index 56f16ae6ce52467ed89f2792857f925b811caa9e..085bdd9762c46f5c2bbb2d2bf7114a57c0785aeb 100755 --- a/plugins/processing/file-io/src/box-algorithms/csv/ovpCBoxAlgorithmOVCSVFileWriter.h +++ b/plugins/processing/file-io/src/box-algorithms/csv/ovpCBoxAlgorithmOVCSVFileWriter.h @@ -9,108 +9,105 @@ #include "csv/ovICSV.h" -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace FileIO { +class CBoxAlgorithmOVCSVFileWriter final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm> { - namespace Plugins - { - namespace FileIO - { - class CBoxAlgorithmOVCSVFileWriter final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm> - { - public: +public: - CBoxAlgorithmOVCSVFileWriter(); - void release() override { delete this; } + CBoxAlgorithmOVCSVFileWriter(); + void release() override { delete this; } - bool initialize() override; - bool uninitialize() override; - bool processInput(const size_t index) override; - bool process() override; + bool initialize() override; + bool uninitialize() override; + bool processInput(const size_t index) override; + bool process() override; - _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_OVCSVFileWriter) + _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_OVCSVFileWriter) - private: - bool processStreamedMatrix(); - bool processStimulation(); +private: + bool processStreamedMatrix(); + bool processStimulation(); - std::unique_ptr<CSV::ICSVHandler, decltype(&CSV::releaseCSVHandler)> m_writerLib; + std::unique_ptr<CSV::ICSVHandler, decltype(&CSV::releaseCSVHandler)> m_writerLib; - CIdentifier m_typeID = OV_UndefinedIdentifier; + CIdentifier m_typeID = OV_UndefinedIdentifier; - Toolkit::TGenericDecoder<CBoxAlgorithmOVCSVFileWriter> m_streamDecoder; - Toolkit::TStimulationDecoder<CBoxAlgorithmOVCSVFileWriter> m_stimDecoder; + Toolkit::TGenericDecoder<CBoxAlgorithmOVCSVFileWriter> m_streamDecoder; + Toolkit::TStimulationDecoder<CBoxAlgorithmOVCSVFileWriter> m_stimDecoder; - uint64_t m_epoch = 0; + uint64_t m_epoch = 0; - bool m_isHeaderReceived = false; - bool m_isFileOpen = false; - bool m_appendData = false; - bool m_lastMatrixOnly = false; - bool m_writeHeader = true; - }; + bool m_isHeaderReceived = false; + bool m_isFileOpen = false; + bool m_appendData = false; + bool m_lastMatrixOnly = false; + bool m_writeHeader = true; +}; - class CBoxAlgorithmOVCSVFileWriterListener final : public Toolkit::TBoxListener<IBoxListener> - { - public: - bool onInputTypeChanged(Kernel::IBox& box, const size_t index) override - { - if (index == 1) - { - CIdentifier typeID = OV_UndefinedIdentifier; - box.getInputType(1, typeID); - if (typeID != OV_TypeId_Stimulations) - { - box.setInputType(1, OV_TypeId_Stimulations); - return true; - } - } - - return true; - } - - _IsDerivedFromClass_Final_(Toolkit::TBoxListener<IBoxListener>, OV_UndefinedIdentifier) - }; - - class CBoxAlgorithmOVCSVFileWriterDesc final : public IBoxAlgorithmDesc +class CBoxAlgorithmOVCSVFileWriterListener final : public Toolkit::TBoxListener<IBoxListener> +{ +public: + bool onInputTypeChanged(Kernel::IBox& box, const size_t index) override + { + if (index == 1) + { + CIdentifier typeID = OV_UndefinedIdentifier; + box.getInputType(1, typeID); + if (typeID != OV_TypeId_Stimulations) { - public: - void release() override { } - CString getName() const override { return CString("CSV File Writer"); } - CString getAuthorName() const override { return CString("Victor Herlin"); } - CString getAuthorCompanyName() const override { return CString("Mensia Technologies SA"); } - CString getShortDescription() const override { return CString("Writes signal in a CSV (text based) file"); } - CString getDetailedDescription() const override { return CString(""); } - CString getCategory() const override { return CString("File reading and writing/CSV"); } - CString getVersion() const override { return CString("1.0"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.1.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.1.0"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_OVCSVFileWriter; } - IPluginObject* create() override { return new CBoxAlgorithmOVCSVFileWriter; } - IBoxListener* createBoxListener() const override { return new CBoxAlgorithmOVCSVFileWriterListener; } - void releaseBoxListener(IBoxListener* boxListener) const override { delete boxListener; } - - bool getBoxPrototype(Kernel::IBoxProto& prototype) const override - { - prototype.addInput("Input stream", OV_TypeId_Signal); - prototype.addInput("Stimulations stream", OV_TypeId_Stimulations); - prototype.addSetting("Filename", OV_TypeId_Filename, "record-[$core{date}-$core{time}].csv"); - prototype.addSetting("Precision", OV_TypeId_Integer, "10"); - prototype.addSetting("Append data", OV_TypeId_Boolean, "false"); - prototype.addSetting("Only last matrix", OV_TypeId_Boolean, "false"); - prototype.addFlag(Kernel::BoxFlag_CanModifyInput); - - prototype.addInputSupport(OV_TypeId_Signal); - prototype.addInputSupport(OV_TypeId_StreamedMatrix); - prototype.addInputSupport(OV_TypeId_Spectrum); - prototype.addInputSupport(OV_TypeId_FeatureVector); - prototype.addInputSupport(OV_TypeId_CovarianceMatrix); - - return true; - } - - _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_OVCSVFileWriterDesc) - }; - } // namespace FileIO - } // namespace Plugins + box.setInputType(1, OV_TypeId_Stimulations); + return true; + } + } + + return true; + } + + _IsDerivedFromClass_Final_(Toolkit::TBoxListener<IBoxListener>, OV_UndefinedIdentifier) +}; + +class CBoxAlgorithmOVCSVFileWriterDesc final : public IBoxAlgorithmDesc +{ +public: + void release() override { } + CString getName() const override { return CString("CSV File Writer"); } + CString getAuthorName() const override { return CString("Victor Herlin"); } + CString getAuthorCompanyName() const override { return CString("Mensia Technologies SA"); } + CString getShortDescription() const override { return CString("Writes signal in a CSV (text based) file"); } + CString getDetailedDescription() const override { return CString(""); } + CString getCategory() const override { return CString("File reading and writing/CSV"); } + CString getVersion() const override { return CString("1.0"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.1.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.1.0"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_OVCSVFileWriter; } + IPluginObject* create() override { return new CBoxAlgorithmOVCSVFileWriter; } + IBoxListener* createBoxListener() const override { return new CBoxAlgorithmOVCSVFileWriterListener; } + void releaseBoxListener(IBoxListener* boxListener) const override { delete boxListener; } + + bool getBoxPrototype(Kernel::IBoxProto& prototype) const override + { + prototype.addInput("Input stream", OV_TypeId_Signal); + prototype.addInput("Stimulations stream", OV_TypeId_Stimulations); + prototype.addSetting("Filename", OV_TypeId_Filename, "record-[$core{date}-$core{time}].csv"); + prototype.addSetting("Precision", OV_TypeId_Integer, "10"); + prototype.addSetting("Append data", OV_TypeId_Boolean, "false"); + prototype.addSetting("Only last matrix", OV_TypeId_Boolean, "false"); + prototype.addFlag(Kernel::BoxFlag_CanModifyInput); + + prototype.addInputSupport(OV_TypeId_Signal); + prototype.addInputSupport(OV_TypeId_StreamedMatrix); + prototype.addInputSupport(OV_TypeId_Spectrum); + prototype.addInputSupport(OV_TypeId_FeatureVector); + prototype.addInputSupport(OV_TypeId_CovarianceMatrix); + + return true; + } + + _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_OVCSVFileWriterDesc) +}; +} // namespace FileIO +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/file-io/src/box-algorithms/openvibe/ovpCBoxAlgorithmGenericStreamReader.cpp b/plugins/processing/file-io/src/box-algorithms/openvibe/ovpCBoxAlgorithmGenericStreamReader.cpp index 37e5520067a8d9995098c8fd553726793c9d60e3..58656655bb2b4b0837670f0f7a497e3f736b9aff 100755 --- a/plugins/processing/file-io/src/box-algorithms/openvibe/ovpCBoxAlgorithmGenericStreamReader.cpp +++ b/plugins/processing/file-io/src/box-algorithms/openvibe/ovpCBoxAlgorithmGenericStreamReader.cpp @@ -10,11 +10,7 @@ using namespace /*OpenViBE::*/Plugins; using namespace FileIO; CBoxAlgorithmGenericStreamReader::CBoxAlgorithmGenericStreamReader() : m_reader(*this) {} - -uint64_t CBoxAlgorithmGenericStreamReader::getClockFrequency() -{ - return 128LL << 32; // the box clock frequency -} +uint64_t CBoxAlgorithmGenericStreamReader::getClockFrequency() { return 128LL << 32; } // the box clock frequency bool CBoxAlgorithmGenericStreamReader::initialize() { @@ -46,7 +42,7 @@ bool CBoxAlgorithmGenericStreamReader::initializeFile() return true; } -bool CBoxAlgorithmGenericStreamReader::processClock(IMessageClock& /*messageClock*/) +bool CBoxAlgorithmGenericStreamReader::processClock(Kernel::CMessageClock& /*msg*/) { getBoxAlgorithmContext()->markAlgorithmAsReadyToProcess(); @@ -260,7 +256,7 @@ void CBoxAlgorithmGenericStreamReader::closeChild() if (top == OVP_NodeId_OpenViBEStream_Buffer) { - m_pending = ((m_outputIdx != std::numeric_limits<size_t>::max()) && + m_pending = ((m_outputIdx != std::numeric_limits<size_t>::max()) && (m_startTime != std::numeric_limits<uint64_t>::max()) && (m_endTime != std::numeric_limits<uint64_t>::max())); } diff --git a/plugins/processing/file-io/src/box-algorithms/openvibe/ovpCBoxAlgorithmGenericStreamReader.h b/plugins/processing/file-io/src/box-algorithms/openvibe/ovpCBoxAlgorithmGenericStreamReader.h index df879f4fbf4f81a59a06981c96aae461f8a10548..9b83cb688077751ce57d8561a1f9c312dbb31777 100644 --- a/plugins/processing/file-io/src/box-algorithms/openvibe/ovpCBoxAlgorithmGenericStreamReader.h +++ b/plugins/processing/file-io/src/box-algorithms/openvibe/ovpCBoxAlgorithmGenericStreamReader.h @@ -12,130 +12,124 @@ #include <cstdio> -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace FileIO { +class CBoxAlgorithmGenericStreamReader final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm>, public EBML::IReaderCallback { - namespace Plugins +public: + + CBoxAlgorithmGenericStreamReader(); + void release() override { delete this; } + uint64_t getClockFrequency() override; + bool initialize() override; + bool uninitialize() override; + bool processClock(Kernel::CMessageClock& msg) override; + bool process() override; + + _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_GenericStreamReader) + + +protected: + + CString m_filename; + + EBML::CReader m_reader; + EBML::CReaderHelper m_readerHelper; + + CMemoryBuffer m_swap; + CMemoryBuffer m_pendingChunk; + uint64_t m_startTime = 0; + uint64_t m_endTime = 0; + size_t m_outputIdx = 0; + bool m_pending = false; + bool m_hasEBMLHeader = false; + + FILE* m_file = nullptr; + std::stack<EBML::CIdentifier> m_nodes; + std::map<size_t, size_t> m_streamIdxToOutputIdxs; + std::map<size_t, CIdentifier> m_streamIdxToTypeIDs; + +private: + bool initializeFile(); + bool isMasterChild(const EBML::CIdentifier& identifier) override; + void openChild(const EBML::CIdentifier& identifier) override; + void processChildData(const void* buffer, const size_t size) override; + void closeChild() override; +}; + +class CBoxAlgorithmGenericStreamReaderListener final : public Toolkit::TBoxListener<IBoxListener> +{ +public: + + bool check(Kernel::IBox& box) const + { + for (size_t i = 0; i < box.getOutputCount(); ++i) { box.setOutputName(i, ("Output stream " + std::to_string(i + 1)).c_str()); } + return true; + } + + bool onDefaultInitialized(Kernel::IBox& box) override + { + box.setOutputName(0, "Output Signal"); + box.setOutputType(0, OV_TypeId_Signal); + box.addOutput("Output Stimulations", OV_TypeId_Stimulations); + return true; + } + + bool onOutputAdded(Kernel::IBox& box, const size_t index) override + { + box.setOutputType(index, OV_TypeId_EBMLStream); + this->check(box); + return true; + } + + bool onOutputRemoved(Kernel::IBox& box, const size_t /*index*/) override + { + this->check(box); + return true; + } + + bool onOutputTypeChanged(Kernel::IBox& box, const size_t /*index*/) override + { + this->check(box); + return true; + } + + _IsDerivedFromClass_Final_(Toolkit::TBoxListener<IBoxListener>, OV_UndefinedIdentifier) +}; + +class CBoxAlgorithmGenericStreamReaderDesc final : virtual public IBoxAlgorithmDesc +{ +public: + void release() override { } + CString getName() const override { return CString("Generic stream reader"); } + CString getAuthorName() const override { return CString("Yann Renard"); } + CString getAuthorCompanyName() const override { return CString("INRIA"); } + CString getShortDescription() const override { return CString("Reads OpenViBE streams saved in the .ov format"); } + + CString getDetailedDescription() const override { return CString("Generic Stream Writer box can be used to store data in the format read by this box"); } + + CString getCategory() const override { return CString("File reading and writing/OpenViBE"); } + CString getVersion() const override { return CString("1.0"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_GenericStreamReader; } + IPluginObject* create() override { return new CBoxAlgorithmGenericStreamReader; } + IBoxListener* createBoxListener() const override { return new CBoxAlgorithmGenericStreamReaderListener; } + void releaseBoxListener(IBoxListener* listener) const override { delete listener; } + + bool getBoxPrototype(Kernel::IBoxProto& prototype) const override { - namespace FileIO - { - class CBoxAlgorithmGenericStreamReader final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm>, public EBML::IReaderCallback - { - public: - - CBoxAlgorithmGenericStreamReader(); - void release() override { delete this; } - uint64_t getClockFrequency() override; - bool initialize() override; - bool uninitialize() override; - bool processClock(CMessageClock& messageClock) override; - bool process() override; - - _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_GenericStreamReader) - - - protected: - - CString m_filename; - - EBML::CReader m_reader; - EBML::CReaderHelper m_readerHelper; - - CMemoryBuffer m_swap; - CMemoryBuffer m_pendingChunk; - uint64_t m_startTime = 0; - uint64_t m_endTime = 0; - size_t m_outputIdx = 0; - bool m_pending = false; - bool m_hasEBMLHeader = false; - - FILE* m_file = nullptr; - std::stack<EBML::CIdentifier> m_nodes; - std::map<size_t, size_t> m_streamIdxToOutputIdxs; - std::map<size_t, CIdentifier> m_streamIdxToTypeIDs; - - private: - bool initializeFile(); - bool isMasterChild(const EBML::CIdentifier& identifier) override; - void openChild(const EBML::CIdentifier& identifier) override; - void processChildData(const void* buffer, const size_t size) override; - void closeChild() override; - }; - - class CBoxAlgorithmGenericStreamReaderListener final : public Toolkit::TBoxListener<IBoxListener> - { - public: - - bool check(Kernel::IBox& box) const - { - for (size_t i = 0; i < box.getOutputCount(); ++i) { box.setOutputName(i, ("Output stream " + std::to_string(i + 1)).c_str()); } - return true; - } - - bool onDefaultInitialized(Kernel::IBox& box) override - { - box.setOutputName(0, "Output Signal"); - box.setOutputType(0, OV_TypeId_Signal); - box.addOutput("Output Stimulations", OV_TypeId_Stimulations); - return true; - } - - bool onOutputAdded(Kernel::IBox& box, const size_t index) override - { - box.setOutputType(index, OV_TypeId_EBMLStream); - this->check(box); - return true; - } - - bool onOutputRemoved(Kernel::IBox& box, const size_t /*index*/) override - { - this->check(box); - return true; - } - - bool onOutputTypeChanged(Kernel::IBox& box, const size_t /*index*/) override - { - this->check(box); - return true; - } - - _IsDerivedFromClass_Final_(Toolkit::TBoxListener<IBoxListener>, OV_UndefinedIdentifier) - }; - - class CBoxAlgorithmGenericStreamReaderDesc final : virtual public IBoxAlgorithmDesc - { - public: - void release() override { } - CString getName() const override { return CString("Generic stream reader"); } - CString getAuthorName() const override { return CString("Yann Renard"); } - CString getAuthorCompanyName() const override { return CString("INRIA"); } - CString getShortDescription() const override { return CString("Reads OpenViBE streams saved in the .ov format"); } - - CString getDetailedDescription() const override - { - return CString("Generic Stream Writer box can be used to store data in the format read by this box"); - } - - CString getCategory() const override { return CString("File reading and writing/OpenViBE"); } - CString getVersion() const override { return CString("1.0"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_GenericStreamReader; } - IPluginObject* create() override { return new CBoxAlgorithmGenericStreamReader; } - IBoxListener* createBoxListener() const override { return new CBoxAlgorithmGenericStreamReaderListener; } - void releaseBoxListener(IBoxListener* listener) const override { delete listener; } - - bool getBoxPrototype(Kernel::IBoxProto& prototype) const override - { - prototype.addOutput("Output stream 1", OV_TypeId_EBMLStream); - prototype.addSetting("Filename", OV_TypeId_Filename, ""); - prototype.addFlag(Kernel::BoxFlag_CanAddOutput); - prototype.addFlag(Kernel::BoxFlag_CanModifyOutput); - return true; - } - - _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_GenericStreamReaderDesc) - }; - } // namespace FileIO - } // namespace Plugins + prototype.addOutput("Output stream 1", OV_TypeId_EBMLStream); + prototype.addSetting("Filename", OV_TypeId_Filename, ""); + prototype.addFlag(Kernel::BoxFlag_CanAddOutput); + prototype.addFlag(Kernel::BoxFlag_CanModifyOutput); + return true; + } + + _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_GenericStreamReaderDesc) +}; +} // namespace FileIO +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/file-io/src/box-algorithms/openvibe/ovpCBoxAlgorithmGenericStreamWriter.h b/plugins/processing/file-io/src/box-algorithms/openvibe/ovpCBoxAlgorithmGenericStreamWriter.h index 3708a8f3f617265fbd9ac023f9a3a3ad16c290e8..557d17d6108f6386d6418638dd1694f0415949d4 100644 --- a/plugins/processing/file-io/src/box-algorithms/openvibe/ovpCBoxAlgorithmGenericStreamWriter.h +++ b/plugins/processing/file-io/src/box-algorithms/openvibe/ovpCBoxAlgorithmGenericStreamWriter.h @@ -11,118 +11,115 @@ #include <fstream> -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace FileIO { +class CBoxAlgorithmGenericStreamWriter final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm>, public EBML::IWriterCallback { - namespace Plugins +public: + + CBoxAlgorithmGenericStreamWriter(); + void release() override { delete this; } + bool initialize() override; + bool uninitialize() override; + bool processInput(const size_t index) override; + bool process() override; + + bool generateFileHeader(); + + _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_GenericStreamWriter) + +protected: + + bool m_isHeaderGenerate = false; + CString m_filename; + EBML::CWriter m_writer; + EBML::CWriterHelper m_writerHelper; + +private: + void write(const void* buffer, const size_t size) override; + + CMemoryBuffer m_swap; + std::ofstream m_file; +}; + +class CBoxAlgorithmGenericStreamWriterListener final : public Toolkit::TBoxListener<IBoxListener> +{ +public: + + //it seems the only purpose of the check was to give a name when adding an input + //without it, the input configuration dialog display random characters in the name field + //the check is unnecessary when removing/changing inputs and on already named inputs + bool check(Kernel::IBox& box) + { + const size_t i = box.getInputCount() - 1; + //only check last input (we assume previous inputs have benn named, how could they not?) + box.setInputName(i, ("Input stream " + std::to_string(i + 1)).c_str()); + //for (i=0; i<box.getInputCount(); ++i) { box.setInputName(i, ("Input stream " + std::to_string(i + 1)).c_str()); } + return true; + } + + bool onDefaultInitialized(Kernel::IBox& box) override + { + box.setInputName(0, "Input Signal"); + box.setInputType(0, OV_TypeId_Signal); + box.addInput("Input Stimulations", OV_TypeId_Stimulations); + return true; + } + + bool onInputAdded(Kernel::IBox& box, const size_t index) override + { + box.setInputType(index, OV_TypeId_EBMLStream); + this->check(box); + return true; + } + + bool onInputRemoved(Kernel::IBox& /*box*/, const size_t /*index*/) override + { + //this->check(box); + return true; + } + + bool onInputTypeChanged(Kernel::IBox& /*box*/, const size_t /*index*/) override + { + //this->check(box); + return true; + } + + _IsDerivedFromClass_Final_(Toolkit::TBoxListener<IBoxListener>, OV_UndefinedIdentifier) +}; + +class CBoxAlgorithmGenericStreamWriterDesc final : virtual public IBoxAlgorithmDesc +{ +public: + void release() override { } + CString getName() const override { return CString("Generic stream writer"); } + CString getAuthorName() const override { return CString("Yann Renard"); } + CString getAuthorCompanyName() const override { return CString("INRIA"); } + CString getShortDescription() const override { return CString("Writes any number of streams into an .ov file"); } + CString getDetailedDescription() const override { return CString(""); } + CString getCategory() const override { return CString("File reading and writing/OpenViBE"); } + CString getVersion() const override { return CString("1.0"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_GenericStreamWriter; } + IPluginObject* create() override { return new CBoxAlgorithmGenericStreamWriter; } + IBoxListener* createBoxListener() const override { return new CBoxAlgorithmGenericStreamWriterListener; } + void releaseBoxListener(IBoxListener* listener) const override { delete listener; } + + bool getBoxPrototype(Kernel::IBoxProto& prototype) const override { - namespace FileIO - { - class CBoxAlgorithmGenericStreamWriter final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm>, public EBML::IWriterCallback - { - public: - - CBoxAlgorithmGenericStreamWriter(); - void release() override { delete this; } - bool initialize() override; - bool uninitialize() override; - bool processInput(const size_t index) override; - bool process() override; - - bool generateFileHeader(); - - _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_GenericStreamWriter) - - protected: - - bool m_isHeaderGenerate = false; - CString m_filename; - EBML::CWriter m_writer; - EBML::CWriterHelper m_writerHelper; - - private: - void write(const void* buffer, const size_t size) override; - - CMemoryBuffer m_swap; - std::ofstream m_file; - }; - - class CBoxAlgorithmGenericStreamWriterListener final : public Toolkit::TBoxListener<IBoxListener> - { - public: - - //it seems the only purpose of the check was to give a name when adding an input - //without it, the input configuration dialog display random characters in the name field - //the check is unnecessary when removing/changing inputs and on already named inputs - bool check(Kernel::IBox& box) - { - const size_t i = box.getInputCount() - 1; - //only check last input (we assume previous inputs have benn named, how could they not?) - box.setInputName(i, ("Input stream " + std::to_string(i + 1)).c_str()); - //for (i=0; i<box.getInputCount(); ++i) { box.setInputName(i, ("Input stream " + std::to_string(i + 1)).c_str()); } - return true; - } - - bool onDefaultInitialized(Kernel::IBox& box) override - { - box.setInputName(0, "Input Signal"); - box.setInputType(0, OV_TypeId_Signal); - box.addInput("Input Stimulations", OV_TypeId_Stimulations); - return true; - } - - bool onInputAdded(Kernel::IBox& box, const size_t index) override - { - box.setInputType(index, OV_TypeId_EBMLStream); - this->check(box); - return true; - } - - bool onInputRemoved(Kernel::IBox& /*box*/, const size_t /*index*/) override - { - //this->check(box); - return true; - } - - bool onInputTypeChanged(Kernel::IBox& /*box*/, const size_t /*index*/) override - { - //this->check(box); - return true; - } - - _IsDerivedFromClass_Final_(Toolkit::TBoxListener<IBoxListener>, OV_UndefinedIdentifier) - }; - - class CBoxAlgorithmGenericStreamWriterDesc final : virtual public IBoxAlgorithmDesc - { - public: - void release() override { } - CString getName() const override { return CString("Generic stream writer"); } - CString getAuthorName() const override { return CString("Yann Renard"); } - CString getAuthorCompanyName() const override { return CString("INRIA"); } - CString getShortDescription() const override { return CString("Writes any number of streams into an .ov file"); } - CString getDetailedDescription() const override { return CString(""); } - CString getCategory() const override { return CString("File reading and writing/OpenViBE"); } - CString getVersion() const override { return CString("1.0"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_GenericStreamWriter; } - IPluginObject* create() override { return new CBoxAlgorithmGenericStreamWriter; } - IBoxListener* createBoxListener() const override { return new CBoxAlgorithmGenericStreamWriterListener; } - void releaseBoxListener(IBoxListener* listener) const override { delete listener; } - - bool getBoxPrototype(Kernel::IBoxProto& prototype) const override - { - prototype.addInput("Input stream 1", OV_TypeId_EBMLStream); - prototype.addSetting("Filename", OV_TypeId_Filename, "record-[$core{date}-$core{time}].ov"); - prototype.addSetting("Use compression", OV_TypeId_Boolean, "false"); - prototype.addFlag(Kernel::BoxFlag_CanAddInput); - prototype.addFlag(Kernel::BoxFlag_CanModifyInput); - return true; - } - - _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_GenericStreamWriterDesc) - }; - } // namespace FileIO - } // namespace Plugins + prototype.addInput("Input stream 1", OV_TypeId_EBMLStream); + prototype.addSetting("Filename", OV_TypeId_Filename, "record-[$core{date}-$core{time}].ov"); + prototype.addSetting("Use compression", OV_TypeId_Boolean, "false"); + prototype.addFlag(Kernel::BoxFlag_CanAddInput); + prototype.addFlag(Kernel::BoxFlag_CanModifyInput); + return true; + } + + _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_GenericStreamWriterDesc) +}; +} // namespace FileIO +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/file-io/src/box-algorithms/ovpCBoxAlgorithmElectrodeLocalizationFileReader.cpp b/plugins/processing/file-io/src/box-algorithms/ovpCBoxAlgorithmElectrodeLocalizationFileReader.cpp index f3cb656923c2dab8a90b53f42a589c098266fac3..eda63ebcfd5d254cc4253a808e6992197ed8ea17 100644 --- a/plugins/processing/file-io/src/box-algorithms/ovpCBoxAlgorithmElectrodeLocalizationFileReader.cpp +++ b/plugins/processing/file-io/src/box-algorithms/ovpCBoxAlgorithmElectrodeLocalizationFileReader.cpp @@ -61,7 +61,7 @@ bool CBoxAlgorithmElectrodeLocalisationFileReader::uninitialize() return true; } -bool CBoxAlgorithmElectrodeLocalisationFileReader::processClock(CMessageClock& /*messageClock*/) +bool CBoxAlgorithmElectrodeLocalisationFileReader::processClock(Kernel::CMessageClock& /*msg*/) { getBoxAlgorithmContext()->markAlgorithmAsReadyToProcess(); return true; @@ -80,8 +80,7 @@ bool CBoxAlgorithmElectrodeLocalisationFileReader::process() //ensure matrix is 2 dimensional and that dimension sizes are correct OV_ERROR_UNLESS_KRF(op_pMatrix->getDimensionCount() == 2 && op_pMatrix->getDimensionSize(1) == 3, - "Wrong format for electrode localisation matrix loaded from file " << m_filename, - ErrorType::BadParsing); + "Wrong format for electrode localisation matrix loaded from file " << m_filename, ErrorType::BadParsing); if (m_headerSent == false) { diff --git a/plugins/processing/file-io/src/box-algorithms/ovpCBoxAlgorithmElectrodeLocalizationFileReader.h b/plugins/processing/file-io/src/box-algorithms/ovpCBoxAlgorithmElectrodeLocalizationFileReader.h index 2a4c993a1d9f7c996c88e743c9954d9be53b557e..314d54f331d6b3682c59df88ea75e4e8dfaad74d 100644 --- a/plugins/processing/file-io/src/box-algorithms/ovpCBoxAlgorithmElectrodeLocalizationFileReader.h +++ b/plugins/processing/file-io/src/box-algorithms/ovpCBoxAlgorithmElectrodeLocalizationFileReader.h @@ -4,66 +4,63 @@ #include <openvibe/ov_all.h> #include <toolkit/ovtk_all.h> -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace FileIO { +class CBoxAlgorithmElectrodeLocalisationFileReader final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm> { - namespace Plugins - { - namespace FileIO - { - class CBoxAlgorithmElectrodeLocalisationFileReader final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm> - { - public: - void release() override { delete this; } - uint64_t getClockFrequency() override; - bool initialize() override; - bool uninitialize() override; - bool processClock(CMessageClock& messageClock) override; - bool process() override; +public: + void release() override { delete this; } + uint64_t getClockFrequency() override; + bool initialize() override; + bool uninitialize() override; + bool processClock(Kernel::CMessageClock& msg) override; + bool process() override; - _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_ElectrodeLocalisationFileReader) + _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_ElectrodeLocalisationFileReader) - protected: +protected: - Kernel::IAlgorithmProxy* m_pOVMatrixFileReader = nullptr; - Toolkit::TChannelLocalisationEncoder<CBoxAlgorithmElectrodeLocalisationFileReader>* m_encoder = nullptr; + Kernel::IAlgorithmProxy* m_pOVMatrixFileReader = nullptr; + Toolkit::TChannelLocalisationEncoder<CBoxAlgorithmElectrodeLocalisationFileReader>* m_encoder = nullptr; - CString m_filename; - bool m_headerSent = false; - bool m_bufferSent = false; - }; + CString m_filename; + bool m_headerSent = false; + bool m_bufferSent = false; +}; - class CBoxAlgorithmElectrodeLocalisationFileReaderDesc final : public IBoxAlgorithmDesc - { - public: - void release() override { } - CString getName() const override { return CString("Electrode localisation file reader"); } - CString getAuthorName() const override { return CString("Vincent Delannoy"); } - CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } +class CBoxAlgorithmElectrodeLocalisationFileReaderDesc final : public IBoxAlgorithmDesc +{ +public: + void release() override { } + CString getName() const override { return CString("Electrode localisation file reader"); } + CString getAuthorName() const override { return CString("Vincent Delannoy"); } + CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } - CString getShortDescription() const override { return CString("Loads files containing the normalized coordinates of an electrode set"); } + CString getShortDescription() const override { return CString("Loads files containing the normalized coordinates of an electrode set"); } - CString getDetailedDescription() const override { return CString(""); } - CString getCategory() const override { return CString("File reading and writing/OpenViBE"); } - CString getVersion() const override { return CString("1.0"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_ElectrodeLocalisationFileReader; } - IPluginObject* create() override { return new CBoxAlgorithmElectrodeLocalisationFileReader; } + CString getDetailedDescription() const override { return CString(""); } + CString getCategory() const override { return CString("File reading and writing/OpenViBE"); } + CString getVersion() const override { return CString("1.0"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_ElectrodeLocalisationFileReader; } + IPluginObject* create() override { return new CBoxAlgorithmElectrodeLocalisationFileReader; } - bool getBoxPrototype(Kernel::IBoxProto& prototype) const override - { - // Adds box outputs - prototype.addOutput("Channel localisation", OV_TypeId_ChannelLocalisation); + bool getBoxPrototype(Kernel::IBoxProto& prototype) const override + { + // Adds box outputs + prototype.addOutput("Channel localisation", OV_TypeId_ChannelLocalisation); - // Adds settings - prototype.addSetting("Filename", OV_TypeId_Filename, ""); + // Adds settings + prototype.addSetting("Filename", OV_TypeId_Filename, ""); - return true; - } + return true; + } - _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_ElectrodeLocalisationFileReaderDesc) - }; - } // namespace FileIO - } // namespace Plugins + _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_ElectrodeLocalisationFileReaderDesc) +}; +} // namespace FileIO +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/signal-processing/CMakeLists.txt b/plugins/processing/signal-processing/CMakeLists.txt index d1ee51616a6ab074cbe982bff063638ff144f433..e5276a26d4e5c70c4d06d3e26e0718a64d5295b3 100644 --- a/plugins/processing/signal-processing/CMakeLists.txt +++ b/plugins/processing/signal-processing/CMakeLists.txt @@ -14,6 +14,7 @@ ADD_LIBRARY(${PROJECT_NAME} SHARED ${SRC_FILES}) SET_TARGET_PROPERTIES(${PROJECT_NAME} PROPERTIES VERSION ${PROJECT_VERSION} SOVERSION ${PROJECT_VERSION_MAJOR} + FOLDER ${PLUGINS_FOLDER} COMPILE_FLAGS "-DOVP_Exports -DOVP_Shared") INCLUDE("FindOpenViBE") @@ -27,9 +28,7 @@ INCLUDE("FindThirdPartyEigen") # --------------------------------- # Target macros -# Defines target operating system -# Defines target architecture -# Defines target compiler +# Defines target operating system, architecture and compiler # --------------------------------- SET_BUILD_PLATFORM() diff --git a/plugins/processing/signal-processing/src/algorithms/basic/ovpCAlgorithmMatrixAverage.h b/plugins/processing/signal-processing/src/algorithms/basic/ovpCAlgorithmMatrixAverage.h index baa8754afc3d5d426e0b4958c817c24d94233cf9..991fc0a70570fbad3fa3a9b42cf53bbd603bdd9f 100644 --- a/plugins/processing/signal-processing/src/algorithms/basic/ovpCAlgorithmMatrixAverage.h +++ b/plugins/processing/signal-processing/src/algorithms/basic/ovpCAlgorithmMatrixAverage.h @@ -7,71 +7,67 @@ #include <vector> #include <deque> -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace SignalProcessing { +class CAlgorithmMatrixAverage final : public Toolkit::TAlgorithm<IAlgorithm> { - namespace Plugins - { - namespace SignalProcessing - { - class CAlgorithmMatrixAverage final : public Toolkit::TAlgorithm<IAlgorithm> - { - public: - void release() override { delete this; } - bool initialize() override; - bool uninitialize() override; - bool process() override; +public: + void release() override { delete this; } + bool initialize() override; + bool uninitialize() override; + bool process() override; - _IsDerivedFromClass_Final_(Toolkit::TAlgorithm<IAlgorithm>, OVP_ClassId_Algorithm_MatrixAverage) + _IsDerivedFromClass_Final_(Toolkit::TAlgorithm<IAlgorithm>, OVP_ClassId_Algorithm_MatrixAverage) - protected: +protected: - Kernel::TParameterHandler<uint64_t> ip_averagingMethod; - Kernel::TParameterHandler<uint64_t> ip_matrixCount; - Kernel::TParameterHandler<IMatrix*> ip_matrix; - Kernel::TParameterHandler<IMatrix*> op_averagedMatrix; + Kernel::TParameterHandler<uint64_t> ip_averagingMethod; + Kernel::TParameterHandler<uint64_t> ip_matrixCount; + Kernel::TParameterHandler<IMatrix*> ip_matrix; + Kernel::TParameterHandler<IMatrix*> op_averagedMatrix; - std::deque<IMatrix*> m_history; - std::vector<double> m_averageMatrices; - size_t m_nAverageSamples = 0; - }; + std::deque<IMatrix*> m_history; + std::vector<double> m_averageMatrices; + size_t m_nAverageSamples = 0; +}; - class CAlgorithmMatrixAverageDesc final : public IAlgorithmDesc - { - public: - void release() override { } - CString getName() const override { return CString("Matrix average"); } - CString getAuthorName() const override { return CString("Yann Renard"); } - CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } - CString getShortDescription() const override { return CString(""); } - CString getDetailedDescription() const override { return CString(""); } - CString getCategory() const override { return CString("Signal processing/Averaging"); } - CString getVersion() const override { return CString("1.1"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_Algorithm_MatrixAverage; } - IPluginObject* create() override { return new CAlgorithmMatrixAverage(); } +class CAlgorithmMatrixAverageDesc final : public IAlgorithmDesc +{ +public: + void release() override { } + CString getName() const override { return CString("Matrix average"); } + CString getAuthorName() const override { return CString("Yann Renard"); } + CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } + CString getShortDescription() const override { return CString(""); } + CString getDetailedDescription() const override { return CString(""); } + CString getCategory() const override { return CString("Signal processing/Averaging"); } + CString getVersion() const override { return CString("1.1"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_Algorithm_MatrixAverage; } + IPluginObject* create() override { return new CAlgorithmMatrixAverage(); } - bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override - { - prototype.addInputParameter(OVP_Algorithm_MatrixAverage_InputParameterId_Matrix, "Matrix", Kernel::ParameterType_Matrix); - prototype.addInputParameter(OVP_Algorithm_MatrixAverage_InputParameterId_MatrixCount, "Matrix count", Kernel::ParameterType_UInteger); - prototype.addInputParameter( - OVP_Algorithm_MatrixAverage_InputParameterId_AveragingMethod, "Averaging Method", Kernel::ParameterType_UInteger); + bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override + { + prototype.addInputParameter(OVP_Algorithm_MatrixAverage_InputParameterId_Matrix, "Matrix", Kernel::ParameterType_Matrix); + prototype.addInputParameter(OVP_Algorithm_MatrixAverage_InputParameterId_MatrixCount, "Matrix count", Kernel::ParameterType_UInteger); + prototype.addInputParameter(OVP_Algorithm_MatrixAverage_InputParameterId_AveragingMethod, "Averaging Method", Kernel::ParameterType_UInteger); - prototype.addOutputParameter(OVP_Algorithm_MatrixAverage_OutputParameterId_AveragedMatrix, "Averaged matrix", Kernel::ParameterType_Matrix); + prototype.addOutputParameter(OVP_Algorithm_MatrixAverage_OutputParameterId_AveragedMatrix, "Averaged matrix", Kernel::ParameterType_Matrix); - prototype.addInputTrigger(OVP_Algorithm_MatrixAverage_InputTriggerId_Reset, "Reset"); - prototype.addInputTrigger(OVP_Algorithm_MatrixAverage_InputTriggerId_FeedMatrix, "Feed matrix"); - prototype.addInputTrigger(OVP_Algorithm_MatrixAverage_InputTriggerId_ForceAverage, "Force average"); + prototype.addInputTrigger(OVP_Algorithm_MatrixAverage_InputTriggerId_Reset, "Reset"); + prototype.addInputTrigger(OVP_Algorithm_MatrixAverage_InputTriggerId_FeedMatrix, "Feed matrix"); + prototype.addInputTrigger(OVP_Algorithm_MatrixAverage_InputTriggerId_ForceAverage, "Force average"); - prototype.addOutputTrigger(OVP_Algorithm_MatrixAverage_OutputTriggerId_AveragePerformed, "Average performed"); + prototype.addOutputTrigger(OVP_Algorithm_MatrixAverage_OutputTriggerId_AveragePerformed, "Average performed"); - return true; - } + return true; + } - _IsDerivedFromClass_Final_(IAlgorithmDesc, OVP_ClassId_Algorithm_MatrixAverageDesc) - }; - } // namespace SignalProcessing - } // namespace Plugins + _IsDerivedFromClass_Final_(IAlgorithmDesc, OVP_ClassId_Algorithm_MatrixAverageDesc) +}; +} // namespace SignalProcessing +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/signal-processing/src/algorithms/basic/ovpCAlgorithmOnlineCovariance.cpp b/plugins/processing/signal-processing/src/algorithms/basic/ovpCAlgorithmOnlineCovariance.cpp index aaa078cc491b6c5a60f2978a7bc72f1816242b44..3b22cc04e7992f73a74e136bf51e729594530e25 100644 --- a/plugins/processing/signal-processing/src/algorithms/basic/ovpCAlgorithmOnlineCovariance.cpp +++ b/plugins/processing/signal-processing/src/algorithms/basic/ovpCAlgorithmOnlineCovariance.cpp @@ -49,9 +49,7 @@ bool CAlgorithmOnlineCovariance::process() if (isInputTriggerActive(OVP_Algorithm_OnlineCovariance_Process_Reset)) { - OV_ERROR_UNLESS_KRF(ip_Shrinkage >= 0.0 && ip_Shrinkage <= 1.0, - "Invalid shrinkage parameter (expected value between 0 and 1)", - ErrorType::BadInput); + OV_ERROR_UNLESS_KRF(ip_Shrinkage >= 0.0 && ip_Shrinkage <= 1.0, "Invalid shrinkage parameter (expected value between 0 and 1)", ErrorType::BadInput); OV_ERROR_UNLESS_KRF(ip_FeatureVectorSet->getDimensionCount() == 2, "Invalid feature vector with " << ip_FeatureVectorSet->getDimensionCount() << " dimensions (expected dim = 2)", @@ -60,9 +58,7 @@ bool CAlgorithmOnlineCovariance::process() const size_t nRows = ip_FeatureVectorSet->getDimensionSize(0); const size_t nCols = ip_FeatureVectorSet->getDimensionSize(1); - OV_ERROR_UNLESS_KRF(nRows >= 1 && nCols >= 1, - "Invalid input matrix [" << nRows << "x" << nCols << "(minimum expected = 1x1)", - ErrorType::BadInput); + OV_ERROR_UNLESS_KRF(nRows >= 1 && nCols >= 1, "Invalid input matrix [" << nRows << "x" << nCols << "(minimum expected = 1x1)", ErrorType::BadInput); this->getLogManager() << LogLevel_Debug << "Using shrinkage coeff " << ip_Shrinkage << " ...\n"; this->getLogManager() << LogLevel_Debug << "Trace normalization is " << (ip_TraceNormalization ? "[on]" : "[off]") << "\n"; diff --git a/plugins/processing/signal-processing/src/algorithms/basic/ovpCAlgorithmOnlineCovariance.h b/plugins/processing/signal-processing/src/algorithms/basic/ovpCAlgorithmOnlineCovariance.h index 7db4fdd58aae65558685e7dae228d395c6114c50..d42dc4c0f057759f6d3764f2d2b31b4cc101d183 100644 --- a/plugins/processing/signal-processing/src/algorithms/basic/ovpCAlgorithmOnlineCovariance.h +++ b/plugins/processing/signal-processing/src/algorithms/basic/ovpCAlgorithmOnlineCovariance.h @@ -13,85 +13,76 @@ #include <Eigen/Dense> -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace SignalProcessing { +class CAlgorithmOnlineCovariance final : virtual public Toolkit::TAlgorithm<IAlgorithm> { - namespace Plugins + typedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> MatrixXdRowMajor; + +public: + void release() override { delete this; } + bool initialize() override; + bool uninitialize() override; + bool process() override; + + _IsDerivedFromClass_Final_(Toolkit::TAlgorithm<IAlgorithm>, OVP_ClassId_Algorithm_OnlineCovariance) + +protected: + // Debug method. Prints the matrix to the logManager. May be disabled in implementation. + static void dumpMatrix(Kernel::ILogManager& mgr, const MatrixXdRowMajor& mat, const CString& desc); + + // These are non-normalized estimates for the corresp. statistics + Eigen::MatrixXd m_cov; + Eigen::MatrixXd m_mean; + + // The divisor for the above estimates to do the normalization + uint64_t m_n = 0; +}; + +class CAlgorithmOnlineCovarianceDesc final : virtual public IAlgorithmDesc +{ +public: + void release() override { } + CString getName() const override { return CString("Online Covariance"); } + CString getAuthorName() const override { return CString("Jussi T. Lindgren"); } + CString getAuthorCompanyName() const override { return CString("Inria"); } + CString getShortDescription() const override { return CString("Incrementally computes covariance with shrinkage."); } + + CString getDetailedDescription() const override { return CString("Regularized covariance output is computed as (diag*shrink + cov)"); } + + CString getCategory() const override { return CString(""); } + CString getVersion() const override { return CString("0.5"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_Algorithm_OnlineCovariance; } + IPluginObject* create() override { return new CAlgorithmOnlineCovariance; } + + bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override { - namespace SignalProcessing - { - class CAlgorithmOnlineCovariance final : virtual public Toolkit::TAlgorithm<IAlgorithm> - { - typedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> MatrixXdRowMajor; - - public: - void release() override { delete this; } - bool initialize() override; - bool uninitialize() override; - bool process() override; - - _IsDerivedFromClass_Final_(Toolkit::TAlgorithm<IAlgorithm>, OVP_ClassId_Algorithm_OnlineCovariance) - - protected: - // Debug method. Prints the matrix to the logManager. May be disabled in implementation. - static void dumpMatrix(Kernel::ILogManager& mgr, const MatrixXdRowMajor& mat, const CString& desc); - - // These are non-normalized estimates for the corresp. statistics - Eigen::MatrixXd m_cov; - Eigen::MatrixXd m_mean; - - // The divisor for the above estimates to do the normalization - uint64_t m_n = 0; - }; - - class CAlgorithmOnlineCovarianceDesc final : virtual public IAlgorithmDesc - { - public: - void release() override { } - CString getName() const override { return CString("Online Covariance"); } - CString getAuthorName() const override { return CString("Jussi T. Lindgren"); } - CString getAuthorCompanyName() const override { return CString("Inria"); } - CString getShortDescription() const override { return CString("Incrementally computes covariance with shrinkage."); } - - CString getDetailedDescription() const override { return CString("Regularized covariance output is computed as (diag*shrink + cov)"); } - - CString getCategory() const override { return CString(""); } - CString getVersion() const override { return CString("0.5"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_Algorithm_OnlineCovariance; } - IPluginObject* create() override { return new CAlgorithmOnlineCovariance; } - - bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override - { - prototype.addInputParameter( - OVP_Algorithm_OnlineCovariance_InputParameterId_Shrinkage, "Shrinkage", Kernel::ParameterType_Float); - prototype.addInputParameter( - OVP_Algorithm_OnlineCovariance_InputParameterId_InputVectors, "Input vectors", Kernel::ParameterType_Matrix); - prototype.addInputParameter( - OVP_Algorithm_OnlineCovariance_InputParameterId_UpdateMethod, "Cov update method", Kernel::ParameterType_Enumeration, - OVP_TypeId_OnlineCovariance_UpdateMethod); - prototype.addInputParameter( - OVP_Algorithm_OnlineCovariance_InputParameterId_TraceNormalization, "Trace normalization", Kernel::ParameterType_Boolean); - - // The algorithm returns these outputs - prototype.addOutputParameter( - OVP_Algorithm_OnlineCovariance_OutputParameterId_Mean, "Mean vector", Kernel::ParameterType_Matrix); - prototype.addOutputParameter( - OVP_Algorithm_OnlineCovariance_OutputParameterId_CovarianceMatrix, "Covariance matrix", Kernel::ParameterType_Matrix); - - prototype.addInputTrigger(OVP_Algorithm_OnlineCovariance_Process_Reset, "Reset the algorithm"); - prototype.addInputTrigger(OVP_Algorithm_OnlineCovariance_Process_Update, "Append a chunk of data"); - prototype.addInputTrigger(OVP_Algorithm_OnlineCovariance_Process_GetCov, "Get the current regularized covariance matrix & mean"); - prototype.addInputTrigger(OVP_Algorithm_OnlineCovariance_Process_GetCovRaw, "Get the current covariance matrix & mean"); - - return true; - } - - _IsDerivedFromClass_Final_(IAlgorithmDesc, OVP_ClassId_Algorithm_OnlineCovarianceDesc) - }; - } // namespace SignalProcessing - } // namespace Plugins + prototype.addInputParameter(OVP_Algorithm_OnlineCovariance_InputParameterId_Shrinkage, "Shrinkage", Kernel::ParameterType_Float); + prototype.addInputParameter(OVP_Algorithm_OnlineCovariance_InputParameterId_InputVectors, "Input vectors", Kernel::ParameterType_Matrix); + prototype.addInputParameter(OVP_Algorithm_OnlineCovariance_InputParameterId_UpdateMethod, "Cov update method", Kernel::ParameterType_Enumeration, + OVP_TypeId_OnlineCovariance_UpdateMethod); + prototype.addInputParameter(OVP_Algorithm_OnlineCovariance_InputParameterId_TraceNormalization, "Trace normalization", Kernel::ParameterType_Boolean); + + // The algorithm returns these outputs + prototype.addOutputParameter(OVP_Algorithm_OnlineCovariance_OutputParameterId_Mean, "Mean vector", Kernel::ParameterType_Matrix); + prototype.addOutputParameter(OVP_Algorithm_OnlineCovariance_OutputParameterId_CovarianceMatrix, "Covariance matrix", Kernel::ParameterType_Matrix); + + prototype.addInputTrigger(OVP_Algorithm_OnlineCovariance_Process_Reset, "Reset the algorithm"); + prototype.addInputTrigger(OVP_Algorithm_OnlineCovariance_Process_Update, "Append a chunk of data"); + prototype.addInputTrigger(OVP_Algorithm_OnlineCovariance_Process_GetCov, "Get the current regularized covariance matrix & mean"); + prototype.addInputTrigger(OVP_Algorithm_OnlineCovariance_Process_GetCovRaw, "Get the current covariance matrix & mean"); + + return true; + } + + _IsDerivedFromClass_Final_(IAlgorithmDesc, OVP_ClassId_Algorithm_OnlineCovarianceDesc) +}; +} // namespace SignalProcessing +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/signal-processing/src/box-algorithms/basic/ovpCBoxAlgorithmChannelRename.h b/plugins/processing/signal-processing/src/box-algorithms/basic/ovpCBoxAlgorithmChannelRename.h index f1cda870db735669763ecc49d767cc9b0acfd5ea..94afe34e01766a4817b93c9f23d5d108d312a67f 100644 --- a/plugins/processing/signal-processing/src/box-algorithms/basic/ovpCBoxAlgorithmChannelRename.h +++ b/plugins/processing/signal-processing/src/box-algorithms/basic/ovpCBoxAlgorithmChannelRename.h @@ -7,103 +7,100 @@ #include <string> #include <vector> -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace SignalProcessing { +class CBoxAlgorithmChannelRename final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm> { - namespace Plugins +public: + void release() override { delete this; } + bool initialize() override; + bool uninitialize() override; + bool processInput(const size_t index) override; + bool process() override; + + _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_ChannelRename) + +protected: + + Toolkit::TGenericDecoder<CBoxAlgorithmChannelRename> m_decoder; + Toolkit::TGenericEncoder<CBoxAlgorithmChannelRename> m_encoder; + + CIdentifier m_typeID = OV_UndefinedIdentifier; + + Kernel::TParameterHandler<IMatrix*> ip_Matrix; + Kernel::TParameterHandler<IMatrix*> op_Matrix; + + std::vector<std::string> m_names; +}; + +class CBoxAlgorithmChannelRenameListener final : public Toolkit::TBoxListener<IBoxListener> +{ +public: + bool onInputTypeChanged(Kernel::IBox& box, const size_t index) override + { + CIdentifier typeID = OV_UndefinedIdentifier; + box.getInputType(index, typeID); + box.setOutputType(index, typeID); + return true; + } + + bool onOutputTypeChanged(Kernel::IBox& box, const size_t index) override + { + CIdentifier typeID = OV_UndefinedIdentifier; + box.getOutputType(index, typeID); + box.setInputType(index, typeID); + return true; + } + + + _IsDerivedFromClass_Final_(Toolkit::TBoxListener<IBoxListener>, OV_UndefinedIdentifier) +}; + +class CBoxAlgorithmChannelRenameDesc final : public IBoxAlgorithmDesc +{ +public: + void release() override { } + CString getName() const override { return CString("Channel Rename"); } + CString getAuthorName() const override { return CString("Yann Renard"); } + CString getAuthorCompanyName() const override { return CString("INRIA"); } + CString getShortDescription() const override { return CString("Renames channels of different types of streamed matrices"); } + CString getDetailedDescription() const override { return CString(""); } + CString getCategory() const override { return CString("Signal processing/Channels"); } + CString getVersion() const override { return CString("1.1"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("1.1.0"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_ChannelRename; } + IPluginObject* create() override { return new CBoxAlgorithmChannelRename; } + IBoxListener* createBoxListener() const override { return new CBoxAlgorithmChannelRenameListener; } + void releaseBoxListener(IBoxListener* boxListener) const override { delete boxListener; } + + bool getBoxPrototype(Kernel::IBoxProto& prototype) const override { - namespace SignalProcessing - { - class CBoxAlgorithmChannelRename final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm> - { - public: - void release() override { delete this; } - bool initialize() override; - bool uninitialize() override; - bool processInput(const size_t index) override; - bool process() override; - - _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_ChannelRename) - - protected: - - Toolkit::TGenericDecoder<CBoxAlgorithmChannelRename> m_decoder; - Toolkit::TGenericEncoder<CBoxAlgorithmChannelRename> m_encoder; - - CIdentifier m_typeID = OV_UndefinedIdentifier; - - Kernel::TParameterHandler<IMatrix*> ip_Matrix; - Kernel::TParameterHandler<IMatrix*> op_Matrix; - - std::vector<std::string> m_names; - }; - - class CBoxAlgorithmChannelRenameListener final : public Toolkit::TBoxListener<IBoxListener> - { - public: - bool onInputTypeChanged(Kernel::IBox& box, const size_t index) override - { - CIdentifier typeID = OV_UndefinedIdentifier; - box.getInputType(index, typeID); - box.setOutputType(index, typeID); - return true; - } - - bool onOutputTypeChanged(Kernel::IBox& box, const size_t index) override - { - CIdentifier typeID = OV_UndefinedIdentifier; - box.getOutputType(index, typeID); - box.setInputType(index, typeID); - return true; - } - - - _IsDerivedFromClass_Final_(Toolkit::TBoxListener<IBoxListener>, OV_UndefinedIdentifier) - }; - - class CBoxAlgorithmChannelRenameDesc final : public IBoxAlgorithmDesc - { - public: - void release() override { } - CString getName() const override { return CString("Channel Rename"); } - CString getAuthorName() const override { return CString("Yann Renard"); } - CString getAuthorCompanyName() const override { return CString("INRIA"); } - CString getShortDescription() const override { return CString("Renames channels of different types of streamed matrices"); } - CString getDetailedDescription() const override { return CString(""); } - CString getCategory() const override { return CString("Signal processing/Channels"); } - CString getVersion() const override { return CString("1.1"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("1.1.0"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_ChannelRename; } - IPluginObject* create() override { return new CBoxAlgorithmChannelRename; } - IBoxListener* createBoxListener() const override { return new CBoxAlgorithmChannelRenameListener; } - void releaseBoxListener(IBoxListener* boxListener) const override { delete boxListener; } - - bool getBoxPrototype(Kernel::IBoxProto& prototype) const override - { - prototype.addInput("Input matrix", OV_TypeId_Signal); - prototype.addOutput("Output matrix", OV_TypeId_Signal); - prototype.addSetting("New channel names", OV_TypeId_String, "Channel 1;Channel 2"); - prototype.addFlag(Kernel::BoxFlag_CanModifyInput); - prototype.addFlag(Kernel::BoxFlag_CanModifyOutput); - - prototype.addInputSupport(OV_TypeId_Signal); - prototype.addInputSupport(OV_TypeId_Spectrum); - prototype.addInputSupport(OV_TypeId_StreamedMatrix); - prototype.addInputSupport(OV_TypeId_TimeFrequency); - prototype.addInputSupport(OV_TypeId_CovarianceMatrix); - - prototype.addOutputSupport(OV_TypeId_Signal); - prototype.addOutputSupport(OV_TypeId_Spectrum); - prototype.addOutputSupport(OV_TypeId_StreamedMatrix); - prototype.addOutputSupport(OV_TypeId_TimeFrequency); - prototype.addOutputSupport(OV_TypeId_CovarianceMatrix); - - return true; - } - - _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_ChannelRenameDesc) - }; - } // namespace SignalProcessing - } // namespace Plugins + prototype.addInput("Input matrix", OV_TypeId_Signal); + prototype.addOutput("Output matrix", OV_TypeId_Signal); + prototype.addSetting("New channel names", OV_TypeId_String, "Channel 1;Channel 2"); + prototype.addFlag(Kernel::BoxFlag_CanModifyInput); + prototype.addFlag(Kernel::BoxFlag_CanModifyOutput); + + prototype.addInputSupport(OV_TypeId_Signal); + prototype.addInputSupport(OV_TypeId_Spectrum); + prototype.addInputSupport(OV_TypeId_StreamedMatrix); + prototype.addInputSupport(OV_TypeId_TimeFrequency); + prototype.addInputSupport(OV_TypeId_CovarianceMatrix); + + prototype.addOutputSupport(OV_TypeId_Signal); + prototype.addOutputSupport(OV_TypeId_Spectrum); + prototype.addOutputSupport(OV_TypeId_StreamedMatrix); + prototype.addOutputSupport(OV_TypeId_TimeFrequency); + prototype.addOutputSupport(OV_TypeId_CovarianceMatrix); + + return true; + } + + _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_ChannelRenameDesc) +}; +} // namespace SignalProcessing +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/signal-processing/src/box-algorithms/basic/ovpCBoxAlgorithmChannelSelector.cpp b/plugins/processing/signal-processing/src/box-algorithms/basic/ovpCBoxAlgorithmChannelSelector.cpp index 2f34e3fa7fa76a8ff20d3a37c7a9e5b61d915e66..3bf6a2426380e0a6201c85bda8cc0a0a5b876d3d 100755 --- a/plugins/processing/signal-processing/src/box-algorithms/basic/ovpCBoxAlgorithmChannelSelector.cpp +++ b/plugins/processing/signal-processing/src/box-algorithms/basic/ovpCBoxAlgorithmChannelSelector.cpp @@ -8,55 +8,54 @@ using namespace /*OpenViBE::*/Toolkit; using namespace /*OpenViBE::Plugins::*/SignalProcessing; -namespace +namespace { +size_t FindChannel(const IMatrix& matrix, const CString& channel, const EMatchMethod matchMethod, const size_t start = 0) { - size_t FindChannel(const IMatrix& matrix, const CString& channel, const EMatchMethod matchMethod, const size_t start = 0) - { - size_t result = std::numeric_limits<size_t>::max(); - const size_t nChannel = matrix.getDimensionSize(0); + size_t result = std::numeric_limits<size_t>::max(); + const size_t nChannel = matrix.getDimensionSize(0); - if (matchMethod == EMatchMethod::Name) + if (matchMethod == EMatchMethod::Name) + { + for (size_t i = start; i < matrix.getDimensionSize(0); ++i) { - for (size_t i = start; i < matrix.getDimensionSize(0); ++i) - { - if (String::isAlmostEqual(matrix.getDimensionLabel(0, i), channel, false)) { result = i; } - } + if (String::isAlmostEqual(matrix.getDimensionLabel(0, i), channel, false)) { result = i; } } - else if (matchMethod == EMatchMethod::Index) + } + else if (matchMethod == EMatchMethod::Index) + { + try { - try - { - const int value = std::stoi(channel.toASCIIString()); + const int value = std::stoi(channel.toASCIIString()); - if (value < 0) - { - size_t idx = size_t(- value - 1); // => makes it 0-indexed ! - if (idx < nChannel) - { - idx = nChannel - idx - 1; // => reverses index - if (start <= idx) { result = idx; } - } - } - if (value > 0) + if (value < 0) + { + size_t idx = size_t(- value - 1); // => makes it 0-indexed ! + if (idx < nChannel) { - const size_t index = size_t(value - 1); // => makes it 0-indexed ! - if (index < nChannel) { if (start <= index) { result = index; } } + idx = nChannel - idx - 1; // => reverses index + if (start <= idx) { result = idx; } } } - catch (const std::exception&) + if (value > 0) { - // catch block intentionnaly left blank + const size_t index = size_t(value - 1); // => makes it 0-indexed ! + if (index < nChannel) { if (start <= index) { result = index; } } } } - else if (matchMethod == EMatchMethod::Smart) + catch (const std::exception&) { - if (result == std::numeric_limits<size_t>::max()) { result = FindChannel(matrix, channel, EMatchMethod::Name, start); } - if (result == std::numeric_limits<size_t>::max()) { result = FindChannel(matrix, channel, EMatchMethod::Index, start); } + // catch block intentionnaly left blank } - - return result; } -} // namespace + else if (matchMethod == EMatchMethod::Smart) + { + if (result == std::numeric_limits<size_t>::max()) { result = FindChannel(matrix, channel, EMatchMethod::Name, start); } + if (result == std::numeric_limits<size_t>::max()) { result = FindChannel(matrix, channel, EMatchMethod::Index, start); } + } + + return result; +} +} // namespace bool CBoxAlgorithmChannelSelector::initialize() { @@ -169,7 +168,6 @@ bool CBoxAlgorithmChannelSelector::process() } else { - // ______________________________________________________________________________________________________________________________________________________ // // Splits the channel list in order to build up the look up table diff --git a/plugins/processing/signal-processing/src/box-algorithms/basic/ovpCBoxAlgorithmChannelSelector.h b/plugins/processing/signal-processing/src/box-algorithms/basic/ovpCBoxAlgorithmChannelSelector.h index 9db5e2c8b92872df56d622ef45d4ccc3800604da..e7b08798c68b1f7e58cf40630d4de968c7422e74 100644 --- a/plugins/processing/signal-processing/src/box-algorithms/basic/ovpCBoxAlgorithmChannelSelector.h +++ b/plugins/processing/signal-processing/src/box-algorithms/basic/ovpCBoxAlgorithmChannelSelector.h @@ -6,164 +6,155 @@ #include <string> -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace SignalProcessing { +class CBoxAlgorithmChannelSelector final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm> { - namespace Plugins +public: + void release() override { delete this; } + bool initialize() override; + bool uninitialize() override; + bool processInput(const size_t index) override; + bool process() override; + + _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_ChannelSelector) + +protected: + + Toolkit::TDecoder<CBoxAlgorithmChannelSelector>* m_decoder = nullptr; + Toolkit::TEncoder<CBoxAlgorithmChannelSelector>* m_encoder = nullptr; + + IMatrix* m_iMatrix = nullptr; + IMatrix* m_oMatrix = nullptr; + + std::vector<size_t> m_vLookup; +}; + +class CBoxAlgorithmChannelSelectorListener final : public Toolkit::TBoxListener<IBoxListener> +{ +public: + bool onOutputTypeChanged(Kernel::IBox& box, const size_t /*index*/) override + { + CIdentifier typeID = OV_UndefinedIdentifier; + box.getOutputType(0, typeID); + if (typeID == OV_TypeId_Signal || typeID == OV_TypeId_Spectrum || typeID == OV_TypeId_StreamedMatrix) + { + box.setInputType(0, typeID); + return true; + } + box.getInputType(0, typeID); + box.setOutputType(0, typeID); + OV_ERROR_KRF("Invalid output type [" << typeID.str() << "] (expected Signal, Spectrum or Streamed Matrix)", Kernel::ErrorType::BadOutput); + } + + bool onInputTypeChanged(Kernel::IBox& box, const size_t /*index*/) override + { + CIdentifier typeID = OV_UndefinedIdentifier; + box.getInputType(0, typeID); + if (typeID == OV_TypeId_Signal || typeID == OV_TypeId_Spectrum || typeID == OV_TypeId_StreamedMatrix) + { + box.setOutputType(0, typeID); + return true; + } + box.getOutputType(0, typeID); + box.setInputType(0, typeID); + + OV_ERROR_KRF("Invalid input type [" << typeID.str() << "] (expected Signal, Spectrum or Streamed Matrix)", Kernel::ErrorType::BadInput); + } + + bool onSettingValueChanged(Kernel::IBox& box, const size_t index) override { - namespace SignalProcessing + //we are only interested in the setting 0 and the type changes (select or reject) + if ((index == 0 || index == 1) && (!m_hasUserSetName)) { - class CBoxAlgorithmChannelSelector final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm> - { - public: - void release() override { delete this; } - bool initialize() override; - bool uninitialize() override; - bool processInput(const size_t index) override; - bool process() override; - - _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_ChannelSelector) - - protected: - - Toolkit::TDecoder<CBoxAlgorithmChannelSelector>* m_decoder = nullptr; - Toolkit::TEncoder<CBoxAlgorithmChannelSelector>* m_encoder = nullptr; - - IMatrix* m_iMatrix = nullptr; - IMatrix* m_oMatrix = nullptr; - - std::vector<size_t> m_vLookup; - }; - - class CBoxAlgorithmChannelSelectorListener final : public Toolkit::TBoxListener<IBoxListener> - { - public: - bool onOutputTypeChanged(Kernel::IBox& box, const size_t /*index*/) override - { - CIdentifier typeID = OV_UndefinedIdentifier; - box.getOutputType(0, typeID); - if (typeID == OV_TypeId_Signal || typeID == OV_TypeId_Spectrum || typeID == OV_TypeId_StreamedMatrix) - { - box.setInputType(0, typeID); - return true; - } - box.getInputType(0, typeID); - box.setOutputType(0, typeID); - OV_ERROR_KRF("Invalid output type [" << typeID.str() << "] (expected Signal, Spectrum or Streamed Matrix)", - Kernel::ErrorType::BadOutput); - } - - bool onInputTypeChanged(Kernel::IBox& box, const size_t /*index*/) override - { - CIdentifier typeID = OV_UndefinedIdentifier; - box.getInputType(0, typeID); - if (typeID == OV_TypeId_Signal || typeID == OV_TypeId_Spectrum - || typeID == OV_TypeId_StreamedMatrix) - { - box.setOutputType(0, typeID); - return true; - } - box.getOutputType(0, typeID); - box.setInputType(0, typeID); - - OV_ERROR_KRF("Invalid input type [" << typeID.str() << "] (expected Signal, Spectrum or Streamed Matrix)", - Kernel::ErrorType::BadInput); - } - - bool onSettingValueChanged(Kernel::IBox& box, const size_t index) override - { - //we are only interested in the setting 0 and the type changes (select or reject) - if ((index == 0 || index == 1) && (!m_hasUserSetName)) - { - CString channels; - box.getSettingValue(0, channels); - - CString method; - CIdentifier enumID = OV_UndefinedIdentifier; - box.getSettingValue(1, method); - box.getSettingType(1, enumID); - - const ESelectionMethod methodID = ESelectionMethod(this->getTypeManager().getEnumerationEntryValueFromName(enumID, method)); - - if (methodID == ESelectionMethod::Reject) { channels = CString("!") + channels; } - box.setName(channels); - } - return true; - } - - bool onNameChanged(Kernel::IBox& box) override - //when user set box name manually - { - if (m_hasUserSetName) - { - const CString rename = box.getName(); - if (rename == CString("Channel Selector")) - {//default name, we switch back to default behaviour - m_hasUserSetName = false; - } - } - else { m_hasUserSetName = true; } - return true; - } - - bool initialize() override - { - m_hasUserSetName = false;//need to initialize this value - return true; - } - - private: - bool m_hasUserSetName = false; - - _IsDerivedFromClass_Final_(Toolkit::TBoxListener<IBoxListener>, OV_UndefinedIdentifier) - }; - - class CBoxAlgorithmChannelSelectorDesc final : public IBoxAlgorithmDesc - { - public: - void release() override { } - CString getName() const override { return CString("Channel Selector"); } - CString getAuthorName() const override { return CString("Yann Renard"); } - CString getAuthorCompanyName() const override { return CString("INRIA"); } - CString getShortDescription() const override { return CString("Select a subset of signal channels"); } - - CString getDetailedDescription() const override - { - return CString("Selection can be based on channel name (case-sensitive) or index starting from 0"); - } - - CString getCategory() const override { return CString("Signal processing/Channels"); } - CString getVersion() const override { return CString("1.0"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_ChannelSelector; } - IPluginObject* create() override { return new CBoxAlgorithmChannelSelector; } - IBoxListener* createBoxListener() const override { return new CBoxAlgorithmChannelSelectorListener; } - void releaseBoxListener(IBoxListener* listener) const override { delete listener; } - - bool getBoxPrototype(Kernel::IBoxProto& prototype) const override - { - prototype.addInput("Input signal", OV_TypeId_Signal); - prototype.addOutput("Output signal", OV_TypeId_Signal); - prototype.addSetting("Channel List", OV_TypeId_String, ":"); - prototype.addSetting("Action", OVP_TypeId_SelectionMethod, "Select"); - prototype.addSetting("Channel Matching Method", OVP_TypeId_MatchMethod, "Smart"); - - prototype.addFlag(Kernel::BoxFlag_CanModifyInput); - prototype.addFlag(Kernel::BoxFlag_CanModifyOutput); - - prototype.addInputSupport(OV_TypeId_Signal); - prototype.addInputSupport(OV_TypeId_Spectrum); - prototype.addInputSupport(OV_TypeId_StreamedMatrix); - - prototype.addOutputSupport(OV_TypeId_Signal); - prototype.addOutputSupport(OV_TypeId_Spectrum); - prototype.addOutputSupport(OV_TypeId_StreamedMatrix); - return true; - } - - _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_ChannelSelectorDesc) - }; - } // namespace SignalProcessing - } // namespace Plugins + CString channels; + box.getSettingValue(0, channels); + + CString method; + CIdentifier enumID = OV_UndefinedIdentifier; + box.getSettingValue(1, method); + box.getSettingType(1, enumID); + + const ESelectionMethod methodID = ESelectionMethod(this->getTypeManager().getEnumerationEntryValueFromName(enumID, method)); + + if (methodID == ESelectionMethod::Reject) { channels = CString("!") + channels; } + box.setName(channels); + } + return true; + } + + bool onNameChanged(Kernel::IBox& box) override + //when user set box name manually + { + if (m_hasUserSetName) + { + const CString rename = box.getName(); + if (rename == CString("Channel Selector")) + {//default name, we switch back to default behaviour + m_hasUserSetName = false; + } + } + else { m_hasUserSetName = true; } + return true; + } + + bool initialize() override + { + m_hasUserSetName = false;//need to initialize this value + return true; + } + +private: + bool m_hasUserSetName = false; + + _IsDerivedFromClass_Final_(Toolkit::TBoxListener<IBoxListener>, OV_UndefinedIdentifier) +}; + +class CBoxAlgorithmChannelSelectorDesc final : public IBoxAlgorithmDesc +{ +public: + void release() override { } + CString getName() const override { return CString("Channel Selector"); } + CString getAuthorName() const override { return CString("Yann Renard"); } + CString getAuthorCompanyName() const override { return CString("INRIA"); } + CString getShortDescription() const override { return CString("Select a subset of signal channels"); } + + CString getDetailedDescription() const override { return CString("Selection can be based on channel name (case-sensitive) or index starting from 0"); } + + CString getCategory() const override { return CString("Signal processing/Channels"); } + CString getVersion() const override { return CString("1.0"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_ChannelSelector; } + IPluginObject* create() override { return new CBoxAlgorithmChannelSelector; } + IBoxListener* createBoxListener() const override { return new CBoxAlgorithmChannelSelectorListener; } + void releaseBoxListener(IBoxListener* listener) const override { delete listener; } + + bool getBoxPrototype(Kernel::IBoxProto& prototype) const override + { + prototype.addInput("Input signal", OV_TypeId_Signal); + prototype.addOutput("Output signal", OV_TypeId_Signal); + prototype.addSetting("Channel List", OV_TypeId_String, ":"); + prototype.addSetting("Action", OVP_TypeId_SelectionMethod, "Select"); + prototype.addSetting("Channel Matching Method", OVP_TypeId_MatchMethod, "Smart"); + + prototype.addFlag(Kernel::BoxFlag_CanModifyInput); + prototype.addFlag(Kernel::BoxFlag_CanModifyOutput); + + prototype.addInputSupport(OV_TypeId_Signal); + prototype.addInputSupport(OV_TypeId_Spectrum); + prototype.addInputSupport(OV_TypeId_StreamedMatrix); + + prototype.addOutputSupport(OV_TypeId_Signal); + prototype.addOutputSupport(OV_TypeId_Spectrum); + prototype.addOutputSupport(OV_TypeId_StreamedMatrix); + return true; + } + + _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_ChannelSelectorDesc) +}; +} // namespace SignalProcessing +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/signal-processing/src/box-algorithms/basic/ovpCBoxAlgorithmCrop.h b/plugins/processing/signal-processing/src/box-algorithms/basic/ovpCBoxAlgorithmCrop.h index d80ecea947770823cc5115e3e4032bda610df75a..4e6e1b78fdee24af20a30e96316bd5e8a63f93f4 100644 --- a/plugins/processing/signal-processing/src/box-algorithms/basic/ovpCBoxAlgorithmCrop.h +++ b/plugins/processing/signal-processing/src/box-algorithms/basic/ovpCBoxAlgorithmCrop.h @@ -4,98 +4,95 @@ #include <openvibe/ov_all.h> #include <toolkit/ovtk_all.h> -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace SignalProcessing { +class CBoxAlgorithmCrop final : virtual public Toolkit::TBoxAlgorithm<IBoxAlgorithm> { - namespace Plugins - { - namespace SignalProcessing - { - class CBoxAlgorithmCrop final : virtual public Toolkit::TBoxAlgorithm<IBoxAlgorithm> - { - public: - void release() override { delete this; } - bool initialize() override; - bool uninitialize() override; - bool processInput(const size_t index) override; - bool process() override; +public: + void release() override { delete this; } + bool initialize() override; + bool uninitialize() override; + bool processInput(const size_t index) override; + bool process() override; - _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_Crop) + _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_Crop) - protected: +protected: - IMatrix* m_matrix = nullptr; - Kernel::IAlgorithmProxy* m_decoder = nullptr; - Kernel::IAlgorithmProxy* m_encoder = nullptr; - double m_minCropValue = 0; - double m_maxCropValue = 0; - ECropMethod m_cropMethod = ECropMethod::MinMax; - }; + IMatrix* m_matrix = nullptr; + Kernel::IAlgorithmProxy* m_decoder = nullptr; + Kernel::IAlgorithmProxy* m_encoder = nullptr; + double m_minCropValue = 0; + double m_maxCropValue = 0; + ECropMethod m_cropMethod = ECropMethod::MinMax; +}; - class CBoxAlgorithmCropListener final : public Toolkit::TBoxListener<IBoxListener> - { - public: - bool onInputTypeChanged(Kernel::IBox& box, const size_t index) override - { - CIdentifier typeID = OV_UndefinedIdentifier; - box.getInputType(index, typeID); - box.setOutputType(index, typeID); - return true; - } +class CBoxAlgorithmCropListener final : public Toolkit::TBoxListener<IBoxListener> +{ +public: + bool onInputTypeChanged(Kernel::IBox& box, const size_t index) override + { + CIdentifier typeID = OV_UndefinedIdentifier; + box.getInputType(index, typeID); + box.setOutputType(index, typeID); + return true; + } - bool onOutputTypeChanged(Kernel::IBox& box, const size_t index) override - { - CIdentifier typeID = OV_UndefinedIdentifier; - box.getOutputType(index, typeID); - box.setInputType(index, typeID); - return true; - } + bool onOutputTypeChanged(Kernel::IBox& box, const size_t index) override + { + CIdentifier typeID = OV_UndefinedIdentifier; + box.getOutputType(index, typeID); + box.setInputType(index, typeID); + return true; + } - _IsDerivedFromClass_Final_(Toolkit::TBoxListener<IBoxListener>, OV_UndefinedIdentifier) - }; + _IsDerivedFromClass_Final_(Toolkit::TBoxListener<IBoxListener>, OV_UndefinedIdentifier) +}; - class CBoxAlgorithmCropDesc final : virtual public IBoxAlgorithmDesc - { - public: - void release() override { } - CString getName() const override { return CString("Crop"); } - CString getAuthorName() const override { return CString("Yann Renard"); } - CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } - CString getShortDescription() const override { return CString("Truncates signal values to a specified range"); } - CString getDetailedDescription() const override { return CString("Minimum or maximum or both limits can be specified"); } - CString getCategory() const override { return CString("Signal processing/Basic"); } - CString getVersion() const override { return CString("1.0"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_Crop; } - IPluginObject* create() override { return new CBoxAlgorithmCrop; } - IBoxListener* createBoxListener() const override { return new CBoxAlgorithmCropListener; } - void releaseBoxListener(IBoxListener* listener) const override { delete listener; } +class CBoxAlgorithmCropDesc final : virtual public IBoxAlgorithmDesc +{ +public: + void release() override { } + CString getName() const override { return CString("Crop"); } + CString getAuthorName() const override { return CString("Yann Renard"); } + CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } + CString getShortDescription() const override { return CString("Truncates signal values to a specified range"); } + CString getDetailedDescription() const override { return CString("Minimum or maximum or both limits can be specified"); } + CString getCategory() const override { return CString("Signal processing/Basic"); } + CString getVersion() const override { return CString("1.0"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_Crop; } + IPluginObject* create() override { return new CBoxAlgorithmCrop; } + IBoxListener* createBoxListener() const override { return new CBoxAlgorithmCropListener; } + void releaseBoxListener(IBoxListener* listener) const override { delete listener; } - bool getBoxPrototype(Kernel::IBoxProto& prototype) const override - { - prototype.addInput("Input matrix", OV_TypeId_StreamedMatrix); - prototype.addOutput("Output matrix", OV_TypeId_StreamedMatrix); - prototype.addSetting("Crop method", OVP_TypeId_CropMethod, "MinMax"); - prototype.addSetting("Min crop value", OV_TypeId_Float, "-1"); - prototype.addSetting("Max crop value", OV_TypeId_Float, "1"); - prototype.addFlag(Kernel::BoxFlag_CanModifyInput); - prototype.addFlag(Kernel::BoxFlag_CanModifyOutput); + bool getBoxPrototype(Kernel::IBoxProto& prototype) const override + { + prototype.addInput("Input matrix", OV_TypeId_StreamedMatrix); + prototype.addOutput("Output matrix", OV_TypeId_StreamedMatrix); + prototype.addSetting("Crop method", OVP_TypeId_CropMethod, "MinMax"); + prototype.addSetting("Min crop value", OV_TypeId_Float, "-1"); + prototype.addSetting("Max crop value", OV_TypeId_Float, "1"); + prototype.addFlag(Kernel::BoxFlag_CanModifyInput); + prototype.addFlag(Kernel::BoxFlag_CanModifyOutput); - prototype.addInputSupport(OV_TypeId_Signal); - prototype.addInputSupport(OV_TypeId_Spectrum); - prototype.addInputSupport(OV_TypeId_StreamedMatrix); - prototype.addInputSupport(OV_TypeId_FeatureVector); + prototype.addInputSupport(OV_TypeId_Signal); + prototype.addInputSupport(OV_TypeId_Spectrum); + prototype.addInputSupport(OV_TypeId_StreamedMatrix); + prototype.addInputSupport(OV_TypeId_FeatureVector); - prototype.addOutputSupport(OV_TypeId_Signal); - prototype.addOutputSupport(OV_TypeId_Spectrum); - prototype.addOutputSupport(OV_TypeId_StreamedMatrix); - prototype.addOutputSupport(OV_TypeId_FeatureVector); - return true; - } + prototype.addOutputSupport(OV_TypeId_Signal); + prototype.addOutputSupport(OV_TypeId_Spectrum); + prototype.addOutputSupport(OV_TypeId_StreamedMatrix); + prototype.addOutputSupport(OV_TypeId_FeatureVector); + return true; + } - _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_CropDesc) - }; - } // namespace SignalProcessing - } // namespace Plugins + _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_CropDesc) +}; +} // namespace SignalProcessing +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/signal-processing/src/box-algorithms/basic/ovpCBoxAlgorithmEpochAverage.h b/plugins/processing/signal-processing/src/box-algorithms/basic/ovpCBoxAlgorithmEpochAverage.h index 19facb9961e5ae3eb2434943b43fd6402ef66039..178c841d6bcd08da156e3ea588103a32794e4292 100644 --- a/plugins/processing/signal-processing/src/box-algorithms/basic/ovpCBoxAlgorithmEpochAverage.h +++ b/plugins/processing/signal-processing/src/box-algorithms/basic/ovpCBoxAlgorithmEpochAverage.h @@ -3,105 +3,102 @@ #include "../../ovp_defines.h" #include <toolkit/ovtk_all.h> -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace SignalProcessing { +class CBoxAlgorithmEpochAverage final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm> { - namespace Plugins +public: + void release() override { delete this; } + bool initialize() override; + bool uninitialize() override; + bool processInput(const size_t index) override; + bool process() override; + + _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_EpochAverage) + +protected: + + Kernel::IAlgorithmProxy* m_decoder = nullptr; + Kernel::IAlgorithmProxy* m_encoder = nullptr; + Kernel::IAlgorithmProxy* m_matrixAverage = nullptr; + + Kernel::TParameterHandler<uint64_t> ip_matrixCount; + Kernel::TParameterHandler<uint64_t> ip_averagingMethod; +}; + +class CBoxAlgorithmEpochAverageListener final : public Toolkit::TBoxListener<IBoxListener> +{ +public: + bool onInputTypeChanged(Kernel::IBox& box, const size_t index) override + { + CIdentifier typeID = OV_UndefinedIdentifier; + box.getInputType(index, typeID); + box.setOutputType(index, typeID); + return true; + } + + bool onOutputTypeChanged(Kernel::IBox& box, const size_t index) override + { + CIdentifier typeID = OV_UndefinedIdentifier; + box.getOutputType(index, typeID); + box.setInputType(index, typeID); + return true; + } + + _IsDerivedFromClass_Final_(Toolkit::TBoxListener<IBoxListener>, OV_UndefinedIdentifier) +}; + +class CBoxAlgorithmEpochAverageDesc final : public IBoxAlgorithmDesc +{ +public: + void release() override { } + CString getName() const override { return CString("Epoch average"); } + CString getAuthorName() const override { return CString("Yann Renard"); } + CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } + + CString getShortDescription() const override { return CString("Averages matrices among time, this can be used to enhance ERPs"); } + + CString getDetailedDescription() const override + { + return CString("This box can average matrices of different types including signal, spectrum or feature vectors"); + } + + CString getCategory() const override { return CString("Signal processing/Averaging"); } + CString getVersion() const override { return CString("1.0"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_EpochAverage; } + IPluginObject* create() override { return new CBoxAlgorithmEpochAverage(); } + IBoxListener* createBoxListener() const override { return new CBoxAlgorithmEpochAverageListener; } + void releaseBoxListener(IBoxListener* listener) const override { delete listener; } + + bool getBoxPrototype(Kernel::IBoxProto& prototype) const override { - namespace SignalProcessing - { - class CBoxAlgorithmEpochAverage final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm> - { - public: - void release() override { delete this; } - bool initialize() override; - bool uninitialize() override; - bool processInput(const size_t index) override; - bool process() override; - - _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_EpochAverage) - - protected: - - Kernel::IAlgorithmProxy* m_decoder = nullptr; - Kernel::IAlgorithmProxy* m_encoder = nullptr; - Kernel::IAlgorithmProxy* m_matrixAverage = nullptr; - - Kernel::TParameterHandler<uint64_t> ip_matrixCount; - Kernel::TParameterHandler<uint64_t> ip_averagingMethod; - }; - - class CBoxAlgorithmEpochAverageListener final : public Toolkit::TBoxListener<IBoxListener> - { - public: - bool onInputTypeChanged(Kernel::IBox& box, const size_t index) override - { - CIdentifier typeID = OV_UndefinedIdentifier; - box.getInputType(index, typeID); - box.setOutputType(index, typeID); - return true; - } - - bool onOutputTypeChanged(Kernel::IBox& box, const size_t index) override - { - CIdentifier typeID = OV_UndefinedIdentifier; - box.getOutputType(index, typeID); - box.setInputType(index, typeID); - return true; - } - - _IsDerivedFromClass_Final_(Toolkit::TBoxListener<IBoxListener>, OV_UndefinedIdentifier) - }; - - class CBoxAlgorithmEpochAverageDesc final : public IBoxAlgorithmDesc - { - public: - void release() override { } - CString getName() const override { return CString("Epoch average"); } - CString getAuthorName() const override { return CString("Yann Renard"); } - CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } - - CString getShortDescription() const override { return CString("Averages matrices among time, this can be used to enhance ERPs"); } - - CString getDetailedDescription() const override - { - return CString("This box can average matrices of different types including signal, spectrum or feature vectors"); - } - - CString getCategory() const override { return CString("Signal processing/Averaging"); } - CString getVersion() const override { return CString("1.0"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_EpochAverage; } - IPluginObject* create() override { return new CBoxAlgorithmEpochAverage(); } - IBoxListener* createBoxListener() const override { return new CBoxAlgorithmEpochAverageListener; } - void releaseBoxListener(IBoxListener* listener) const override { delete listener; } - - bool getBoxPrototype(Kernel::IBoxProto& prototype) const override - { - prototype.addInput("Input epochs", OV_TypeId_StreamedMatrix); - prototype.addOutput("Averaged epochs", OV_TypeId_StreamedMatrix); - prototype.addSetting("Averaging type", OVP_TypeId_EpochAverageMethod, "Moving epoch average"); - prototype.addSetting("Epoch count", OV_TypeId_Integer, "4"); - prototype.addFlag(Kernel::BoxFlag_CanModifyOutput); - prototype.addFlag(Kernel::BoxFlag_CanModifyInput); - - prototype.addInputSupport(OV_TypeId_Signal); - prototype.addInputSupport(OV_TypeId_Spectrum); - prototype.addInputSupport(OV_TypeId_StreamedMatrix); - prototype.addInputSupport(OV_TypeId_FeatureVector); - prototype.addInputSupport(OV_TypeId_TimeFrequency); - - prototype.addOutputSupport(OV_TypeId_Signal); - prototype.addOutputSupport(OV_TypeId_Spectrum); - prototype.addOutputSupport(OV_TypeId_StreamedMatrix); - prototype.addOutputSupport(OV_TypeId_FeatureVector); - prototype.addOutputSupport(OV_TypeId_TimeFrequency); - return true; - } - - _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_EpochAverageDesc) - }; - } // namespace SignalProcessing - } // namespace Plugins + prototype.addInput("Input epochs", OV_TypeId_StreamedMatrix); + prototype.addOutput("Averaged epochs", OV_TypeId_StreamedMatrix); + prototype.addSetting("Averaging type", OVP_TypeId_EpochAverageMethod, "Moving epoch average"); + prototype.addSetting("Epoch count", OV_TypeId_Integer, "4"); + prototype.addFlag(Kernel::BoxFlag_CanModifyOutput); + prototype.addFlag(Kernel::BoxFlag_CanModifyInput); + + prototype.addInputSupport(OV_TypeId_Signal); + prototype.addInputSupport(OV_TypeId_Spectrum); + prototype.addInputSupport(OV_TypeId_StreamedMatrix); + prototype.addInputSupport(OV_TypeId_FeatureVector); + prototype.addInputSupport(OV_TypeId_TimeFrequency); + + prototype.addOutputSupport(OV_TypeId_Signal); + prototype.addOutputSupport(OV_TypeId_Spectrum); + prototype.addOutputSupport(OV_TypeId_StreamedMatrix); + prototype.addOutputSupport(OV_TypeId_FeatureVector); + prototype.addOutputSupport(OV_TypeId_TimeFrequency); + return true; + } + + _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_EpochAverageDesc) +}; +} // namespace SignalProcessing +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/signal-processing/src/box-algorithms/basic/ovpCBoxAlgorithmIdentity.h b/plugins/processing/signal-processing/src/box-algorithms/basic/ovpCBoxAlgorithmIdentity.h index 689aa590fb9a55ffcb721bbab6c6b69412fb5f85..2fd36ea56c9f7c8ec507754e87ae0bc094447b0a 100644 --- a/plugins/processing/signal-processing/src/box-algorithms/basic/ovpCBoxAlgorithmIdentity.h +++ b/plugins/processing/signal-processing/src/box-algorithms/basic/ovpCBoxAlgorithmIdentity.h @@ -3,122 +3,119 @@ #include "../../ovp_defines.h" #include <toolkit/ovtk_all.h> -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace SignalProcessing { +class CBoxAlgorithmIdentity final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm> { - namespace Plugins +public: + void release() override; + bool processInput(const size_t index) override; + bool process() override; + + _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_Identity) +}; + +class CBoxAlgorithmIdentityListener final : public Toolkit::TBoxListener<IBoxListener> +{ +public: + + static bool check(Kernel::IBox& box) + { + size_t i; + for (i = 0; i < box.getInputCount(); ++i) { box.setInputName(i, ("Input stream " + std::to_string(i + 1)).c_str()); } + for (i = 0; i < box.getOutputCount(); ++i) { box.setOutputName(i, ("Output stream " + std::to_string(i + 1)).c_str()); } + return true; + } + + bool onDefaultInitialized(Kernel::IBox& box) override + { + box.setInputType(0, OV_TypeId_Signal); + box.setOutputType(0, OV_TypeId_Signal); + return true; + } + + bool onInputAdded(Kernel::IBox& box, const size_t index) override + { + box.setInputType(index, OV_TypeId_Signal); + box.addOutput("", OV_TypeId_Signal, box.getUnusedInputIdentifier()); + check(box); + return true; + } + + bool onInputRemoved(Kernel::IBox& box, const size_t index) override + { + box.removeOutput(index); + check(box); + return true; + } + + bool onInputTypeChanged(Kernel::IBox& box, const size_t index) override + { + CIdentifier typeID = OV_UndefinedIdentifier; + box.getInputType(index, typeID); + box.setOutputType(index, typeID); + return true; + } + + bool onOutputAdded(Kernel::IBox& box, const size_t index) override + { + box.setOutputType(index, OV_TypeId_Signal); + box.addInput("", OV_TypeId_Signal, box.getUnusedOutputIdentifier()); + check(box); + return true; + } + + bool onOutputRemoved(Kernel::IBox& box, const size_t index) override + { + box.removeInput(index); + check(box); + return true; + } + + bool onOutputTypeChanged(Kernel::IBox& box, const size_t index) override + { + CIdentifier typeID = OV_UndefinedIdentifier; + box.getOutputType(index, typeID); + box.setInputType(index, typeID); + return true; + } + + _IsDerivedFromClass_Final_(Toolkit::TBoxListener<IBoxListener>, OV_UndefinedIdentifier) +}; + +class CBoxAlgorithmIdentityDesc final : public IBoxAlgorithmDesc +{ +public: + void release() override { } + CString getName() const override { return CString("Identity"); } + CString getAuthorName() const override { return CString("Yann Renard"); } + CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } + CString getShortDescription() const override { return CString("Duplicates input to output"); } + CString getDetailedDescription() const override { return CString("This simply duplicates intput on its output"); } + CString getCategory() const override { return CString("Signal processing/Basic"); } + CString getVersion() const override { return CString("1.0"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_Identity; } + IPluginObject* create() override { return new CBoxAlgorithmIdentity(); } + IBoxListener* createBoxListener() const override { return new CBoxAlgorithmIdentityListener; } + void releaseBoxListener(IBoxListener* listener) const override { delete listener; } + + bool getBoxPrototype(Kernel::IBoxProto& prototype) const override { - namespace SignalProcessing - { - class CBoxAlgorithmIdentity final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm> - { - public: - void release() override; - bool processInput(const size_t index) override; - bool process() override; - - _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_Identity) - }; - - class CBoxAlgorithmIdentityListener final : public Toolkit::TBoxListener<IBoxListener> - { - public: - - static bool check(Kernel::IBox& box) - { - size_t i; - for (i = 0; i < box.getInputCount(); ++i) { box.setInputName(i, ("Input stream " + std::to_string(i + 1)).c_str()); } - for (i = 0; i < box.getOutputCount(); ++i) { box.setOutputName(i, ("Output stream " + std::to_string(i + 1)).c_str()); } - return true; - } - - bool onDefaultInitialized(Kernel::IBox& box) override - { - box.setInputType(0, OV_TypeId_Signal); - box.setOutputType(0, OV_TypeId_Signal); - return true; - } - - bool onInputAdded(Kernel::IBox& box, const size_t index) override - { - box.setInputType(index, OV_TypeId_Signal); - box.addOutput("", OV_TypeId_Signal, box.getUnusedInputIdentifier()); - check(box); - return true; - } - - bool onInputRemoved(Kernel::IBox& box, const size_t index) override - { - box.removeOutput(index); - check(box); - return true; - } - - bool onInputTypeChanged(Kernel::IBox& box, const size_t index) override - { - CIdentifier typeID = OV_UndefinedIdentifier; - box.getInputType(index, typeID); - box.setOutputType(index, typeID); - return true; - } - - bool onOutputAdded(Kernel::IBox& box, const size_t index) override - { - box.setOutputType(index, OV_TypeId_Signal); - box.addInput("", OV_TypeId_Signal, box.getUnusedOutputIdentifier()); - check(box); - return true; - } - - bool onOutputRemoved(Kernel::IBox& box, const size_t index) override - { - box.removeInput(index); - check(box); - return true; - } - - bool onOutputTypeChanged(Kernel::IBox& box, const size_t index) override - { - CIdentifier typeID = OV_UndefinedIdentifier; - box.getOutputType(index, typeID); - box.setInputType(index, typeID); - return true; - } - - _IsDerivedFromClass_Final_(Toolkit::TBoxListener<IBoxListener>, OV_UndefinedIdentifier) - }; - - class CBoxAlgorithmIdentityDesc final : public IBoxAlgorithmDesc - { - public: - void release() override { } - CString getName() const override { return CString("Identity"); } - CString getAuthorName() const override { return CString("Yann Renard"); } - CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } - CString getShortDescription() const override { return CString("Duplicates input to output"); } - CString getDetailedDescription() const override { return CString("This simply duplicates intput on its output"); } - CString getCategory() const override { return CString("Signal processing/Basic"); } - CString getVersion() const override { return CString("1.0"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_Identity; } - IPluginObject* create() override { return new CBoxAlgorithmIdentity(); } - IBoxListener* createBoxListener() const override { return new CBoxAlgorithmIdentityListener; } - void releaseBoxListener(IBoxListener* listener) const override { delete listener; } - - bool getBoxPrototype(Kernel::IBoxProto& prototype) const override - { - prototype.addInput("Input stream", OV_TypeId_Signal); - prototype.addOutput("Output stream", OV_TypeId_Signal); - prototype.addFlag(Kernel::BoxFlag_CanAddOutput); - prototype.addFlag(Kernel::BoxFlag_CanModifyOutput); - prototype.addFlag(Kernel::BoxFlag_CanAddInput); - prototype.addFlag(Kernel::BoxFlag_CanModifyInput); - return true; - } - - _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_IdentityDesc) - }; - } // namespace SignalProcessing - } // namespace Plugins + prototype.addInput("Input stream", OV_TypeId_Signal); + prototype.addOutput("Output stream", OV_TypeId_Signal); + prototype.addFlag(Kernel::BoxFlag_CanAddOutput); + prototype.addFlag(Kernel::BoxFlag_CanModifyOutput); + prototype.addFlag(Kernel::BoxFlag_CanAddInput); + prototype.addFlag(Kernel::BoxFlag_CanModifyInput); + return true; + } + + _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_IdentityDesc) +}; +} // namespace SignalProcessing +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/signal-processing/src/box-algorithms/basic/ovpCBoxAlgorithmReferenceChannel.cpp b/plugins/processing/signal-processing/src/box-algorithms/basic/ovpCBoxAlgorithmReferenceChannel.cpp index 02f856008546f4764d019e66f20ee77b49bc27f9..134437a573b3f50e5ba744288cd9852c873608ac 100644 --- a/plugins/processing/signal-processing/src/box-algorithms/basic/ovpCBoxAlgorithmReferenceChannel.cpp +++ b/plugins/processing/signal-processing/src/box-algorithms/basic/ovpCBoxAlgorithmReferenceChannel.cpp @@ -7,42 +7,41 @@ using namespace /*OpenViBE::*/Kernel; using namespace /*OpenViBE::*/Plugins; using namespace SignalProcessing; -namespace +namespace { +size_t FindChannel(const IMatrix& matrix, const CString& channel, const EMatchMethod matchMethod, const size_t start = 0) { - size_t FindChannel(const IMatrix& matrix, const CString& channel, const EMatchMethod matchMethod, const size_t start = 0) - { - size_t res = std::numeric_limits<size_t>::max(); + size_t res = std::numeric_limits<size_t>::max(); - if (matchMethod == EMatchMethod::Name) + if (matchMethod == EMatchMethod::Name) + { + for (size_t i = start; i < matrix.getDimensionSize(0); ++i) { - for (size_t i = start; i < matrix.getDimensionSize(0); ++i) - { - if (Toolkit::String::isAlmostEqual(matrix.getDimensionLabel(0, i), channel, false)) { res = i; } - } + if (Toolkit::String::isAlmostEqual(matrix.getDimensionLabel(0, i), channel, false)) { res = i; } } - else if (matchMethod == EMatchMethod::Index) + } + else if (matchMethod == EMatchMethod::Index) + { + try { - try - { - size_t value = std::stoul(channel.toASCIIString()); - value--; // => makes it 0-indexed ! + size_t value = std::stoul(channel.toASCIIString()); + value--; // => makes it 0-indexed ! - if (start <= size_t(value) && size_t(value) < matrix.getDimensionSize(0)) { res = size_t(value); } - } - catch (const std::exception&) - { - // catch block intentionnaly left blank - } + if (start <= size_t(value) && size_t(value) < matrix.getDimensionSize(0)) { res = size_t(value); } } - else if (matchMethod == EMatchMethod::Smart) + catch (const std::exception&) { - if (res == std::numeric_limits<size_t>::max()) { res = FindChannel(matrix, channel, EMatchMethod::Name, start); } - if (res == std::numeric_limits<size_t>::max()) { res = FindChannel(matrix, channel, EMatchMethod::Index, start); } + // catch block intentionnaly left blank } - - return res; } -} // namespace + else if (matchMethod == EMatchMethod::Smart) + { + if (res == std::numeric_limits<size_t>::max()) { res = FindChannel(matrix, channel, EMatchMethod::Name, start); } + if (res == std::numeric_limits<size_t>::max()) { res = FindChannel(matrix, channel, EMatchMethod::Index, start); } + } + + return res; +} +} // namespace bool CBoxAlgorithmReferenceChannel::initialize() { @@ -78,10 +77,9 @@ bool CBoxAlgorithmReferenceChannel::process() IMatrix& oMatrix = *m_encoder.getInputMatrix(); OV_ERROR_UNLESS_KRF(iMatrix.getDimensionSize(0) >= 2, - "Invalid input matrix with [" << iMatrix.getDimensionSize(0) << "] channels (expected channels >= 2)", - ErrorType::BadInput); + "Invalid input matrix with [" << iMatrix.getDimensionSize(0) << "] channels (expected channels >= 2)", ErrorType::BadInput); - CString channel = FSettingValueAutoCast(*this->getBoxAlgorithmContext(), 0); + CString channel = FSettingValueAutoCast(*this->getBoxAlgorithmContext(), 0); const EMatchMethod method = EMatchMethod(uint64_t(FSettingValueAutoCast(*this->getBoxAlgorithmContext(), 1))); m_referenceChannelIdx = FindChannel(iMatrix, channel, method, 0); diff --git a/plugins/processing/signal-processing/src/box-algorithms/basic/ovpCBoxAlgorithmReferenceChannel.h b/plugins/processing/signal-processing/src/box-algorithms/basic/ovpCBoxAlgorithmReferenceChannel.h index 57bef054b7b4e7b0cc83894acba90eccb5d0bd56..61abccbc1b3aad0f34dadfc6540dc8f6f83fd97d 100644 --- a/plugins/processing/signal-processing/src/box-algorithms/basic/ovpCBoxAlgorithmReferenceChannel.h +++ b/plugins/processing/signal-processing/src/box-algorithms/basic/ovpCBoxAlgorithmReferenceChannel.h @@ -4,62 +4,59 @@ #include <openvibe/ov_all.h> #include <toolkit/ovtk_all.h> -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace SignalProcessing { +class CBoxAlgorithmReferenceChannel final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm> { - namespace Plugins - { - namespace SignalProcessing - { - class CBoxAlgorithmReferenceChannel final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm> - { - public: - void release() override { delete this; } - bool initialize() override; - bool uninitialize() override; - bool processInput(const size_t index) override; - bool process() override; - - _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_ReferenceChannel) - - protected: - - Toolkit::TSignalDecoder<CBoxAlgorithmReferenceChannel> m_decoder; - Toolkit::TSignalEncoder<CBoxAlgorithmReferenceChannel> m_encoder; - size_t m_referenceChannelIdx = 0; - }; +public: + void release() override { delete this; } + bool initialize() override; + bool uninitialize() override; + bool processInput(const size_t index) override; + bool process() override; - class CBoxAlgorithmReferenceChannelDesc final : public IBoxAlgorithmDesc - { - public: - void release() override { } - CString getName() const override { return CString("Reference Channel"); } - CString getAuthorName() const override { return CString("Yann Renard"); } - CString getAuthorCompanyName() const override { return CString("INRIA"); } + _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_ReferenceChannel) - CString getShortDescription() const override { return CString("Subtracts the value of the reference channel from all other channels"); } +protected: - CString getDetailedDescription() const override { return CString("Reference channel must be specified as a parameter for the box"); } + Toolkit::TSignalDecoder<CBoxAlgorithmReferenceChannel> m_decoder; + Toolkit::TSignalEncoder<CBoxAlgorithmReferenceChannel> m_encoder; + size_t m_referenceChannelIdx = 0; +}; - CString getCategory() const override { return CString("Signal processing/Channels"); } - CString getVersion() const override { return CString("1.0"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_ReferenceChannel; } - IPluginObject* create() override { return new CBoxAlgorithmReferenceChannel; } - // virtual IBoxListener* createBoxListener() const { return new CBoxAlgorithmReferenceChannelListener; } - // virtual void releaseBoxListener(IBoxListener* listener) const { delete listener; } - bool getBoxPrototype(Kernel::IBoxProto& prototype) const override - { - prototype.addInput("Input signal", OV_TypeId_Signal); - prototype.addOutput("Output signal", OV_TypeId_Signal); - prototype.addSetting("Channel", OV_TypeId_String, "Ref_Nose"); - prototype.addSetting("Channel Matching Method", OVP_TypeId_MatchMethod, "Smart"); - return true; - } - - _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_ReferenceChannelDesc) - }; - } // namespace SignalProcessing - } // namespace Plugins +class CBoxAlgorithmReferenceChannelDesc final : public IBoxAlgorithmDesc +{ +public: + void release() override { } + CString getName() const override { return CString("Reference Channel"); } + CString getAuthorName() const override { return CString("Yann Renard"); } + CString getAuthorCompanyName() const override { return CString("INRIA"); } + + CString getShortDescription() const override { return CString("Subtracts the value of the reference channel from all other channels"); } + + CString getDetailedDescription() const override { return CString("Reference channel must be specified as a parameter for the box"); } + + CString getCategory() const override { return CString("Signal processing/Channels"); } + CString getVersion() const override { return CString("1.0"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_ReferenceChannel; } + IPluginObject* create() override { return new CBoxAlgorithmReferenceChannel; } + // virtual IBoxListener* createBoxListener() const { return new CBoxAlgorithmReferenceChannelListener; } + // virtual void releaseBoxListener(IBoxListener* listener) const { delete listener; } + bool getBoxPrototype(Kernel::IBoxProto& prototype) const override + { + prototype.addInput("Input signal", OV_TypeId_Signal); + prototype.addOutput("Output signal", OV_TypeId_Signal); + prototype.addSetting("Channel", OV_TypeId_String, "Ref_Nose"); + prototype.addSetting("Channel Matching Method", OVP_TypeId_MatchMethod, "Smart"); + return true; + } + + _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_ReferenceChannelDesc) +}; +} // namespace SignalProcessing +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/signal-processing/src/box-algorithms/basic/ovpCBoxAlgorithmSignalDecimation.h b/plugins/processing/signal-processing/src/box-algorithms/basic/ovpCBoxAlgorithmSignalDecimation.h index b4ca878b4490e28df25ff35c44d1365b0ff6d073..50805645bb6e360a3ef6e985ccf1ced49319ee48 100644 --- a/plugins/processing/signal-processing/src/box-algorithms/basic/ovpCBoxAlgorithmSignalDecimation.h +++ b/plugins/processing/signal-processing/src/box-algorithms/basic/ovpCBoxAlgorithmSignalDecimation.h @@ -4,86 +4,80 @@ #include <openvibe/ov_all.h> #include <toolkit/ovtk_all.h> -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace SignalProcessing { +class CBoxAlgorithmSignalDecimation final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm> { - namespace Plugins - { - namespace SignalProcessing - { - class CBoxAlgorithmSignalDecimation final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm> - { - public: - void release() override { delete this; } - bool initialize() override; - bool uninitialize() override; - bool processInput(const size_t index) override; - bool process() override; +public: + void release() override { delete this; } + bool initialize() override; + bool uninitialize() override; + bool processInput(const size_t index) override; + bool process() override; - _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_SignalDecimation) + _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_SignalDecimation) - protected: +protected: - size_t m_decimationFactor = 0; - size_t m_nChannel = 0; - size_t m_iSampleIdx = 0; - size_t m_iNSamplePerBlock = 0; - size_t m_iSampling = 0; - size_t m_oSampleIdx = 0; - size_t m_oNSamplePerBlock = 0; - size_t m_oSampling = 0; + size_t m_decimationFactor = 0; + size_t m_nChannel = 0; + size_t m_iSampleIdx = 0; + size_t m_iNSamplePerBlock = 0; + size_t m_iSampling = 0; + size_t m_oSampleIdx = 0; + size_t m_oNSamplePerBlock = 0; + size_t m_oSampling = 0; - size_t m_nTotalSample = 0; - uint64_t m_startTimeBase = 0; - uint64_t m_lastStartTime = 0; - uint64_t m_lastEndTime = 0; + size_t m_nTotalSample = 0; + uint64_t m_startTimeBase = 0; + uint64_t m_lastStartTime = 0; + uint64_t m_lastEndTime = 0; - Kernel::IAlgorithmProxy* m_decoder = nullptr; - Kernel::TParameterHandler<const IMemoryBuffer*> ip_buffer; - Kernel::TParameterHandler<IMatrix*> op_pMatrix; - Kernel::TParameterHandler<uint64_t> op_sampling; + Kernel::IAlgorithmProxy* m_decoder = nullptr; + Kernel::TParameterHandler<const IMemoryBuffer*> ip_buffer; + Kernel::TParameterHandler<IMatrix*> op_pMatrix; + Kernel::TParameterHandler<uint64_t> op_sampling; - Kernel::IAlgorithmProxy* m_encoder = nullptr; - Kernel::TParameterHandler<uint64_t> ip_sampling; - Kernel::TParameterHandler<IMatrix*> ip_pMatrix; - Kernel::TParameterHandler<IMemoryBuffer*> op_buffer; - }; + Kernel::IAlgorithmProxy* m_encoder = nullptr; + Kernel::TParameterHandler<uint64_t> ip_sampling; + Kernel::TParameterHandler<IMatrix*> ip_pMatrix; + Kernel::TParameterHandler<IMemoryBuffer*> op_buffer; +}; - class CBoxAlgorithmSignalDecimationDesc final : public IBoxAlgorithmDesc - { - public: - void release() override { } - CString getName() const override { return CString("Signal Decimation"); } - CString getAuthorName() const override { return CString("Yann Renard"); } - CString getAuthorCompanyName() const override { return CString("INRIA"); } +class CBoxAlgorithmSignalDecimationDesc final : public IBoxAlgorithmDesc +{ +public: + void release() override { } + CString getName() const override { return CString("Signal Decimation"); } + CString getAuthorName() const override { return CString("Yann Renard"); } + CString getAuthorCompanyName() const override { return CString("INRIA"); } - CString getShortDescription() const override - { - return CString("Reduces the sampling frequency to a divider of the original sampling frequency"); - } + CString getShortDescription() const override { return CString("Reduces the sampling frequency to a divider of the original sampling frequency"); } - CString getDetailedDescription() const override - { - return CString("No pre filtering applied - Number of samples per block have to be a multiple of the decimation factor"); - } + CString getDetailedDescription() const override + { + return CString("No pre filtering applied - Number of samples per block have to be a multiple of the decimation factor"); + } - CString getCategory() const override { return CString("Signal processing/Temporal Filtering"); } - CString getVersion() const override { return CString("1.0"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_SignalDecimation; } - IPluginObject* create() override { return new CBoxAlgorithmSignalDecimation; } + CString getCategory() const override { return CString("Signal processing/Temporal Filtering"); } + CString getVersion() const override { return CString("1.0"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_SignalDecimation; } + IPluginObject* create() override { return new CBoxAlgorithmSignalDecimation; } - bool getBoxPrototype(Kernel::IBoxProto& prototype) const override - { - prototype.addInput("Input signal", OV_TypeId_Signal); - prototype.addOutput("Output signal", OV_TypeId_Signal); - prototype.addSetting("Decimation factor", OV_TypeId_Integer, "8"); - return true; - } + bool getBoxPrototype(Kernel::IBoxProto& prototype) const override + { + prototype.addInput("Input signal", OV_TypeId_Signal); + prototype.addOutput("Output signal", OV_TypeId_Signal); + prototype.addSetting("Decimation factor", OV_TypeId_Integer, "8"); + return true; + } - _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_SignalDecimationDesc) - }; - } // namespace SignalProcessing - } // namespace Plugins + _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_SignalDecimationDesc) +}; +} // namespace SignalProcessing +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/signal-processing/src/box-algorithms/basic/ovpCBoxAlgorithmZeroCrossingDetector.h b/plugins/processing/signal-processing/src/box-algorithms/basic/ovpCBoxAlgorithmZeroCrossingDetector.h index 794860d4d8d819e2cb033ee2e38264ae0a9247e9..4fd01b211fe5ba9725504e728143d5339a76b8db 100644 --- a/plugins/processing/signal-processing/src/box-algorithms/basic/ovpCBoxAlgorithmZeroCrossingDetector.h +++ b/plugins/processing/signal-processing/src/box-algorithms/basic/ovpCBoxAlgorithmZeroCrossingDetector.h @@ -26,146 +26,143 @@ #include <vector> -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace SignalProcessing { +class CBoxAlgorithmZeroCrossingDetector final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm> { - namespace Plugins +public: + void release() override { delete this; } + bool initialize() override; + bool uninitialize() override; + bool processInput(const size_t index) override; + bool process() override; + + _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_ZeroCrossingDetector) + +protected: + + Toolkit::TGenericDecoder<CBoxAlgorithmZeroCrossingDetector> m_decoder; + Toolkit::TGenericEncoder<CBoxAlgorithmZeroCrossingDetector> m_encoder0; + Toolkit::TStimulationEncoder<CBoxAlgorithmZeroCrossingDetector> m_encoder1; + Toolkit::TStreamedMatrixEncoder<CBoxAlgorithmZeroCrossingDetector> m_encoder2; + + std::vector<double> m_signals; + std::vector<int> m_states; + double m_hysteresis = 0; + uint64_t m_nChunk = 0; + + size_t m_sampling = 0; + double m_windowTimeD = 0; + size_t m_windowTime = 0; + std::vector<std::vector<size_t>> m_chunks; + std::vector<std::vector<size_t>> m_samples; + + uint64_t m_stimId1 = 0; + uint64_t m_stimId2 = 0; +}; + +class CBoxAlgorithmZeroCrossingDetectorListener final : public Toolkit::TBoxListener<IBoxListener> +{ +public: + bool onInputTypeChanged(Kernel::IBox& box, const size_t index) override + { + CIdentifier typeID = OV_UndefinedIdentifier; + box.getInputType(index, typeID); + return onConnectorTypeChanged(box, index, typeID, false); + } + + bool onOutputTypeChanged(Kernel::IBox& box, const size_t index) override + { + CIdentifier typeID = OV_UndefinedIdentifier; + box.getOutputType(index, typeID); + return onConnectorTypeChanged(box, index, typeID, true); + } + + static bool onConnectorTypeChanged(Kernel::IBox& box, const size_t index, const CIdentifier& typeID, const bool outputChanged) { - namespace SignalProcessing + if (index == 0) { - class CBoxAlgorithmZeroCrossingDetector final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm> + if (typeID == OV_TypeId_Signal) { - public: - void release() override { delete this; } - bool initialize() override; - bool uninitialize() override; - bool processInput(const size_t index) override; - bool process() override; - - _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_ZeroCrossingDetector) - - protected: - - Toolkit::TGenericDecoder<CBoxAlgorithmZeroCrossingDetector> m_decoder; - Toolkit::TGenericEncoder<CBoxAlgorithmZeroCrossingDetector> m_encoder0; - Toolkit::TStimulationEncoder<CBoxAlgorithmZeroCrossingDetector> m_encoder1; - Toolkit::TStreamedMatrixEncoder<CBoxAlgorithmZeroCrossingDetector> m_encoder2; - - std::vector<double> m_signals; - std::vector<int> m_states; - double m_hysteresis = 0; - uint64_t m_nChunk = 0; - - size_t m_sampling = 0; - double m_windowTimeD = 0; - size_t m_windowTime = 0; - std::vector<std::vector<size_t>> m_chunks; - std::vector<std::vector<size_t>> m_samples; - - uint64_t m_stimId1 = 0; - uint64_t m_stimId2 = 0; - }; - - class CBoxAlgorithmZeroCrossingDetectorListener final : public Toolkit::TBoxListener<IBoxListener> + box.setInputType(0, OV_TypeId_Signal); + box.setOutputType(0, OV_TypeId_Signal); + } + else if (typeID == OV_TypeId_StreamedMatrix) { - public: - bool onInputTypeChanged(Kernel::IBox& box, const size_t index) override + box.setInputType(0, OV_TypeId_StreamedMatrix); + box.setOutputType(0, OV_TypeId_StreamedMatrix); + } + else + { + // Invalid i/o type identifier + CIdentifier originalTypeID = OV_UndefinedIdentifier; + if (outputChanged) { - CIdentifier typeID = OV_UndefinedIdentifier; - box.getInputType(index, typeID); - return onConnectorTypeChanged(box, index, typeID, false); + // Restores output + box.getInputType(0, originalTypeID); + box.setOutputType(0, originalTypeID); } - - bool onOutputTypeChanged(Kernel::IBox& box, const size_t index) override + else { - CIdentifier typeID = OV_UndefinedIdentifier; - box.getOutputType(index, typeID); - return onConnectorTypeChanged(box, index, typeID, true); + // Restores input + box.getOutputType(0, originalTypeID); + box.setInputType(0, originalTypeID); } + } + } + if (index == 1) { box.setOutputType(1, OV_TypeId_Stimulations); } + if (index == 2) { box.setOutputType(2, OV_TypeId_StreamedMatrix); } - static bool onConnectorTypeChanged(Kernel::IBox& box, const size_t index, const CIdentifier& typeID, const bool outputChanged) - { - if (index == 0) - { - if (typeID == OV_TypeId_Signal) - { - box.setInputType(0, OV_TypeId_Signal); - box.setOutputType(0, OV_TypeId_Signal); - } - else if (typeID == OV_TypeId_StreamedMatrix) - { - box.setInputType(0, OV_TypeId_StreamedMatrix); - box.setOutputType(0, OV_TypeId_StreamedMatrix); - } - else - { - // Invalid i/o type identifier - CIdentifier originalTypeID = OV_UndefinedIdentifier; - if (outputChanged) - { - // Restores output - box.getInputType(0, originalTypeID); - box.setOutputType(0, originalTypeID); - } - else - { - // Restores input - box.getOutputType(0, originalTypeID); - box.setInputType(0, originalTypeID); - } - } - } - if (index == 1) { box.setOutputType(1, OV_TypeId_Stimulations); } - if (index == 2) { box.setOutputType(2, OV_TypeId_StreamedMatrix); } - - return true; - } + return true; + } - _IsDerivedFromClass_Final_(Toolkit::TBoxListener<IBoxListener>, OV_UndefinedIdentifier) - }; + _IsDerivedFromClass_Final_(Toolkit::TBoxListener<IBoxListener>, OV_UndefinedIdentifier) +}; - class CBoxAlgorithmZeroCrossingDetectorDesc final : public IBoxAlgorithmDesc - { - public: - void release() override { } - CString getName() const override { return CString("Zero-Crossing Detector"); } - CString getAuthorName() const override { return CString("Quentin Barthelemy"); } - CString getAuthorCompanyName() const override { return CString("Mensia Technologies SA"); } - CString getShortDescription() const override { return CString("Detects zero-crossings of the signal"); } - - CString getDetailedDescription() const override - { - return CString( - "Detects zero-crossings of the signal for each channel, with 1 for positive zero-crossings (negative-to-positive), -1 for negatives ones (positive-to-negative), 0 otherwise. For all channels, stimulations mark positive and negatives zero-crossings. For each channel, the rythm is computed in events per min."); - } - - CString getCategory() const override { return CString("Signal processing/Temporal Filtering"); } - CString getVersion() const override { return CString("1.0"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_ZeroCrossingDetector; } - IPluginObject* create() override { return new CBoxAlgorithmZeroCrossingDetector; } - IBoxListener* createBoxListener() const override { return new CBoxAlgorithmZeroCrossingDetectorListener; } - void releaseBoxListener(IBoxListener* listener) const override { delete listener; } - - bool getBoxPrototype(Kernel::IBoxProto& prototype) const override - { - prototype.addInput("Input signal", OV_TypeId_Signal); - prototype.addOutput("Zero-crossing signal", OV_TypeId_Signal); - prototype.addOutput("Zero-crossing stimulations", OV_TypeId_Stimulations); - prototype.addOutput("Events rythm (per min)", OV_TypeId_StreamedMatrix); - prototype.addSetting("Hysteresis threshold", OV_TypeId_Float, "0.01"); - prototype.addSetting("Rythm estimation window (in sec)", OV_TypeId_Float, "10"); - prototype.addSetting("Negative-to-positive stimulation", OV_TypeId_Stimulation, "OVTK_StimulationId_ThresholdPassed_Positive"); - prototype.addSetting("Positive-to-negative stimulation", OV_TypeId_Stimulation, "OVTK_StimulationId_ThresholdPassed_Negative"); - prototype.addFlag(Kernel::BoxFlag_CanModifyInput); - prototype.addFlag(Kernel::BoxFlag_CanModifyOutput); - - return true; - } - - _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_ZeroCrossingDetectorDesc) - }; - } // namespace SignalProcessing - } // namespace Plugins +class CBoxAlgorithmZeroCrossingDetectorDesc final : public IBoxAlgorithmDesc +{ +public: + void release() override { } + CString getName() const override { return CString("Zero-Crossing Detector"); } + CString getAuthorName() const override { return CString("Quentin Barthelemy"); } + CString getAuthorCompanyName() const override { return CString("Mensia Technologies SA"); } + CString getShortDescription() const override { return CString("Detects zero-crossings of the signal"); } + + CString getDetailedDescription() const override + { + return CString( + "Detects zero-crossings of the signal for each channel, with 1 for positive zero-crossings (negative-to-positive), -1 for negatives ones (positive-to-negative), 0 otherwise. For all channels, stimulations mark positive and negatives zero-crossings. For each channel, the rythm is computed in events per min."); + } + + CString getCategory() const override { return CString("Signal processing/Temporal Filtering"); } + CString getVersion() const override { return CString("1.0"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_ZeroCrossingDetector; } + IPluginObject* create() override { return new CBoxAlgorithmZeroCrossingDetector; } + IBoxListener* createBoxListener() const override { return new CBoxAlgorithmZeroCrossingDetectorListener; } + void releaseBoxListener(IBoxListener* listener) const override { delete listener; } + + bool getBoxPrototype(Kernel::IBoxProto& prototype) const override + { + prototype.addInput("Input signal", OV_TypeId_Signal); + prototype.addOutput("Zero-crossing signal", OV_TypeId_Signal); + prototype.addOutput("Zero-crossing stimulations", OV_TypeId_Stimulations); + prototype.addOutput("Events rythm (per min)", OV_TypeId_StreamedMatrix); + prototype.addSetting("Hysteresis threshold", OV_TypeId_Float, "0.01"); + prototype.addSetting("Rythm estimation window (in sec)", OV_TypeId_Float, "10"); + prototype.addSetting("Negative-to-positive stimulation", OV_TypeId_Stimulation, "OVTK_StimulationId_ThresholdPassed_Positive"); + prototype.addSetting("Positive-to-negative stimulation", OV_TypeId_Stimulation, "OVTK_StimulationId_ThresholdPassed_Negative"); + prototype.addFlag(Kernel::BoxFlag_CanModifyInput); + prototype.addFlag(Kernel::BoxFlag_CanModifyOutput); + + return true; + } + + _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_ZeroCrossingDetectorDesc) +}; +} // namespace SignalProcessing +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/signal-processing/src/box-algorithms/epoching/ovpCBoxAlgorithmStimulationBasedEpoching.cpp b/plugins/processing/signal-processing/src/box-algorithms/epoching/ovpCBoxAlgorithmStimulationBasedEpoching.cpp index 412c5147fabea9284ee0882daa5235c74fe52165..2c488fcd24a27f8f38ab4e2edd2b21b04c4f04a1 100755 --- a/plugins/processing/signal-processing/src/box-algorithms/epoching/ovpCBoxAlgorithmStimulationBasedEpoching.cpp +++ b/plugins/processing/signal-processing/src/box-algorithms/epoching/ovpCBoxAlgorithmStimulationBasedEpoching.cpp @@ -250,6 +250,6 @@ bool CBoxAlgorithmStimulationBasedEpoching::process() return true; } -} // namespace SignalProcessing -} // namespace Plugins -} // namespace OpenViBE +} // namespace SignalProcessing +} // namespace Plugins +} // namespace OpenViBE diff --git a/plugins/processing/signal-processing/src/box-algorithms/epoching/ovpCBoxAlgorithmStimulationBasedEpoching.h b/plugins/processing/signal-processing/src/box-algorithms/epoching/ovpCBoxAlgorithmStimulationBasedEpoching.h index fbe9a24ad60ad6b47cfa49a947347e2404c7fb8e..1cc7dd1358768dd8d4089685509c1250901b2c2b 100755 --- a/plugins/processing/signal-processing/src/box-algorithms/epoching/ovpCBoxAlgorithmStimulationBasedEpoching.h +++ b/plugins/processing/signal-processing/src/box-algorithms/epoching/ovpCBoxAlgorithmStimulationBasedEpoching.h @@ -105,6 +105,6 @@ public: _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_StimulationBasedEpochingDesc) }; -} // namespace SignalProcessing -} // namespace Plugins -} // namespace OpenViBE +} // namespace SignalProcessing +} // namespace Plugins +} // namespace OpenViBE diff --git a/plugins/processing/signal-processing/src/box-algorithms/epoching/ovpCBoxAlgorithmTimeBasedEpoching.h b/plugins/processing/signal-processing/src/box-algorithms/epoching/ovpCBoxAlgorithmTimeBasedEpoching.h index 63d13fb511bed8db71ca2b213b8467cbb34409a7..16c15958f857b8bd855d9e7c3d5e58184b41d493 100755 --- a/plugins/processing/signal-processing/src/box-algorithms/epoching/ovpCBoxAlgorithmTimeBasedEpoching.h +++ b/plugins/processing/signal-processing/src/box-algorithms/epoching/ovpCBoxAlgorithmTimeBasedEpoching.h @@ -3,75 +3,69 @@ #include "../../ovp_defines.h" #include <toolkit/ovtk_all.h> -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace SignalProcessing { +class CBoxAlgorithmTimeBasedEpoching final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm> { - namespace Plugins - { - namespace SignalProcessing - { - class CBoxAlgorithmTimeBasedEpoching final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm> - { - public: - void release() override { delete this; } - bool initialize() override; - bool uninitialize() override; - bool processInput(const size_t index) override; - bool process() override; +public: + void release() override { delete this; } + bool initialize() override; + bool uninitialize() override; + bool processInput(const size_t index) override; + bool process() override; - _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_TimeBasedEpoching) + _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_TimeBasedEpoching) - private: +private: - Toolkit::TSignalDecoder<CBoxAlgorithmTimeBasedEpoching> m_decoder; - Toolkit::TSignalEncoder<CBoxAlgorithmTimeBasedEpoching> m_encoder; + Toolkit::TSignalDecoder<CBoxAlgorithmTimeBasedEpoching> m_decoder; + Toolkit::TSignalEncoder<CBoxAlgorithmTimeBasedEpoching> m_encoder; - double m_duration = 0; - double m_interval = 0; + double m_duration = 0; + double m_interval = 0; - size_t m_sampling = 0; - size_t m_oNSample = 0; - size_t m_oNSampleBetweenEpoch = 0; - size_t m_oSampleIdx = 0; - size_t m_oChunkIdx = 0; - uint64_t m_lastInputEndTime = 0; - uint64_t m_referenceTime = 0; - }; + size_t m_sampling = 0; + size_t m_oNSample = 0; + size_t m_oNSampleBetweenEpoch = 0; + size_t m_oSampleIdx = 0; + size_t m_oChunkIdx = 0; + uint64_t m_lastInputEndTime = 0; + uint64_t m_referenceTime = 0; +}; - class CBoxAlgorithmTimeBasedEpochingDesc final : public IBoxAlgorithmDesc - { - public: - void release() override { } - CString getName() const override { return CString("Time based epoching"); } - CString getAuthorName() const override { return CString("Quentin Barthelemy"); } - CString getAuthorCompanyName() const override { return CString("Mensia Technologies SA"); } +class CBoxAlgorithmTimeBasedEpochingDesc final : public IBoxAlgorithmDesc +{ +public: + void release() override { } + CString getName() const override { return CString("Time based epoching"); } + CString getAuthorName() const override { return CString("Quentin Barthelemy"); } + CString getAuthorCompanyName() const override { return CString("Mensia Technologies SA"); } - CString getShortDescription() const override - { - return CString("Generates signal 'slices' or 'blocks' having a specified duration and interval"); - } + CString getShortDescription() const override { return CString("Generates signal 'slices' or 'blocks' having a specified duration and interval"); } - CString getDetailedDescription() const override { return CString("Interval can be used to control the overlap of epochs"); } - CString getCategory() const override { return CString("Signal processing/Epoching"); } - CString getVersion() const override { return CString("2.0"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } - CString getStockItemName() const override { return CString("gtk-cut"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_TimeBasedEpoching; } - IPluginObject* create() override { return new CBoxAlgorithmTimeBasedEpoching(); } + CString getDetailedDescription() const override { return CString("Interval can be used to control the overlap of epochs"); } + CString getCategory() const override { return CString("Signal processing/Epoching"); } + CString getVersion() const override { return CString("2.0"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } + CString getStockItemName() const override { return CString("gtk-cut"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_TimeBasedEpoching; } + IPluginObject* create() override { return new CBoxAlgorithmTimeBasedEpoching(); } - bool getBoxPrototype(Kernel::IBoxProto& prototype) const override - { - prototype.addInput("Input signal", OV_TypeId_Signal); - prototype.addOutput("Epoched signal", OV_TypeId_Signal); - prototype.addSetting("Epoch duration (in sec)", OV_TypeId_Float, "1"); - prototype.addSetting("Epoch intervals (in sec)", OV_TypeId_Float, "0.5"); + bool getBoxPrototype(Kernel::IBoxProto& prototype) const override + { + prototype.addInput("Input signal", OV_TypeId_Signal); + prototype.addOutput("Epoched signal", OV_TypeId_Signal); + prototype.addSetting("Epoch duration (in sec)", OV_TypeId_Float, "1"); + prototype.addSetting("Epoch intervals (in sec)", OV_TypeId_Float, "0.5"); - return true; - } + return true; + } - _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_TimeBasedEpochingDesc) - }; - } // namespace SignalProcessing - } // namespace Plugins + _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_TimeBasedEpochingDesc) +}; +} // namespace SignalProcessing +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/signal-processing/src/box-algorithms/filters/ovpCBoxAlgorithmCommonAverageReference.h b/plugins/processing/signal-processing/src/box-algorithms/filters/ovpCBoxAlgorithmCommonAverageReference.h index dfdd4dbcc775006fc69313485b338636bc178d6f..abf15cb6d918755e9bcafb2bae499dd7c3f55561 100644 --- a/plugins/processing/signal-processing/src/box-algorithms/filters/ovpCBoxAlgorithmCommonAverageReference.h +++ b/plugins/processing/signal-processing/src/box-algorithms/filters/ovpCBoxAlgorithmCommonAverageReference.h @@ -4,70 +4,67 @@ #include <openvibe/ov_all.h> #include <toolkit/ovtk_all.h> -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace SignalProcessing { +class CBoxAlgorithmCommonAverageReference final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm> { - namespace Plugins - { - namespace SignalProcessing - { - class CBoxAlgorithmCommonAverageReference final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm> - { - public: - void release() override { delete this; } - bool initialize() override; - bool uninitialize() override; - bool processInput(const size_t index) override; - bool process() override; +public: + void release() override { delete this; } + bool initialize() override; + bool uninitialize() override; + bool processInput(const size_t index) override; + bool process() override; - _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_CommonAverageReference) + _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_CommonAverageReference) - protected: +protected: - Kernel::IAlgorithmProxy* m_decoder = nullptr; - Kernel::TParameterHandler<const IMemoryBuffer*> ip_buffer; - Kernel::TParameterHandler<IMatrix*> op_matrix; - Kernel::TParameterHandler<uint64_t> op_sampling; + Kernel::IAlgorithmProxy* m_decoder = nullptr; + Kernel::TParameterHandler<const IMemoryBuffer*> ip_buffer; + Kernel::TParameterHandler<IMatrix*> op_matrix; + Kernel::TParameterHandler<uint64_t> op_sampling; - Kernel::IAlgorithmProxy* m_encoder = nullptr; - Kernel::TParameterHandler<IMatrix*> ip_matrix; - Kernel::TParameterHandler<uint64_t> ip_sampling; - Kernel::TParameterHandler<IMemoryBuffer*> op_buffer; + Kernel::IAlgorithmProxy* m_encoder = nullptr; + Kernel::TParameterHandler<IMatrix*> ip_matrix; + Kernel::TParameterHandler<uint64_t> ip_sampling; + Kernel::TParameterHandler<IMemoryBuffer*> op_buffer; - CMatrix m_oMatrix; - }; + CMatrix m_oMatrix; +}; - class CBoxAlgorithmCommonAverageReferenceDesc final : public IBoxAlgorithmDesc - { - public: - void release() override { } - CString getName() const override { return CString("Common Average Reference"); } - CString getAuthorName() const override { return CString("Yann Renard"); } - CString getAuthorCompanyName() const override { return CString("INRIA"); } - CString getShortDescription() const override { return CString("Re-reference the signal to common average reference"); } +class CBoxAlgorithmCommonAverageReferenceDesc final : public IBoxAlgorithmDesc +{ +public: + void release() override { } + CString getName() const override { return CString("Common Average Reference"); } + CString getAuthorName() const override { return CString("Yann Renard"); } + CString getAuthorCompanyName() const override { return CString("INRIA"); } + CString getShortDescription() const override { return CString("Re-reference the signal to common average reference"); } - CString getDetailedDescription() const override - { - return CString( - "Re-referencing the signal to common average reference consists in subtracting from each sample the average value of the samples of all electrodes at this time"); - } + CString getDetailedDescription() const override + { + return CString( + "Re-referencing the signal to common average reference consists in subtracting from each sample the average value of the samples of all electrodes at this time"); + } - CString getCategory() const override { return CString("Signal processing/Spatial Filtering"); } - CString getVersion() const override { return CString("1.0"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_CommonAverageReference; } - IPluginObject* create() override { return new CBoxAlgorithmCommonAverageReference; } + CString getCategory() const override { return CString("Signal processing/Spatial Filtering"); } + CString getVersion() const override { return CString("1.0"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_CommonAverageReference; } + IPluginObject* create() override { return new CBoxAlgorithmCommonAverageReference; } - bool getBoxPrototype(Kernel::IBoxProto& prototype) const override - { - prototype.addInput("Input signal", OV_TypeId_Signal); - prototype.addOutput("Output signal", OV_TypeId_Signal); - return true; - } + bool getBoxPrototype(Kernel::IBoxProto& prototype) const override + { + prototype.addInput("Input signal", OV_TypeId_Signal); + prototype.addOutput("Output signal", OV_TypeId_Signal); + return true; + } - _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_CommonAverageReferenceDesc) - }; - } // namespace SignalProcessing - } // namespace Plugins + _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_CommonAverageReferenceDesc) +}; +} // namespace SignalProcessing +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/signal-processing/src/box-algorithms/filters/ovpCBoxAlgorithmRegularizedCSPTrainer.cpp b/plugins/processing/signal-processing/src/box-algorithms/filters/ovpCBoxAlgorithmRegularizedCSPTrainer.cpp index 298c96a1e65791761f1bdc5f230c6e156d646d65..903ed04b6c01030c8a7d3113a9f0161a1838afb3 100755 --- a/plugins/processing/signal-processing/src/box-algorithms/filters/ovpCBoxAlgorithmRegularizedCSPTrainer.cpp +++ b/plugins/processing/signal-processing/src/box-algorithms/filters/ovpCBoxAlgorithmRegularizedCSPTrainer.cpp @@ -227,7 +227,7 @@ bool CBoxAlgorithmRegularizedCSPTrainer::computeCSP(const vector<MatrixXd>& cov, for (int i = 0; i < eigenValues[c].size(); ++i) { - sortedEigenValues[c][i] = eigenValues[c][indexes[i].second]; + sortedEigenValues[c][i] = eigenValues[c][indexes[i].second]; //@todo @FIXME This fonction work sometimes randomly sortedEigenVectors[c].col(i) = eigenVectors[c].col(indexes[i].second); } @@ -335,7 +335,8 @@ bool CBoxAlgorithmRegularizedCSPTrainer::process() for (size_t c = 0; c < m_nClasses; ++c) { - selectedVectorsMapper.block(c * m_filtersPerClass, 0, m_filtersPerClass, nChannels) = sortedVectors[c].block(0, 0, nChannels, m_filtersPerClass).transpose(); + selectedVectorsMapper.block(c * m_filtersPerClass, 0, m_filtersPerClass, nChannels) = sortedVectors[c].block(0, 0, nChannels, m_filtersPerClass). + transpose(); this->getLogManager() << LogLevel_Info << "The " << m_filtersPerClass << " filter(s) for cond " << c + 1 << " cover " << 100.0 * sortedValues[c].head(m_filtersPerClass).sum() / sortedValues[c].sum() << "% of corresp. eigenvalues\n"; diff --git a/plugins/processing/signal-processing/src/box-algorithms/filters/ovpCBoxAlgorithmRegularizedCSPTrainer.h b/plugins/processing/signal-processing/src/box-algorithms/filters/ovpCBoxAlgorithmRegularizedCSPTrainer.h index e380bb82f5f5a0d84d5cae2d748324892244660c..96eeb54efa3af9be94f840799bc0210330e6c9e1 100755 --- a/plugins/processing/signal-processing/src/box-algorithms/filters/ovpCBoxAlgorithmRegularizedCSPTrainer.h +++ b/plugins/processing/signal-processing/src/box-algorithms/filters/ovpCBoxAlgorithmRegularizedCSPTrainer.h @@ -12,115 +12,112 @@ typedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> MatrixXdRowMajor; -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace SignalProcessing { +class CBoxAlgorithmRegularizedCSPTrainer final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm> { - namespace Plugins +public: + void release() override { delete this; } + bool initialize() override; + bool uninitialize() override; + bool processInput(const size_t index) override; + bool process() override; + +protected: + + bool updateCov(size_t index); + bool outclassCovAverage(size_t skipIndex, const std::vector<Eigen::MatrixXd>& cov, Eigen::MatrixXd& covAvg); + bool computeCSP(const std::vector<Eigen::MatrixXd>& cov, std::vector<Eigen::MatrixXd>& sortedEigenVectors, + std::vector<Eigen::VectorXd>& sortedEigenValues); + + Toolkit::TStimulationDecoder<CBoxAlgorithmRegularizedCSPTrainer> m_stimDecoder; + std::vector<Toolkit::TSignalDecoder<CBoxAlgorithmRegularizedCSPTrainer>> m_signalDecoders; + Toolkit::TStimulationEncoder<CBoxAlgorithmRegularizedCSPTrainer> m_encoder; + + uint64_t m_stimID = 0; + CString m_configFilename; + size_t m_filtersPerClass = 0; + bool m_saveAsBoxConf = false; + bool m_hasBeenInitialized = false; + + double m_tikhonov = 0.0; + + struct SIncrementalCovarianceProxy + { + Kernel::IAlgorithmProxy* cov = nullptr; + size_t nBuffers = 0; + size_t nSamples = 0; + }; + + std::vector<SIncrementalCovarianceProxy> m_covProxies; + + size_t m_nClasses = 0; + + _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_RegularizedCSPTrainer) +}; + +class CBoxAlgorithmRegularizedCSPTrainerListener final : public Toolkit::TBoxListener<IBoxListener> +{ +public: + bool onInputAdded(Kernel::IBox& box, const size_t index) override { - namespace SignalProcessing - { - class CBoxAlgorithmRegularizedCSPTrainer final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm> - { - public: - void release() override { delete this; } - bool initialize() override; - bool uninitialize() override; - bool processInput(const size_t index) override; - bool process() override; - - protected: - - bool updateCov(size_t index); - bool outclassCovAverage(size_t skipIndex, const std::vector<Eigen::MatrixXd>& cov, Eigen::MatrixXd& covAvg); - bool computeCSP(const std::vector<Eigen::MatrixXd>& cov, std::vector<Eigen::MatrixXd>& sortedEigenVectors, - std::vector<Eigen::VectorXd>& sortedEigenValues); - - Toolkit::TStimulationDecoder<CBoxAlgorithmRegularizedCSPTrainer> m_stimDecoder; - std::vector<Toolkit::TSignalDecoder<CBoxAlgorithmRegularizedCSPTrainer>> m_signalDecoders; - Toolkit::TStimulationEncoder<CBoxAlgorithmRegularizedCSPTrainer> m_encoder; - - uint64_t m_stimID = 0; - CString m_configFilename; - size_t m_filtersPerClass = 0; - bool m_saveAsBoxConf = false; - bool m_hasBeenInitialized = false; - - double m_tikhonov = 0.0; - - struct SIncrementalCovarianceProxy - { - Kernel::IAlgorithmProxy* cov = nullptr; - size_t nBuffers = 0; - size_t nSamples = 0; - }; - - std::vector<SIncrementalCovarianceProxy> m_covProxies; - - size_t m_nClasses = 0; - - _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_RegularizedCSPTrainer) - }; - - class CBoxAlgorithmRegularizedCSPTrainerListener final : public Toolkit::TBoxListener<IBoxListener> - { - public: - bool onInputAdded(Kernel::IBox& box, const size_t index) override - { - box.setInputName(index, ("Signal condition " + std::to_string(index)).c_str()); - return true; - } - - _IsDerivedFromClass_Final_(Toolkit::TBoxListener<IBoxListener>, OV_UndefinedIdentifier) - }; - - class CBoxAlgorithmRegularizedCSPTrainerDesc final : public IBoxAlgorithmDesc - { - public: - void release() override { } - CString getName() const override { return CString("Regularized CSP Trainer"); } - CString getAuthorName() const override { return CString("Jussi T. Lindgren"); } - CString getAuthorCompanyName() const override { return CString("Inria"); } - CString getShortDescription() const override { return CString("Computes Common Spatial Pattern filters with regularization"); } - CString getDetailedDescription() const override { return CString(""); } - CString getCategory() const override { return CString("Signal processing/Filtering"); } - CString getVersion() const override { return CString("1.0"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_RegularizedCSPTrainer; } - IPluginObject* create() override { return new CBoxAlgorithmRegularizedCSPTrainer; } - IBoxListener* createBoxListener() const override { return new CBoxAlgorithmRegularizedCSPTrainerListener; } - - bool getBoxPrototype(Kernel::IBoxProto& prototype) const override - { - prototype.addInput("Stimulations", OV_TypeId_Stimulations); - prototype.addInput("Signal condition 1", OV_TypeId_Signal); - prototype.addInput("Signal condition 2", OV_TypeId_Signal); - - prototype.addInputSupport(OV_TypeId_Signal); - prototype.addInputSupport(OV_TypeId_StreamedMatrix); - - prototype.addSetting("Train Trigger", OV_TypeId_Stimulation, "OVTK_GDF_End_Of_Session"); - prototype.addSetting("Spatial filter configuration", OV_TypeId_Filename, ""); - prototype.addSetting("Filters per condition", OV_TypeId_Integer, "2"); - prototype.addSetting("Save filters as box config", OV_TypeId_Boolean, "false"); - - // Params of the cov algorithm; would be better to poll the params from the algorithm, however this is not straightforward to do - prototype.addSetting("Covariance update", OVP_TypeId_OnlineCovariance_UpdateMethod, "Chunk average"); - prototype.addSetting("Trace normalization", OV_TypeId_Boolean, "false"); - prototype.addSetting("Shrinkage coefficient", OV_TypeId_Float, "0.0"); - prototype.addSetting("Tikhonov coefficient", OV_TypeId_Float, "0.0"); - - prototype.addOutput("Train-completed Flag", OV_TypeId_Stimulations); - - prototype.addFlag(Kernel::BoxFlag_CanAddInput); - - return true; - } - - _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_RegularizedCSPTrainerDesc) - }; - } // namespace SignalProcessing - } // namespace Plugins + box.setInputName(index, ("Signal condition " + std::to_string(index)).c_str()); + return true; + } + + _IsDerivedFromClass_Final_(Toolkit::TBoxListener<IBoxListener>, OV_UndefinedIdentifier) +}; + +class CBoxAlgorithmRegularizedCSPTrainerDesc final : public IBoxAlgorithmDesc +{ +public: + void release() override { } + CString getName() const override { return CString("Regularized CSP Trainer"); } + CString getAuthorName() const override { return CString("Jussi T. Lindgren"); } + CString getAuthorCompanyName() const override { return CString("Inria"); } + CString getShortDescription() const override { return CString("Computes Common Spatial Pattern filters with regularization"); } + CString getDetailedDescription() const override { return CString(""); } + CString getCategory() const override { return CString("Signal processing/Filtering"); } + CString getVersion() const override { return CString("1.0"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_RegularizedCSPTrainer; } + IPluginObject* create() override { return new CBoxAlgorithmRegularizedCSPTrainer; } + IBoxListener* createBoxListener() const override { return new CBoxAlgorithmRegularizedCSPTrainerListener; } + + bool getBoxPrototype(Kernel::IBoxProto& prototype) const override + { + prototype.addInput("Stimulations", OV_TypeId_Stimulations); + prototype.addInput("Signal condition 1", OV_TypeId_Signal); + prototype.addInput("Signal condition 2", OV_TypeId_Signal); + + prototype.addInputSupport(OV_TypeId_Signal); + prototype.addInputSupport(OV_TypeId_StreamedMatrix); + + prototype.addSetting("Train Trigger", OV_TypeId_Stimulation, "OVTK_GDF_End_Of_Session"); + prototype.addSetting("Spatial filter configuration", OV_TypeId_Filename, ""); + prototype.addSetting("Filters per condition", OV_TypeId_Integer, "2"); + prototype.addSetting("Save filters as box config", OV_TypeId_Boolean, "false"); + + // Params of the cov algorithm; would be better to poll the params from the algorithm, however this is not straightforward to do + prototype.addSetting("Covariance update", OVP_TypeId_OnlineCovariance_UpdateMethod, "Chunk average"); + prototype.addSetting("Trace normalization", OV_TypeId_Boolean, "false"); + prototype.addSetting("Shrinkage coefficient", OV_TypeId_Float, "0.0"); + prototype.addSetting("Tikhonov coefficient", OV_TypeId_Float, "0.0"); + + prototype.addOutput("Train-completed Flag", OV_TypeId_Stimulations); + + prototype.addFlag(Kernel::BoxFlag_CanAddInput); + + return true; + } + + _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_RegularizedCSPTrainerDesc) +}; +} // namespace SignalProcessing +} // namespace Plugins } // namespace OpenViBE #endif // TARGET_HAS_ThirdPartyEIGEN diff --git a/plugins/processing/signal-processing/src/box-algorithms/filters/ovpCBoxAlgorithmSpatialFilter.cpp b/plugins/processing/signal-processing/src/box-algorithms/filters/ovpCBoxAlgorithmSpatialFilter.cpp index c7784f96b745b9612e1ddddcec0d1c1cfc4bc768..8d169ceb29fa01eb3c7394a730939e6f60e8f6bc 100755 --- a/plugins/processing/signal-processing/src/box-algorithms/filters/ovpCBoxAlgorithmSpatialFilter.cpp +++ b/plugins/processing/signal-processing/src/box-algorithms/filters/ovpCBoxAlgorithmSpatialFilter.cpp @@ -70,8 +70,7 @@ size_t CBoxAlgorithmSpatialFilter::loadCoefs(const CString& coefs, const char c1 const size_t row = idx / nRows + 1; const size_t col = idx % nRows + 1; - OV_ERROR_KRZ("Failed to parse coefficient number [" << idx << "] at matrix positions [" << row << "," << col << "]", - ErrorType::BadProcessing); + OV_ERROR_KRZ("Failed to parse coefficient number [" << idx << "] at matrix positions [" << row << "," << col << "]", ErrorType::BadProcessing); } idx++; @@ -101,8 +100,7 @@ bool CBoxAlgorithmSpatialFilter::initialize() m_encoder = new Toolkit::TSignalEncoder<CBoxAlgorithmSpatialFilter>(*this, 0); static_cast<Toolkit::TSignalEncoder<CBoxAlgorithmSpatialFilter>*>(m_encoder)->getInputSamplingRate().setReferenceTarget( - static_cast<Toolkit::TSignalDecoder<CBoxAlgorithmSpatialFilter>*>( - m_decoder)->getOutputSamplingRate()); + static_cast<Toolkit::TSignalDecoder<CBoxAlgorithmSpatialFilter>*>(m_decoder)->getOutputSamplingRate()); } else if (id == OV_TypeId_Spectrum) { @@ -110,11 +108,9 @@ bool CBoxAlgorithmSpatialFilter::initialize() m_encoder = new Toolkit::TSpectrumEncoder<CBoxAlgorithmSpatialFilter>(*this, 0); static_cast<Toolkit::TSpectrumEncoder<CBoxAlgorithmSpatialFilter>*>(m_encoder)->getInputFrequencyAbscissa().setReferenceTarget( - static_cast<Toolkit::TSpectrumDecoder<CBoxAlgorithmSpatialFilter>*>( - m_decoder)->getOutputFrequencyAbscissa()); + static_cast<Toolkit::TSpectrumDecoder<CBoxAlgorithmSpatialFilter>*>(m_decoder)->getOutputFrequencyAbscissa()); static_cast<Toolkit::TSpectrumEncoder<CBoxAlgorithmSpatialFilter>*>(m_encoder)->getInputSamplingRate().setReferenceTarget( - static_cast<Toolkit::TSpectrumDecoder<CBoxAlgorithmSpatialFilter>*>( - m_decoder)->getOutputSamplingRate()); + static_cast<Toolkit::TSpectrumDecoder<CBoxAlgorithmSpatialFilter>*>(m_decoder)->getOutputSamplingRate()); } else { OV_ERROR_KRF("Invalid input stream type [" << id.str() << "]", ErrorType::BadInput); } @@ -123,8 +119,7 @@ bool CBoxAlgorithmSpatialFilter::initialize() if (filterFile != CString("")) { OV_ERROR_UNLESS_KRF(Toolkit::Matrix::loadFromTextFile(m_filterBank, filterFile), - "Failed to load filter parameters from file at location [" << filterFile << "]", - ErrorType::BadFileRead); + "Failed to load filter parameters from file at location [" << filterFile << "]", ErrorType::BadFileRead); OV_ERROR_UNLESS_KRF(m_filterBank.getDimensionCount() == 2, "Invalid filter matrix in file " << filterFile << ": found [" << m_filterBank.getDimensionCount() << diff --git a/plugins/processing/signal-processing/src/box-algorithms/filters/ovpCBoxAlgorithmSpatialFilter.h b/plugins/processing/signal-processing/src/box-algorithms/filters/ovpCBoxAlgorithmSpatialFilter.h index 2fed04aa7a8a2298a81236658943d1700fc6fcf5..5606584290613a94ed2041c7eed904c4b8cbc4d7 100644 --- a/plugins/processing/signal-processing/src/box-algorithms/filters/ovpCBoxAlgorithmSpatialFilter.h +++ b/plugins/processing/signal-processing/src/box-algorithms/filters/ovpCBoxAlgorithmSpatialFilter.h @@ -4,110 +4,104 @@ #include <openvibe/ov_all.h> #include <toolkit/ovtk_all.h> -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace SignalProcessing { +class CBoxAlgorithmSpatialFilter final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm> { - namespace Plugins +public: + void release() override { delete this; } + bool initialize() override; + bool uninitialize() override; + bool processInput(const size_t index) override; + bool process() override; + + _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_SpatialFilter) + +protected: + + Toolkit::TDecoder<CBoxAlgorithmSpatialFilter>* m_decoder = nullptr; + Toolkit::TEncoder<CBoxAlgorithmSpatialFilter>* m_encoder = nullptr; + + CMatrix m_filterBank; + +private: + // Loads the m_vCoefficient vector (representing a matrix) from the given string. c1 and c2 are separator characters between floats. + size_t loadCoefs(const CString& coefs, char c1, char c2, size_t nRows, size_t nCols); +}; + +class CBoxAlgorithmSpatialFilterListener final : public Toolkit::TBoxListener<IBoxListener> +{ +public: + bool onInputTypeChanged(Kernel::IBox& box, const size_t /*index*/) override + { + CIdentifier typeID = OV_UndefinedIdentifier; + box.getInputType(0, typeID); + box.setOutputType(0, typeID); + return true; + } + + bool onOutputTypeChanged(Kernel::IBox& box, const size_t /*index*/) override + { + CIdentifier typeID = OV_UndefinedIdentifier; + box.getOutputType(0, typeID); + box.setInputType(0, typeID); + return true; + } + + _IsDerivedFromClass_Final_(Toolkit::TBoxListener<IBoxListener>, OV_UndefinedIdentifier) +}; + +class CBoxAlgorithmSpatialFilterDesc final : public IBoxAlgorithmDesc +{ +public: + void release() override { } + CString getName() const override { return CString("Spatial Filter"); } + CString getAuthorName() const override { return CString("Yann Renard, Jussi T. Lindgren"); } + CString getAuthorCompanyName() const override { return CString("Inria"); } + + CString getShortDescription() const override { return CString("Maps M inputs to N outputs by multiplying the each input vector with a matrix"); } + + CString getDetailedDescription() const override + { + return CString( + "The applied coefficient matrix must be specified as a box parameter. The filter processes each sample independently of the past samples."); + } + + CString getCategory() const override { return CString("Signal processing/Filtering"); } + CString getVersion() const override { return CString("1.1"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.1.0"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_SpatialFilter; } + IPluginObject* create() override { return new CBoxAlgorithmSpatialFilter; } + IBoxListener* createBoxListener() const override { return new CBoxAlgorithmSpatialFilterListener; } + void releaseBoxListener(IBoxListener* listener) const override { delete listener; } + + bool getBoxPrototype(Kernel::IBoxProto& prototype) const override { - namespace SignalProcessing - { - class CBoxAlgorithmSpatialFilter final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm> - { - public: - void release() override { delete this; } - bool initialize() override; - bool uninitialize() override; - bool processInput(const size_t index) override; - bool process() override; - - _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_SpatialFilter) - - protected: - - Toolkit::TDecoder<CBoxAlgorithmSpatialFilter>* m_decoder = nullptr; - Toolkit::TEncoder<CBoxAlgorithmSpatialFilter>* m_encoder = nullptr; - - CMatrix m_filterBank; - - private: - // Loads the m_vCoefficient vector (representing a matrix) from the given string. c1 and c2 are separator characters between floats. - size_t loadCoefs(const CString& coefs, char c1, char c2, size_t nRows, size_t nCols); - }; - - class CBoxAlgorithmSpatialFilterListener final : public Toolkit::TBoxListener<IBoxListener> - { - public: - bool onInputTypeChanged(Kernel::IBox& box, const size_t /*index*/) override - { - CIdentifier typeID = OV_UndefinedIdentifier; - box.getInputType(0, typeID); - box.setOutputType(0, typeID); - return true; - } - - bool onOutputTypeChanged(Kernel::IBox& box, const size_t /*index*/) override - { - CIdentifier typeID = OV_UndefinedIdentifier; - box.getOutputType(0, typeID); - box.setInputType(0, typeID); - return true; - } - - _IsDerivedFromClass_Final_(Toolkit::TBoxListener<IBoxListener>, OV_UndefinedIdentifier) - }; - - class CBoxAlgorithmSpatialFilterDesc final : public IBoxAlgorithmDesc - { - public: - void release() override { } - CString getName() const override { return CString("Spatial Filter"); } - CString getAuthorName() const override { return CString("Yann Renard, Jussi T. Lindgren"); } - CString getAuthorCompanyName() const override { return CString("Inria"); } - - CString getShortDescription() const override - { - return CString("Maps M inputs to N outputs by multiplying the each input vector with a matrix"); - } - - CString getDetailedDescription() const override - { - return CString( - "The applied coefficient matrix must be specified as a box parameter. The filter processes each sample independently of the past samples."); - } - - CString getCategory() const override { return CString("Signal processing/Filtering"); } - CString getVersion() const override { return CString("1.1"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.1.0"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_SpatialFilter; } - IPluginObject* create() override { return new CBoxAlgorithmSpatialFilter; } - IBoxListener* createBoxListener() const override { return new CBoxAlgorithmSpatialFilterListener; } - void releaseBoxListener(IBoxListener* listener) const override { delete listener; } - - bool getBoxPrototype(Kernel::IBoxProto& prototype) const override - { - prototype.addInput("Input Signal", OV_TypeId_Signal); - prototype.addOutput("Output Signal", OV_TypeId_Signal); - prototype.addSetting("Spatial Filter Coefficients", OV_TypeId_String, "1;0;0;0;0;1;0;0;0;0;1;0;0;0;0;1"); - prototype.addSetting("Number of Output Channels", OV_TypeId_Integer, "4"); - prototype.addSetting("Number of Input Channels", OV_TypeId_Integer, "4"); - prototype.addSetting("Filter matrix file", OV_TypeId_Filename, ""); - prototype.addFlag(Kernel::BoxFlag_CanModifyInput); - prototype.addFlag(Kernel::BoxFlag_CanModifyOutput); - - prototype.addInputSupport(OV_TypeId_StreamedMatrix); - prototype.addInputSupport(OV_TypeId_Spectrum); - prototype.addInputSupport(OV_TypeId_Signal); - - prototype.addOutputSupport(OV_TypeId_StreamedMatrix); - prototype.addOutputSupport(OV_TypeId_Spectrum); - prototype.addOutputSupport(OV_TypeId_Signal); - - return true; - } - - _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_SpatialFilterDesc) - }; - } // namespace SignalProcessing - } // namespace Plugins + prototype.addInput("Input Signal", OV_TypeId_Signal); + prototype.addOutput("Output Signal", OV_TypeId_Signal); + prototype.addSetting("Spatial Filter Coefficients", OV_TypeId_String, "1;0;0;0;0;1;0;0;0;0;1;0;0;0;0;1"); + prototype.addSetting("Number of Output Channels", OV_TypeId_Integer, "4"); + prototype.addSetting("Number of Input Channels", OV_TypeId_Integer, "4"); + prototype.addSetting("Filter matrix file", OV_TypeId_Filename, ""); + prototype.addFlag(Kernel::BoxFlag_CanModifyInput); + prototype.addFlag(Kernel::BoxFlag_CanModifyOutput); + + prototype.addInputSupport(OV_TypeId_StreamedMatrix); + prototype.addInputSupport(OV_TypeId_Spectrum); + prototype.addInputSupport(OV_TypeId_Signal); + + prototype.addOutputSupport(OV_TypeId_StreamedMatrix); + prototype.addOutputSupport(OV_TypeId_Spectrum); + prototype.addOutputSupport(OV_TypeId_Signal); + + return true; + } + + _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_SpatialFilterDesc) +}; +} // namespace SignalProcessing +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/signal-processing/src/box-algorithms/filters/ovpCBoxAlgorithmTemporalFilter.cpp b/plugins/processing/signal-processing/src/box-algorithms/filters/ovpCBoxAlgorithmTemporalFilter.cpp index 88d3130aebe99228921f43ad5ddb29d003ef9a26..afbeb8a47efa43de011c29f5380238c28d3f5b45 100644 --- a/plugins/processing/signal-processing/src/box-algorithms/filters/ovpCBoxAlgorithmTemporalFilter.cpp +++ b/plugins/processing/signal-processing/src/box-algorithms/filters/ovpCBoxAlgorithmTemporalFilter.cpp @@ -5,97 +5,96 @@ using namespace /*OpenViBE::*/Kernel; using namespace /*OpenViBE::*/Plugins; using namespace SignalProcessing; -namespace +namespace { +typedef Dsp::SmoothedFilterDesign<Dsp::Butterworth::Design::BandPass<32>, 1, Dsp::DirectFormII> CButterworthBandPass; +typedef Dsp::SmoothedFilterDesign<Dsp::Butterworth::Design::BandStop<32>, 1, Dsp::DirectFormII> CButterworthBandStop; +typedef Dsp::SmoothedFilterDesign<Dsp::Butterworth::Design::HighPass<32>, 1, Dsp::DirectFormII> CButterworthHighPass; +typedef Dsp::SmoothedFilterDesign<Dsp::Butterworth::Design::LowPass<32>, 1, Dsp::DirectFormII> CButterworthLowPass; + +std::shared_ptr<Dsp::Filter> createButterworthFilter(const EFilterType type, const size_t nSmooth) { - typedef Dsp::SmoothedFilterDesign<Dsp::Butterworth::Design::BandPass<32>, 1, Dsp::DirectFormII> CButterworthBandPass; - typedef Dsp::SmoothedFilterDesign<Dsp::Butterworth::Design::BandStop<32>, 1, Dsp::DirectFormII> CButterworthBandStop; - typedef Dsp::SmoothedFilterDesign<Dsp::Butterworth::Design::HighPass<32>, 1, Dsp::DirectFormII> CButterworthHighPass; - typedef Dsp::SmoothedFilterDesign<Dsp::Butterworth::Design::LowPass<32>, 1, Dsp::DirectFormII> CButterworthLowPass; + switch (type) + { + case EFilterType::BandPass: return std::static_pointer_cast<Dsp::Filter>(std::make_shared<CButterworthBandPass>(int(nSmooth))); + case EFilterType::BandStop: return std::static_pointer_cast<Dsp::Filter>(std::make_shared<CButterworthBandStop>(int(nSmooth))); + case EFilterType::HighPass: return std::static_pointer_cast<Dsp::Filter>(std::make_shared<CButterworthHighPass>(int(nSmooth))); + case EFilterType::LowPass: return std::static_pointer_cast<Dsp::Filter>(std::make_shared<CButterworthLowPass>(int(nSmooth))); + default: return nullptr; + } +} - std::shared_ptr<Dsp::Filter> createButterworthFilter(const EFilterType type, const size_t nSmooth) +bool getButterworthParameters(Dsp::Params& parameters, const size_t frequency, const EFilterType type, const size_t order, + const double lowCut, const double highCut, const double /*ripple*/) +{ + parameters[0] = double(frequency); + parameters[1] = double(order); + switch (type) { - switch (type) + case EFilterType::BandPass: + case EFilterType::BandStop: + parameters[2] = .5 * (highCut + lowCut); + parameters[3] = 1. * (highCut - lowCut); + break; + case EFilterType::HighPass: + parameters[2] = lowCut; + break; + case EFilterType::LowPass: + parameters[2] = highCut; + break; + default: + return false; + } + return true; +} + +/* +typedef Dsp::SmoothedFilterDesign<Dsp::ChebyshevI::Design::BandPass<4>, 1, Dsp::DirectFormII> CChebyshevBandPass; +typedef Dsp::SmoothedFilterDesign<Dsp::ChebyshevI::Design::BandStop<4>, 1, Dsp::DirectFormII> CChebyshevBandStop; +typedef Dsp::SmoothedFilterDesign<Dsp::ChebyshevI::Design::HighPass<4>, 1, Dsp::DirectFormII> CChebyshevHighPass; +typedef Dsp::SmoothedFilterDesign<Dsp::ChebyshevI::Design::LowPass<4>, 1, Dsp::DirectFormII> CChebyshevLowPass; + std::shared_ptr < Dsp::Filter > createChebishevFilter(size_t type, size_t nSmooth) + { + switch(type) { - case EFilterType::BandPass: return std::static_pointer_cast<Dsp::Filter>(std::make_shared<CButterworthBandPass>(int(nSmooth))); - case EFilterType::BandStop: return std::static_pointer_cast<Dsp::Filter>(std::make_shared<CButterworthBandStop>(int(nSmooth))); - case EFilterType::HighPass: return std::static_pointer_cast<Dsp::Filter>(std::make_shared<CButterworthHighPass>(int(nSmooth))); - case EFilterType::LowPass: return std::static_pointer_cast<Dsp::Filter>(std::make_shared<CButterworthLowPass>(int(nSmooth))); - default: return nullptr; + case EFilterType::BandPass: return std::shared_ptr < Dsp::Filter >(new CChebyshevBandPass(int(nSmooth))); + case EFilterType::BandStop: return std::shared_ptr < Dsp::Filter >(new CChebyshevBandStop(int(nSmooth))); + case EFilterType::HighPass: return std::shared_ptr < Dsp::Filter >(new CChebyshevHighPass(int(nSmooth))); + case EFilterType::LowPass: return std::shared_ptr < Dsp::Filter >(new CChebyshevLowPass(int(nSmooth))); + default: + break; } + return NULL; } - bool getButterworthParameters(Dsp::Params& parameters, const size_t frequency, const EFilterType type, const size_t order, - const double lowCut, const double highCut, const double /*ripple*/) + bool getChebishevParameters(Dsp::Params& params, size_t type, size_t sampling, size_t order, double lowCut, double highCut, double ripple) { - parameters[0] = double(frequency); - parameters[1] = double(order); - switch (type) + params[0]=int(sampling); + params[1]=int(order); + switch(type) { case EFilterType::BandPass: case EFilterType::BandStop: - parameters[2] = .5 * (highCut + lowCut); - parameters[3] = 1. * (highCut - lowCut); + params[2]=.5*(highCut+lowCut); + params[3]=1.*(highCut-lowCut); + params[4]=ripple; break; case EFilterType::HighPass: - parameters[2] = lowCut; + params[2]=highCut; // TO CHECK : lowCut ? + params[3]=ripple; break; case EFilterType::LowPass: - parameters[2] = highCut; + params[2]=highCut; + params[3]=lowCut; // TO CHECK : ripple ? break; default: return false; } return true; } + */ - /* - typedef Dsp::SmoothedFilterDesign<Dsp::ChebyshevI::Design::BandPass<4>, 1, Dsp::DirectFormII> CChebyshevBandPass; - typedef Dsp::SmoothedFilterDesign<Dsp::ChebyshevI::Design::BandStop<4>, 1, Dsp::DirectFormII> CChebyshevBandStop; - typedef Dsp::SmoothedFilterDesign<Dsp::ChebyshevI::Design::HighPass<4>, 1, Dsp::DirectFormII> CChebyshevHighPass; - typedef Dsp::SmoothedFilterDesign<Dsp::ChebyshevI::Design::LowPass<4>, 1, Dsp::DirectFormII> CChebyshevLowPass; - std::shared_ptr < Dsp::Filter > createChebishevFilter(size_t type, size_t nSmooth) - { - switch(type) - { - case EFilterType::BandPass: return std::shared_ptr < Dsp::Filter >(new CChebyshevBandPass(int(nSmooth))); - case EFilterType::BandStop: return std::shared_ptr < Dsp::Filter >(new CChebyshevBandStop(int(nSmooth))); - case EFilterType::HighPass: return std::shared_ptr < Dsp::Filter >(new CChebyshevHighPass(int(nSmooth))); - case EFilterType::LowPass: return std::shared_ptr < Dsp::Filter >(new CChebyshevLowPass(int(nSmooth))); - default: - break; - } - return NULL; - } - - bool getChebishevParameters(Dsp::Params& params, size_t type, size_t sampling, size_t order, double lowCut, double highCut, double ripple) - { - params[0]=int(sampling); - params[1]=int(order); - switch(type) - { - case EFilterType::BandPass: - case EFilterType::BandStop: - params[2]=.5*(highCut+lowCut); - params[3]=1.*(highCut-lowCut); - params[4]=ripple; - break; - case EFilterType::HighPass: - params[2]=highCut; // TO CHECK : lowCut ? - params[3]=ripple; - break; - case EFilterType::LowPass: - params[2]=highCut; - params[3]=lowCut; // TO CHECK : ripple ? - break; - default: - return false; - } - return true; - } - */ - - typedef bool (*fpGetParameters_t)(Dsp::Params& params, size_t sampling, EFilterType type, size_t order, double lowCut, double highCut, double ripple); - typedef std::shared_ptr<Dsp::Filter> (*fpCreateFilter_t)(EFilterType type, size_t nSmooth); +typedef bool (*fpGetParameters_t)(Dsp::Params& params, size_t sampling, EFilterType type, size_t order, double lowCut, double highCut, double ripple); +typedef std::shared_ptr<Dsp::Filter> (*fpCreateFilter_t)(EFilterType type, size_t nSmooth); } // namespace bool CBoxAlgorithmTemporalFilter::initialize() @@ -202,8 +201,14 @@ bool CBoxAlgorithmTemporalFilter::process() } else { OV_ERROR_KRF("Invalid filter method", ErrorType::BadSetting); } - if (m_type == EFilterType::HighPass) { this->getLogManager() << LogLevel_Debug << "Low cut frequency of the High pass filter : " << m_lowCut << "Hz\n"; } - if (m_type == EFilterType::LowPass) { this->getLogManager() << LogLevel_Debug << "High cut frequency of the Low pass filter : " << m_highCut << "Hz\n"; } + if (m_type == EFilterType::HighPass) + { + this->getLogManager() << LogLevel_Debug << "Low cut frequency of the High pass filter : " << m_lowCut << "Hz\n"; + } + if (m_type == EFilterType::LowPass) + { + this->getLogManager() << LogLevel_Debug << "High cut frequency of the Low pass filter : " << m_highCut << "Hz\n"; + } const size_t frequency = m_decoder.getOutputSamplingRate(); const size_t nSmooth = 100 * frequency; diff --git a/plugins/processing/signal-processing/src/box-algorithms/filters/ovpCBoxAlgorithmTemporalFilter.h b/plugins/processing/signal-processing/src/box-algorithms/filters/ovpCBoxAlgorithmTemporalFilter.h index 324b354224bf4ba55b5f6a7815b64a60e7b81d2e..6957cfd19a60675767fffced358e60d43859707b 100644 --- a/plugins/processing/signal-processing/src/box-algorithms/filters/ovpCBoxAlgorithmTemporalFilter.h +++ b/plugins/processing/signal-processing/src/box-algorithms/filters/ovpCBoxAlgorithmTemporalFilter.h @@ -7,82 +7,79 @@ #include <memory> #include <dsp-filters/Dsp.h> -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace SignalProcessing { +class CBoxAlgorithmTemporalFilter final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm> { - namespace Plugins +public: + void release() override { delete this; } + bool initialize() override; + bool uninitialize() override; + bool processInput(const size_t index) override; + bool process() override; + + _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_TemporalFilter) + +protected: + + Toolkit::TSignalDecoder<CBoxAlgorithmTemporalFilter> m_decoder; + Toolkit::TSignalEncoder<CBoxAlgorithmTemporalFilter> m_encoder; + + + EFilterMethod m_method = EFilterMethod::Butterworth; + EFilterType m_type = EFilterType::BandPass; + size_t m_order = 0; + + double m_lowCut = 0; + double m_highCut = 0; + double m_ripple = 0; // for Chebyshev + + std::vector<std::shared_ptr<Dsp::Filter>> m_filters; + //std::vector < std::shared_ptr < Dsp::Filter > > m_filters; + + std::vector<double> m_firstSamples; +}; + +class CBoxAlgorithmTemporalFilterDesc final : public IBoxAlgorithmDesc +{ +public: + void release() override { } + CString getName() const override { return CString("Temporal Filter"); } + CString getAuthorName() const override { return CString("Yann Renard & Laurent Bonnet"); } + CString getAuthorCompanyName() const override { return CString("Mensia Technologies SA"); } + + CString getShortDescription() const override { return CString("Temporal filtering based on various one-way IIR filter designs"); } + + CString getDetailedDescription() const override + { + return CString("Applies a temporal filter, based on various one-way IIR filter designs, to the input stream."); + } + + CString getCategory() const override { return CString("Signal processing/Temporal Filtering"); } + CString getVersion() const override { return CString("1.1"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_TemporalFilter; } + IPluginObject* create() override { return new CBoxAlgorithmTemporalFilter; } + + bool getBoxPrototype(Kernel::IBoxProto& prototype) const override { - namespace SignalProcessing - { - class CBoxAlgorithmTemporalFilter final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm> - { - public: - void release() override { delete this; } - bool initialize() override; - bool uninitialize() override; - bool processInput(const size_t index) override; - bool process() override; - - _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_TemporalFilter) - - protected: - - Toolkit::TSignalDecoder<CBoxAlgorithmTemporalFilter> m_decoder; - Toolkit::TSignalEncoder<CBoxAlgorithmTemporalFilter> m_encoder; - - - EFilterMethod m_method = EFilterMethod::Butterworth; - EFilterType m_type = EFilterType::BandPass; - size_t m_order = 0; - - double m_lowCut = 0; - double m_highCut = 0; - double m_ripple = 0; // for Chebyshev - - std::vector<std::shared_ptr<Dsp::Filter>> m_filters; - //std::vector < std::shared_ptr < Dsp::Filter > > m_filters; - - std::vector<double> m_firstSamples; - }; - - class CBoxAlgorithmTemporalFilterDesc final : public IBoxAlgorithmDesc - { - public: - void release() override { } - CString getName() const override { return CString("Temporal Filter"); } - CString getAuthorName() const override { return CString("Yann Renard & Laurent Bonnet"); } - CString getAuthorCompanyName() const override { return CString("Mensia Technologies SA"); } - - CString getShortDescription() const override { return CString("Temporal filtering based on various one-way IIR filter designs"); } - - CString getDetailedDescription() const override - { - return CString("Applies a temporal filter, based on various one-way IIR filter designs, to the input stream."); - } - - CString getCategory() const override { return CString("Signal processing/Temporal Filtering"); } - CString getVersion() const override { return CString("1.1"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_TemporalFilter; } - IPluginObject* create() override { return new CBoxAlgorithmTemporalFilter; } - - bool getBoxPrototype(Kernel::IBoxProto& prototype) const override - { - prototype.addInput("Input signal", OV_TypeId_Signal); - prototype.addOutput("Output signal", OV_TypeId_Signal); - prototype.addSetting("Filter Method", OVP_TypeId_FilterMethod, "Butterworth"); - prototype.addSetting("Filter Type", OVP_TypeId_FilterType, "Band Pass"); - prototype.addSetting("Filter Order", OV_TypeId_Integer, "4"); - prototype.addSetting("Low Cut-off Frequency (Hz)", OV_TypeId_Float, "1"); - prototype.addSetting("High Cut-off Frequency (Hz)", OV_TypeId_Float, "40"); - prototype.addSetting("Band Pass Ripple (dB)", OV_TypeId_Float, "0.5"); - - return true; - } - - _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_TemporalFilterDesc) - }; - } // namespace SignalProcessing - } // namespace Plugins + prototype.addInput("Input signal", OV_TypeId_Signal); + prototype.addOutput("Output signal", OV_TypeId_Signal); + prototype.addSetting("Filter Method", OVP_TypeId_FilterMethod, "Butterworth"); + prototype.addSetting("Filter Type", OVP_TypeId_FilterType, "Band Pass"); + prototype.addSetting("Filter Order", OV_TypeId_Integer, "4"); + prototype.addSetting("Low Cut-off Frequency (Hz)", OV_TypeId_Float, "1"); + prototype.addSetting("High Cut-off Frequency (Hz)", OV_TypeId_Float, "40"); + prototype.addSetting("Band Pass Ripple (dB)", OV_TypeId_Float, "0.5"); + + return true; + } + + _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_TemporalFilterDesc) +}; +} // namespace SignalProcessing +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/signal-processing/src/box-algorithms/ovpCBoxAlgorithmSignalAverage.h b/plugins/processing/signal-processing/src/box-algorithms/ovpCBoxAlgorithmSignalAverage.h index 7ffd752a25f4fa69dead415afc7ef0569c543e45..46c683b5f7533ef844b68998f273ae53e6b6f211 100644 --- a/plugins/processing/signal-processing/src/box-algorithms/ovpCBoxAlgorithmSignalAverage.h +++ b/plugins/processing/signal-processing/src/box-algorithms/ovpCBoxAlgorithmSignalAverage.h @@ -5,65 +5,62 @@ #include <string> -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace SignalProcessing { +/** +*/ +class CBoxAlgorithmSignalAverage final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm> { - namespace Plugins - { - namespace SignalProcessing - { - /** - */ - class CBoxAlgorithmSignalAverage final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm> - { - public: +public: + + CBoxAlgorithmSignalAverage() {} + void release() override {} + bool initialize() override; + bool uninitialize() override; + bool processInput(const size_t index) override; + bool process() override; - CBoxAlgorithmSignalAverage() {} - void release() override {} - bool initialize() override; - bool uninitialize() override; - bool processInput(const size_t index) override; - bool process() override; + _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_SignalAverage) - _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_SignalAverage) +protected: + void computeAverage(); - protected: - void computeAverage(); - - // Needed to read the input and write the output - Toolkit::TSignalDecoder<CBoxAlgorithmSignalAverage> m_decoder; - Toolkit::TSignalEncoder<CBoxAlgorithmSignalAverage> m_encoder; - }; + // Needed to read the input and write the output + Toolkit::TSignalDecoder<CBoxAlgorithmSignalAverage> m_decoder; + Toolkit::TSignalEncoder<CBoxAlgorithmSignalAverage> m_encoder; +}; - /** - * Description of the channel selection plugin - */ - class CSignalAverageDesc final : public IBoxAlgorithmDesc - { - public: - void release() override { } - CString getName() const override { return CString("Signal average"); } - CString getAuthorName() const override { return CString("Bruno Renier"); } - CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } - CString getShortDescription() const override { return CString("Computes the average of each input buffer."); } - CString getDetailedDescription() const override { return CString(""); } - CString getCategory() const override { return CString("Signal processing/Averaging"); } - CString getVersion() const override { return CString("0.5"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_SignalAverage; } - IPluginObject* create() override { return new CBoxAlgorithmSignalAverage(); } +/** +* Description of the channel selection plugin +*/ +class CSignalAverageDesc final : public IBoxAlgorithmDesc +{ +public: + void release() override { } + CString getName() const override { return CString("Signal average"); } + CString getAuthorName() const override { return CString("Bruno Renier"); } + CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } + CString getShortDescription() const override { return CString("Computes the average of each input buffer."); } + CString getDetailedDescription() const override { return CString(""); } + CString getCategory() const override { return CString("Signal processing/Averaging"); } + CString getVersion() const override { return CString("0.5"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_SignalAverage; } + IPluginObject* create() override { return new CBoxAlgorithmSignalAverage(); } - bool getBoxPrototype(Kernel::IBoxProto& prototype) const override - { - prototype.addInput("Input signal", OV_TypeId_Signal); - prototype.addOutput("Filtered signal", OV_TypeId_Signal); + bool getBoxPrototype(Kernel::IBoxProto& prototype) const override + { + prototype.addInput("Input signal", OV_TypeId_Signal); + prototype.addOutput("Filtered signal", OV_TypeId_Signal); - return true; - } + return true; + } - _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_SignalAverageDesc) - }; - } // namespace SignalProcessing - } // namespace Plugins + _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_SignalAverageDesc) +}; +} // namespace SignalProcessing +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/signal-processing/src/box-algorithms/ovpCBoxAlgorithmSimpleDSP.cpp b/plugins/processing/signal-processing/src/box-algorithms/ovpCBoxAlgorithmSimpleDSP.cpp index 9ddd18ae9b36669703a82b6dcb54f746fef8bf34..8e4ff14ea062918dcc1b6fffc397f935629c1434 100755 --- a/plugins/processing/signal-processing/src/box-algorithms/ovpCBoxAlgorithmSimpleDSP.cpp +++ b/plugins/processing/signal-processing/src/box-algorithms/ovpCBoxAlgorithmSimpleDSP.cpp @@ -17,16 +17,14 @@ bool CBoxAlgorithmSimpleDSP::initialize() m_variables = new double*[boxContext.getInputCount()]; - OV_ERROR_UNLESS_KRF(m_variables, "Failed to allocate arrays of floats for [" << boxContext.getInputCount() << "] inputs", - ErrorType::BadAlloc); + OV_ERROR_UNLESS_KRF(m_variables, "Failed to allocate arrays of floats for [" << boxContext.getInputCount() << "] inputs", ErrorType::BadAlloc); const CString equation = FSettingValueAutoCast(*this->getBoxAlgorithmContext(), 0); m_parser = new CEquationParser(*this, m_variables, boxContext.getInputCount()); OV_ERROR_UNLESS_KRF(m_parser, "Failed to create equation parser", ErrorType::BadAlloc); - OV_ERROR_UNLESS_KRF(m_parser->compileEquation(equation.toASCIIString()), "Failed to compile equation [" << equation << "]", - ErrorType::Internal); + OV_ERROR_UNLESS_KRF(m_parser->compileEquation(equation.toASCIIString()), "Failed to compile equation [" << equation << "]", ErrorType::Internal); m_equationType = m_parser->getTreeCategory(); m_equationParam = m_parser->getTreeParameter(); @@ -35,8 +33,7 @@ bool CBoxAlgorithmSimpleDSP::initialize() boxContext.getOutputType(0, streamType); OV_ERROR_UNLESS_KRF(this->getTypeManager().isDerivedFromStream(streamType, OV_TypeId_StreamedMatrix), - "Invalid output stream [" << streamType.str() << "] (expected stream must derive from OV_TypeId_StreamedMatrix)", - ErrorType::Internal); + "Invalid output stream [" << streamType.str() << "] (expected stream must derive from OV_TypeId_StreamedMatrix)", ErrorType::Internal); if (streamType == OV_TypeId_StreamedMatrix) { diff --git a/plugins/processing/signal-processing/src/box-algorithms/ovpCBoxAlgorithmSimpleDSP.h b/plugins/processing/signal-processing/src/box-algorithms/ovpCBoxAlgorithmSimpleDSP.h index 2f07050fe9093419d1cc0b648dbd5e34f05509b6..1324e23529db387bee697d3e332edd053a7ce6fa 100644 --- a/plugins/processing/signal-processing/src/box-algorithms/ovpCBoxAlgorithmSimpleDSP.h +++ b/plugins/processing/signal-processing/src/box-algorithms/ovpCBoxAlgorithmSimpleDSP.h @@ -7,119 +7,116 @@ #include <vector> #include <cstdio> -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace SignalProcessing { +class CBoxAlgorithmSimpleDSP final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm> { - namespace Plugins +public: + + CBoxAlgorithmSimpleDSP() { } + void release() override { delete this; } + bool initialize() override; + bool uninitialize() override; + bool processInput(const size_t index) override; + bool process() override; + void evaluate(); + + _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_SimpleDSP) + +protected: + std::vector<Kernel::IAlgorithmProxy*> m_decoders; + Kernel::IAlgorithmProxy* m_encoder = nullptr; + std::vector<IMatrix*> m_matrices; + + CEquationParser* m_parser = nullptr; + + uint64_t m_equationType = OP_USERDEF; + double m_equationParam = 0; + double** m_variables = nullptr; + + bool m_checkDates = false; +}; + +class CBoxAlgorithmSimpleDSPListener final : public Toolkit::TBoxListener<IBoxListener> +{ +public: + bool onInputAdded(Kernel::IBox& box, const size_t index) override + { + char name[1024]; + sprintf(name, "Input - %c", char('A' + index)); + CIdentifier typeID = OV_UndefinedIdentifier; + box.getOutputType(0, typeID); + box.setInputType(index, typeID); + box.setInputName(index, name); + return true; + } + + bool onInputTypeChanged(Kernel::IBox& box, const size_t index) override + { + CIdentifier typeID = OV_UndefinedIdentifier; + box.getInputType(index, typeID); + box.setOutputType(0, typeID); + for (size_t i = 0; i < box.getInputCount(); ++i) { box.setInputType(i, typeID); } + return true; + } + + bool onOutputTypeChanged(Kernel::IBox& box, const size_t index) override + { + CIdentifier typeID = OV_UndefinedIdentifier; + box.getOutputType(index, typeID); + box.setOutputType(0, typeID); + for (size_t i = 0; i < box.getInputCount(); ++i) { box.setInputType(i, typeID); } + return true; + } + + _IsDerivedFromClass_Final_(Toolkit::TBoxListener<IBoxListener>, OV_UndefinedIdentifier) +}; + +class CBoxAlgorithmSimpleDSPDesc final : public IBoxAlgorithmDesc +{ +public: + void release() override { } + CString getName() const override { return CString("Simple DSP"); } + CString getAuthorName() const override { return CString("Bruno Renier / Yann Renard"); } + CString getAuthorCompanyName() const override { return CString("INRIA / IRISA"); } + CString getShortDescription() const override { return CString("Apply mathematical formulaes to matrices."); } + CString getDetailedDescription() const override { return CString(""); } + CString getCategory() const override { return CString("Signal processing/Basic"); } + CString getVersion() const override { return CString("1.0"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_SimpleDSP; } + IPluginObject* create() override { return new CBoxAlgorithmSimpleDSP(); } + IBoxListener* createBoxListener() const override { return new CBoxAlgorithmSimpleDSPListener; } + void releaseBoxListener(IBoxListener* listener) const override { delete listener; } + + bool getBoxPrototype(Kernel::IBoxProto& prototype) const override { - namespace SignalProcessing - { - class CBoxAlgorithmSimpleDSP final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm> - { - public: - - CBoxAlgorithmSimpleDSP() { } - void release() override { delete this; } - bool initialize() override; - bool uninitialize() override; - bool processInput(const size_t index) override; - bool process() override; - void evaluate(); - - _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_SimpleDSP) - - protected: - std::vector<Kernel::IAlgorithmProxy*> m_decoders; - Kernel::IAlgorithmProxy* m_encoder = nullptr; - std::vector<IMatrix*> m_matrices; - - CEquationParser* m_parser = nullptr; - - uint64_t m_equationType = OP_USERDEF; - double m_equationParam = 0; - double** m_variables = nullptr; - - bool m_checkDates = false; - }; - - class CBoxAlgorithmSimpleDSPListener final : public Toolkit::TBoxListener<IBoxListener> - { - public: - bool onInputAdded(Kernel::IBox& box, const size_t index) override - { - char name[1024]; - sprintf(name, "Input - %c", char('A' + index)); - CIdentifier typeID = OV_UndefinedIdentifier; - box.getOutputType(0, typeID); - box.setInputType(index, typeID); - box.setInputName(index, name); - return true; - } - - bool onInputTypeChanged(Kernel::IBox& box, const size_t index) override - { - CIdentifier typeID = OV_UndefinedIdentifier; - box.getInputType(index, typeID); - box.setOutputType(0, typeID); - for (size_t i = 0; i < box.getInputCount(); ++i) { box.setInputType(i, typeID); } - return true; - } - - bool onOutputTypeChanged(Kernel::IBox& box, const size_t index) override - { - CIdentifier typeID = OV_UndefinedIdentifier; - box.getOutputType(index, typeID); - box.setOutputType(0, typeID); - for (size_t i = 0; i < box.getInputCount(); ++i) { box.setInputType(i, typeID); } - return true; - } - - _IsDerivedFromClass_Final_(Toolkit::TBoxListener<IBoxListener>, OV_UndefinedIdentifier) - }; - - class CBoxAlgorithmSimpleDSPDesc final : public IBoxAlgorithmDesc - { - public: - void release() override { } - CString getName() const override { return CString("Simple DSP"); } - CString getAuthorName() const override { return CString("Bruno Renier / Yann Renard"); } - CString getAuthorCompanyName() const override { return CString("INRIA / IRISA"); } - CString getShortDescription() const override { return CString("Apply mathematical formulaes to matrices."); } - CString getDetailedDescription() const override { return CString(""); } - CString getCategory() const override { return CString("Signal processing/Basic"); } - CString getVersion() const override { return CString("1.0"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_SimpleDSP; } - IPluginObject* create() override { return new CBoxAlgorithmSimpleDSP(); } - IBoxListener* createBoxListener() const override { return new CBoxAlgorithmSimpleDSPListener; } - void releaseBoxListener(IBoxListener* listener) const override { delete listener; } - - bool getBoxPrototype(Kernel::IBoxProto& prototype) const override - { - prototype.addInput("Input - A", OV_TypeId_Signal); - prototype.addOutput("Output", OV_TypeId_Signal); - prototype.addSetting("Equation", OV_TypeId_String, "x"); - - prototype.addFlag(Kernel::BoxFlag_CanAddInput); - prototype.addFlag(Kernel::BoxFlag_CanModifyOutput); - prototype.addFlag(Kernel::BoxFlag_CanModifyInput); - - prototype.addInputSupport(OV_TypeId_StreamedMatrix); - prototype.addInputSupport(OV_TypeId_FeatureVector); - prototype.addInputSupport(OV_TypeId_Signal); - prototype.addInputSupport(OV_TypeId_Spectrum); - - prototype.addOutputSupport(OV_TypeId_StreamedMatrix); - prototype.addOutputSupport(OV_TypeId_FeatureVector); - prototype.addOutputSupport(OV_TypeId_Signal); - prototype.addOutputSupport(OV_TypeId_Spectrum); - - return true; - } - - _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_SimpleDSPDesc) - }; - } // namespace SignalProcessing - } // namespace Plugins + prototype.addInput("Input - A", OV_TypeId_Signal); + prototype.addOutput("Output", OV_TypeId_Signal); + prototype.addSetting("Equation", OV_TypeId_String, "x"); + + prototype.addFlag(Kernel::BoxFlag_CanAddInput); + prototype.addFlag(Kernel::BoxFlag_CanModifyOutput); + prototype.addFlag(Kernel::BoxFlag_CanModifyInput); + + prototype.addInputSupport(OV_TypeId_StreamedMatrix); + prototype.addInputSupport(OV_TypeId_FeatureVector); + prototype.addInputSupport(OV_TypeId_Signal); + prototype.addInputSupport(OV_TypeId_Spectrum); + + prototype.addOutputSupport(OV_TypeId_StreamedMatrix); + prototype.addOutputSupport(OV_TypeId_FeatureVector); + prototype.addOutputSupport(OV_TypeId_Signal); + prototype.addOutputSupport(OV_TypeId_Spectrum); + + return true; + } + + _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_SimpleDSPDesc) +}; +} // namespace SignalProcessing +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/signal-processing/src/box-algorithms/ovpCBoxAlgorithmWindowing.h b/plugins/processing/signal-processing/src/box-algorithms/ovpCBoxAlgorithmWindowing.h index bc23aa3607d3ce6975b4d124e4bb25decf2218ac..970caa7cebf0141baf7ec3b29815437f41533920 100644 --- a/plugins/processing/signal-processing/src/box-algorithms/ovpCBoxAlgorithmWindowing.h +++ b/plugins/processing/signal-processing/src/box-algorithms/ovpCBoxAlgorithmWindowing.h @@ -5,59 +5,56 @@ #include <vector> -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace SignalProcessing { +class CBoxAlgorithmWindowing final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm> { - namespace Plugins +public: + void release() override { delete this; } + bool initialize() override; + bool uninitialize() override; + bool processInput(const size_t index) override; + bool process() override; + + _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_Windowing) + +protected: + Toolkit::TSignalDecoder<CBoxAlgorithmWindowing> m_decoder; + Toolkit::TSignalEncoder<CBoxAlgorithmWindowing> m_encoder; + + EWindowMethod m_windowMethod = EWindowMethod::None; + std::vector<double> m_windowCoefs; +}; + +class CBoxAlgorithmWindowingDesc final : virtual public IBoxAlgorithmDesc +{ +public: + void release() override { } + CString getName() const override { return CString("Windowing"); } + CString getAuthorName() const override { return CString("Laurent Bonnet"); } + CString getAuthorCompanyName() const override { return CString("Mensia Technologies SA"); } + CString getShortDescription() const override { return CString("Applies a windowing function to the signal."); } + CString getDetailedDescription() const override { return CString("Applies a windowing function to the signal."); } + CString getCategory() const override { return CString("Signal processing/Temporal Filtering"); } + CString getVersion() const override { return CString("1.0"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } + CString getStockItemName() const override { return CString("gtk-execute"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_Windowing; } + IPluginObject* create() override { return new CBoxAlgorithmWindowing(); } + + bool getBoxPrototype(Kernel::IBoxProto& prototype) const override { - namespace SignalProcessing - { - class CBoxAlgorithmWindowing final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm> - { - public: - void release() override { delete this; } - bool initialize() override; - bool uninitialize() override; - bool processInput(const size_t index) override; - bool process() override; - - _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_Windowing) - - protected: - Toolkit::TSignalDecoder<CBoxAlgorithmWindowing> m_decoder; - Toolkit::TSignalEncoder<CBoxAlgorithmWindowing> m_encoder; - - EWindowMethod m_windowMethod = EWindowMethod::None; - std::vector<double> m_windowCoefs; - }; - - class CBoxAlgorithmWindowingDesc final : virtual public IBoxAlgorithmDesc - { - public: - void release() override { } - CString getName() const override { return CString("Windowing"); } - CString getAuthorName() const override { return CString("Laurent Bonnet"); } - CString getAuthorCompanyName() const override { return CString("Mensia Technologies SA"); } - CString getShortDescription() const override { return CString("Applies a windowing function to the signal."); } - CString getDetailedDescription() const override { return CString("Applies a windowing function to the signal."); } - CString getCategory() const override { return CString("Signal processing/Temporal Filtering"); } - CString getVersion() const override { return CString("1.0"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } - CString getStockItemName() const override { return CString("gtk-execute"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_Windowing; } - IPluginObject* create() override { return new CBoxAlgorithmWindowing(); } - - bool getBoxPrototype(Kernel::IBoxProto& prototype) const override - { - prototype.addInput("Input signal", OV_TypeId_Signal); - prototype.addOutput("Output signal", OV_TypeId_Signal); - prototype.addSetting("Window method", OVP_TypeId_WindowMethod, "Hamming"); - return true; - } - - _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_WindowingDesc) - }; - } // namespace SignalProcessing - } // namespace Plugins + prototype.addInput("Input signal", OV_TypeId_Signal); + prototype.addOutput("Output signal", OV_TypeId_Signal); + prototype.addSetting("Window method", OVP_TypeId_WindowMethod, "Hamming"); + return true; + } + + _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_WindowingDesc) +}; +} // namespace SignalProcessing +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/signal-processing/src/box-algorithms/ovpCBoxAlgorithmXDAWNTrainer.cpp b/plugins/processing/signal-processing/src/box-algorithms/ovpCBoxAlgorithmXDAWNTrainer.cpp index a3d596b55afdce658272bb59acee2b9dab5a8614..f24476dcac52cd73aac0965f47effb211d67d8d1 100755 --- a/plugins/processing/signal-processing/src/box-algorithms/ovpCBoxAlgorithmXDAWNTrainer.cpp +++ b/plugins/processing/signal-processing/src/box-algorithms/ovpCBoxAlgorithmXDAWNTrainer.cpp @@ -235,7 +235,7 @@ bool CBoxAlgorithmXDAWNTrainer::process() OV_ERROR_KRF("Could not solve generalized eigen decomposition, got error[" << CString(errorMessage) << "]\n", ErrorType::BadProcessing); } - + // Create a CMatrix mapper that can spool the filters to a file CMatrix eigenVectors; @@ -245,8 +245,8 @@ bool CBoxAlgorithmXDAWNTrainer::process() Eigen::Map<MatrixXdRowMajor> vectorsMapper(eigenVectors.getBuffer(), m_filterDim, nChannel); - vectorsMapper.block(0, 0, m_filterDim, nChannel) = eigenSolver.eigenvectors().block(0, 0, nChannel, m_filterDim).transpose(); - + vectorsMapper.block(0, 0, m_filterDim, nChannel) = eigenSolver.eigenvectors().block(0, 0, nChannel, m_filterDim).transpose(); + // Saves filters FILE* file = FS::Files::open(m_filterFilename.toASCIIString(), "wt"); diff --git a/plugins/processing/signal-processing/src/box-algorithms/ovpCBoxAlgorithmXDAWNTrainer.h b/plugins/processing/signal-processing/src/box-algorithms/ovpCBoxAlgorithmXDAWNTrainer.h index acbf9e0b55a52c9ae935f51a4d098e8fe5e835a2..9fd49ff5732d6d96bb30ae1e2b6319df819c8f53 100755 --- a/plugins/processing/signal-processing/src/box-algorithms/ovpCBoxAlgorithmXDAWNTrainer.h +++ b/plugins/processing/signal-processing/src/box-algorithms/ovpCBoxAlgorithmXDAWNTrainer.h @@ -9,80 +9,74 @@ typedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> MatrixXdRowMajor; -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace SignalProcessing { +class CBoxAlgorithmXDAWNTrainer final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm> { - namespace Plugins +public: + CBoxAlgorithmXDAWNTrainer(); + void release() override { delete this; } + bool initialize() override; + bool uninitialize() override; + bool processInput(const size_t index) override; + bool process() override; + + _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_InriaXDAWNTrainer) + +protected: + + Toolkit::TStimulationDecoder<CBoxAlgorithmXDAWNTrainer> m_stimDecoder; + std::array<Toolkit::TSignalDecoder<CBoxAlgorithmXDAWNTrainer>, 2> m_signalDecoder; + Toolkit::TStimulationEncoder<CBoxAlgorithmXDAWNTrainer> m_stimEncoder; + + uint64_t m_trainStimulationID = 0; + CString m_filterFilename; + size_t m_filterDim = 0; + bool m_saveAsBoxConfig = false; +}; + +class CBoxAlgorithmXDAWNTrainerDesc final : public IBoxAlgorithmDesc +{ +public: + void release() override {} + CString getName() const override { return CString("xDAWN Trainer"); } + CString getAuthorName() const override { return CString("Yann Renard"); } + CString getAuthorCompanyName() const override { return CString("Mensia Technologies SA"); } + + CString getShortDescription() const override { return CString("Trains spatial filters that best highlight Evoked Response Potentials (ERP) such as P300"); } + + CString getDetailedDescription() const override + { + return CString("Trains spatial filters that best highlight Evoked Response Potentials (ERP) such as P300"); + } + + CString getCategory() const override { return CString("Signal processing/Spatial Filtering"); } + CString getVersion() const override { return CString("1.0"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } + CString getStockItemName() const override { return CString("gtk-zoom-100"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_InriaXDAWNTrainer; } + IPluginObject* create() override { return new CBoxAlgorithmXDAWNTrainer; } + + bool getBoxPrototype(Kernel::IBoxProto& prototype) const override { - namespace SignalProcessing - { - class CBoxAlgorithmXDAWNTrainer final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm> - { - public: - CBoxAlgorithmXDAWNTrainer(); - void release() override { delete this; } - bool initialize() override; - bool uninitialize() override; - bool processInput(const size_t index) override; - bool process() override; - - _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_InriaXDAWNTrainer) - - protected: - - Toolkit::TStimulationDecoder<CBoxAlgorithmXDAWNTrainer> m_stimDecoder; - std::array<Toolkit::TSignalDecoder<CBoxAlgorithmXDAWNTrainer>, 2> m_signalDecoder; - Toolkit::TStimulationEncoder<CBoxAlgorithmXDAWNTrainer> m_stimEncoder; - - uint64_t m_trainStimulationID = 0; - CString m_filterFilename; - size_t m_filterDim = 0; - bool m_saveAsBoxConfig = false; - }; - - class CBoxAlgorithmXDAWNTrainerDesc final : public IBoxAlgorithmDesc - { - public: - void release() override {} - CString getName() const override { return CString("xDAWN Trainer"); } - CString getAuthorName() const override { return CString("Yann Renard"); } - CString getAuthorCompanyName() const override { return CString("Mensia Technologies SA"); } - - CString getShortDescription() const override - { - return CString("Trains spatial filters that best highlight Evoked Response Potentials (ERP) such as P300"); - } - - CString getDetailedDescription() const override - { - return CString("Trains spatial filters that best highlight Evoked Response Potentials (ERP) such as P300"); - } - - CString getCategory() const override { return CString("Signal processing/Spatial Filtering"); } - CString getVersion() const override { return CString("1.0"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } - CString getStockItemName() const override { return CString("gtk-zoom-100"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_InriaXDAWNTrainer; } - IPluginObject* create() override { return new CBoxAlgorithmXDAWNTrainer; } - - bool getBoxPrototype(Kernel::IBoxProto& prototype) const override - { - prototype.addInput("Stimulations", OV_TypeId_Stimulations); - prototype.addInput("Session signal", OV_TypeId_Signal); - prototype.addInput("Evoked potential epochs", OV_TypeId_Signal); - - prototype.addOutput("Train-completed Flag", OV_TypeId_Stimulations); - - prototype.addSetting("Train stimulation", OV_TypeId_Stimulation, "OVTK_StimulationId_Train"); - prototype.addSetting("Spatial filter configuration", OV_TypeId_Filename, ""); - prototype.addSetting("Filter dimension", OV_TypeId_Integer, "4"); - prototype.addSetting("Save as box config", OV_TypeId_Boolean, "true"); - return true; - } - - _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_InriaXDAWNTrainerDesc) - }; - } // namespace SignalProcessing - } // namespace Plugins + prototype.addInput("Stimulations", OV_TypeId_Stimulations); + prototype.addInput("Session signal", OV_TypeId_Signal); + prototype.addInput("Evoked potential epochs", OV_TypeId_Signal); + + prototype.addOutput("Train-completed Flag", OV_TypeId_Stimulations); + + prototype.addSetting("Train stimulation", OV_TypeId_Stimulation, "OVTK_StimulationId_Train"); + prototype.addSetting("Spatial filter configuration", OV_TypeId_Filename, ""); + prototype.addSetting("Filter dimension", OV_TypeId_Integer, "4"); + prototype.addSetting("Save as box config", OV_TypeId_Boolean, "true"); + return true; + } + + _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_InriaXDAWNTrainerDesc) +}; +} // namespace SignalProcessing +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/signal-processing/src/box-algorithms/resampling/ovpCBoxAlgorithmSignalResampling.cpp b/plugins/processing/signal-processing/src/box-algorithms/resampling/ovpCBoxAlgorithmSignalResampling.cpp index 257e945b1f6e66151ef393523a90c084d2f2a7c3..9d76a78981dfe0952d161e635ab554b9bd4174f9 100644 --- a/plugins/processing/signal-processing/src/box-algorithms/resampling/ovpCBoxAlgorithmSignalResampling.cpp +++ b/plugins/processing/signal-processing/src/box-algorithms/resampling/ovpCBoxAlgorithmSignalResampling.cpp @@ -28,31 +28,30 @@ using namespace /*OpenViBE::*/Kernel; using namespace /*OpenViBE::*/Plugins; using namespace SignalProcessing; -namespace SigProSTD +namespace SigProSTD { +template <typename T, typename std::enable_if<std::is_integral<T>::value>::type* = nullptr, + typename std::enable_if<std::is_unsigned<T>::value>::type* = nullptr> +T gcd(T a, T b) { - template <typename T, typename std::enable_if<std::is_integral<T>::value>::type* = nullptr, typename std::enable_if<std::is_unsigned<T>::value>::type* = - nullptr> - T gcd(T a, T b) - { - T t; - - if (a > b) // ensure b > a - { - t = b; - b = a; - a = t; - } + T t; - while (b != 0) - { - t = a % b; - a = b; - b = t; - } + if (a > b) // ensure b > a + { + t = b; + b = a; + a = t; + } - return a; + while (b != 0) + { + t = a % b; + a = b; + b = t; } -} // namespace SigProSTD + + return a; +} +} // namespace SigProSTD bool CBoxAlgorithmSignalResampling::initialize() { diff --git a/plugins/processing/signal-processing/src/box-algorithms/resampling/ovpCBoxAlgorithmSignalResampling.h b/plugins/processing/signal-processing/src/box-algorithms/resampling/ovpCBoxAlgorithmSignalResampling.h index 61b6f9c87db58039cf1f4d21f2c2598460932a5f..078776717f12d638b7706c6bd3924e29d0b714c2 100644 --- a/plugins/processing/signal-processing/src/box-algorithms/resampling/ovpCBoxAlgorithmSignalResampling.h +++ b/plugins/processing/signal-processing/src/box-algorithms/resampling/ovpCBoxAlgorithmSignalResampling.h @@ -28,89 +28,86 @@ #include <Eigen/Eigen> -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace SignalProcessing { +typedef Common::Resampler::CResamplerSd CResampler; + +class CBoxAlgorithmSignalResampling final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm>, CResampler::ICallback { - namespace Plugins +public: + void release() override { delete this; } + bool initialize() override; + bool uninitialize() override; + bool processInput(const size_t index) override; + bool process() override; + + // implementation for TResampler::ICallback + void processResampler(const double* sample, const size_t nChannel) const override; + + _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_SignalResampling) + +protected: + + Toolkit::TSignalDecoder<CBoxAlgorithmSignalResampling> m_decoder; + mutable Toolkit::TSignalEncoder<CBoxAlgorithmSignalResampling> m_encoder; + + size_t m_oSampling = 0; + size_t m_oNSample = 0; + + int m_nFractionalDelayFilterSample = 0; + double m_transitionBandPercent = 0; + double m_stopBandAttenuation = 0; + + size_t m_iSampling = 0; + mutable uint64_t m_oTotalSample = 0; + CResampler m_resampler; + Kernel::IBoxIO* m_boxContext = nullptr; +}; + +class CBoxAlgorithmSignalResamplingDesc final : public IBoxAlgorithmDesc +{ +public: + void release() override { } + CString getName() const override { return CString("Signal Resampling"); } + CString getAuthorName() const override { return CString("Quentin Barthelemy"); } + CString getAuthorCompanyName() const override { return CString("Mensia Technologies SA"); } + + CString getShortDescription() const override { return CString("Resamples and re-epochs input signal to chosen sampling frequency"); } + + CString getDetailedDescription() const override + { + return CString("The input signal is resampled, down-sampled or up-sampled, at a chosen sampling frequency and then re-epoched."); + } + + CString getCategory() const override { return CString("Signal processing/Temporal Filtering"); } + CString getVersion() const override { return CString("2.0"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_SignalResampling; } + IPluginObject* create() override { return new CBoxAlgorithmSignalResampling; } + + bool getBoxPrototype(Kernel::IBoxProto& prototype) const override { - namespace SignalProcessing - { - typedef Common::Resampler::CResamplerSd CResampler; - - class CBoxAlgorithmSignalResampling final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm>, CResampler::ICallback - { - public: - void release() override { delete this; } - bool initialize() override; - bool uninitialize() override; - bool processInput(const size_t index) override; - bool process() override; - - // implementation for TResampler::ICallback - void processResampler(const double* sample, const size_t nChannel) const override; - - _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_SignalResampling) - - protected: - - Toolkit::TSignalDecoder<CBoxAlgorithmSignalResampling> m_decoder; - mutable Toolkit::TSignalEncoder<CBoxAlgorithmSignalResampling> m_encoder; - - size_t m_oSampling = 0; - size_t m_oNSample = 0; - - int m_nFractionalDelayFilterSample = 0; - double m_transitionBandPercent = 0; - double m_stopBandAttenuation = 0; - - size_t m_iSampling = 0; - mutable uint64_t m_oTotalSample = 0; - CResampler m_resampler; - Kernel::IBoxIO* m_boxContext = nullptr; - }; - - class CBoxAlgorithmSignalResamplingDesc final : public IBoxAlgorithmDesc - { - public: - void release() override { } - CString getName() const override { return CString("Signal Resampling"); } - CString getAuthorName() const override { return CString("Quentin Barthelemy"); } - CString getAuthorCompanyName() const override { return CString("Mensia Technologies SA"); } - - CString getShortDescription() const override { return CString("Resamples and re-epochs input signal to chosen sampling frequency"); } - - CString getDetailedDescription() const override - { - return CString("The input signal is resampled, down-sampled or up-sampled, at a chosen sampling frequency and then re-epoched."); - } - - CString getCategory() const override { return CString("Signal processing/Temporal Filtering"); } - CString getVersion() const override { return CString("2.0"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_SignalResampling; } - IPluginObject* create() override { return new CBoxAlgorithmSignalResampling; } - - bool getBoxPrototype(Kernel::IBoxProto& prototype) const override - { - prototype.addInput("Input signal", OV_TypeId_Signal); - prototype.addOutput("Output signal", OV_TypeId_Signal); - prototype.addSetting("New Sampling Frequency", OV_TypeId_Integer, "128", false, - OVP_ClassId_BoxAlgorithm_SignalResampling_SettingId_NewSampling); - prototype.addSetting("Sample Count Per Buffer", OV_TypeId_Integer, "8", false, - OVP_ClassId_BoxAlgorithm_SignalResampling_SettingId_SampleCountPerBuffer); - prototype.addSetting("Low Pass Filter Signal Before Downsampling", OV_TypeId_Boolean, "true", false, - OVP_ClassId_BoxAlgorithm_SignalResampling_SettingId_LowPassFilterSignalFlag); // displayed for backward compatibility, but never used - - //prototype.addSetting("New Sampling Frequency",OV_TypeId_Integer,"128"); - //prototype.addSetting("Sample Count Per Buffer",OV_TypeId_Integer,"8"); - //prototype.addSetting("Low Pass Filter Signal Before Downsampling", OV_TypeId_Boolean, "true"); // displayed for backward compatibility, but never used - - return true; - } - - _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_SignalResamplingDesc) - }; - } // namespace SignalProcessing - } // namespace Plugins + prototype.addInput("Input signal", OV_TypeId_Signal); + prototype.addOutput("Output signal", OV_TypeId_Signal); + prototype.addSetting("New Sampling Frequency", OV_TypeId_Integer, "128", false, + OVP_ClassId_BoxAlgorithm_SignalResampling_SettingId_NewSampling); + prototype.addSetting("Sample Count Per Buffer", OV_TypeId_Integer, "8", false, + OVP_ClassId_BoxAlgorithm_SignalResampling_SettingId_SampleCountPerBuffer); + prototype.addSetting("Low Pass Filter Signal Before Downsampling", OV_TypeId_Boolean, "true", false, + OVP_ClassId_BoxAlgorithm_SignalResampling_SettingId_LowPassFilterSignalFlag); // displayed for backward compatibility, but never used + + //prototype.addSetting("New Sampling Frequency",OV_TypeId_Integer,"128"); + //prototype.addSetting("Sample Count Per Buffer",OV_TypeId_Integer,"8"); + //prototype.addSetting("Low Pass Filter Signal Before Downsampling", OV_TypeId_Boolean, "true"); // displayed for backward compatibility, but never used + + return true; + } + + _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_SignalResamplingDesc) +}; +} // namespace SignalProcessing +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/signal-processing/src/box-algorithms/spectral-analysis/ovpCBoxAlgorithmContinuousWaveletAnalysis.cpp b/plugins/processing/signal-processing/src/box-algorithms/spectral-analysis/ovpCBoxAlgorithmContinuousWaveletAnalysis.cpp index a2477db6b6d9a935fed600f10f15dfb4782abd6a..e1ca4949397d481f3009f92596e3273733372460 100644 --- a/plugins/processing/signal-processing/src/box-algorithms/spectral-analysis/ovpCBoxAlgorithmContinuousWaveletAnalysis.cpp +++ b/plugins/processing/signal-processing/src/box-algorithms/spectral-analysis/ovpCBoxAlgorithmContinuousWaveletAnalysis.cpp @@ -13,21 +13,20 @@ using namespace SignalProcessing; using namespace /*OpenViBE::*/Toolkit; -namespace SigProSTD +namespace SigProSTD { +double WaveletFourierFactor(const char* type, const double param) { - double WaveletFourierFactor(const char* type, const double param) - { - double factor = -1; - if (strcmp(type, "morlet") == 0) { factor = 4.0 * M_PI / (param + std::sqrt(2 + param * param)); } - else if (strcmp(type, "paul") == 0) { factor = 4.0 * M_PI / (2 * param + 1); } - else if (strcmp(type, "dog") == 0) { factor = 2.0 * M_PI / std::sqrt(param + 0.5); } - return factor; - } + double factor = -1; + if (strcmp(type, "morlet") == 0) { factor = 4.0 * M_PI / (param + std::sqrt(2 + param * param)); } + else if (strcmp(type, "paul") == 0) { factor = 4.0 * M_PI / (2 * param + 1); } + else if (strcmp(type, "dog") == 0) { factor = 2.0 * M_PI / std::sqrt(param + 0.5); } + return factor; +} - double WaveletScale2Period(const char* type, const double param, const double scale) { return WaveletFourierFactor(type, param) * scale; } - double WaveletScale2Freq(const char* type, const double param, const double scale) { return 1.0 / (WaveletFourierFactor(type, param) * scale); } - double WaveletFreq2Scale(const char* type, const double param, const double frequency) { return 1.0 / (WaveletFourierFactor(type, param) * frequency); } -} // namespace SigProSTD +double WaveletScale2Period(const char* type, const double param, const double scale) { return WaveletFourierFactor(type, param) * scale; } +double WaveletScale2Freq(const char* type, const double param, const double scale) { return 1.0 / (WaveletFourierFactor(type, param) * scale); } +double WaveletFreq2Scale(const char* type, const double param, const double frequency) { return 1.0 / (WaveletFourierFactor(type, param) * frequency); } +} // namespace SigProSTD bool CBoxAlgorithmContinuousWaveletAnalysis::initialize() { @@ -171,7 +170,7 @@ bool CBoxAlgorithmContinuousWaveletAnalysis::process() } // initialize CWT - m_waveletTransform = cwt_init(const_cast<char *>(m_waveletType), m_waveletParam, int(nSample), m_samplingPeriodDt, int(m_nScaleJ)); + m_waveletTransform = cwt_init(const_cast<char*>(m_waveletType), m_waveletParam, int(nSample), m_samplingPeriodDt, int(m_nScaleJ)); if (!m_waveletTransform) { this->getLogManager() << LogLevel_Error << "Error during CWT initialization.\n"; @@ -194,7 +193,7 @@ bool CBoxAlgorithmContinuousWaveletAnalysis::process() oMatrix->setDimensionSize(1, m_nScaleJ); oMatrix->setDimensionSize(2, nSample); - for (size_t c = 0; c < nChannel; ++c) { oMatrix->setDimensionLabel(0, c, iMatrix->getDimensionLabel(0, c)); } + for (size_t c = 0; c < nChannel; ++c) { oMatrix->setDimensionLabel(0, c, iMatrix->getDimensionLabel(0, c)); } for (size_t scaleIndex = 0; scaleIndex < m_nScaleJ; ++scaleIndex) { const double scaleValue = m_waveletTransform->scale[scaleIndex]; diff --git a/plugins/processing/signal-processing/src/box-algorithms/spectral-analysis/ovpCBoxAlgorithmContinuousWaveletAnalysis.h b/plugins/processing/signal-processing/src/box-algorithms/spectral-analysis/ovpCBoxAlgorithmContinuousWaveletAnalysis.h index 9c9f2ba1e0c2e16e812350ef1e2f6b51abc0daab..a2247f5dff2e157f564c54aa8b956a2491ec92a4 100644 --- a/plugins/processing/signal-processing/src/box-algorithms/spectral-analysis/ovpCBoxAlgorithmContinuousWaveletAnalysis.h +++ b/plugins/processing/signal-processing/src/box-algorithms/spectral-analysis/ovpCBoxAlgorithmContinuousWaveletAnalysis.h @@ -5,81 +5,78 @@ #include <wavelib/header/wavelib.h> #include <array> -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace SignalProcessing { +class CBoxAlgorithmContinuousWaveletAnalysis final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm> { - namespace Plugins - { - namespace SignalProcessing - { - class CBoxAlgorithmContinuousWaveletAnalysis final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm> - { - public: - void release() override { delete this; } - bool initialize() override; - bool uninitialize() override; - bool processInput(const size_t index) override; - bool process() override; +public: + void release() override { delete this; } + bool initialize() override; + bool uninitialize() override; + bool processInput(const size_t index) override; + bool process() override; - _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_ContinuousWaveletAnalysis) + _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_ContinuousWaveletAnalysis) - protected: +protected: - Toolkit::TSignalDecoder<CBoxAlgorithmContinuousWaveletAnalysis> m_decoder; - std::array<Toolkit::TStreamedMatrixEncoder<CBoxAlgorithmContinuousWaveletAnalysis>, 4> m_encoders; + Toolkit::TSignalDecoder<CBoxAlgorithmContinuousWaveletAnalysis> m_decoder; + std::array<Toolkit::TStreamedMatrixEncoder<CBoxAlgorithmContinuousWaveletAnalysis>, 4> m_encoders; - const char* m_waveletType = nullptr; - double m_waveletParam = 0; - size_t m_nScaleJ = 0; - double m_highestFreq = 0; - double m_smallestScaleS0 = 0; - double m_scaleSpacingDj = 0; + const char* m_waveletType = nullptr; + double m_waveletParam = 0; + size_t m_nScaleJ = 0; + double m_highestFreq = 0; + double m_smallestScaleS0 = 0; + double m_scaleSpacingDj = 0; - const char* m_scaleType = nullptr; - int m_scalePowerBaseA0 = 0; - double m_samplingPeriodDt = 0; - cwt_object m_waveletTransform = nullptr; - }; + const char* m_scaleType = nullptr; + int m_scalePowerBaseA0 = 0; + double m_samplingPeriodDt = 0; + cwt_object m_waveletTransform = nullptr; +}; - class CBoxAlgorithmContinuousWaveletAnalysisDesc final : virtual public IBoxAlgorithmDesc - { - public: - void release() override { } - CString getName() const override { return CString("Continuous Wavelet Analysis"); } - CString getAuthorName() const override { return CString("Quentin Barthelemy"); } - CString getAuthorCompanyName() const override { return CString("Mensia Technologies SA"); } - CString getShortDescription() const override { return CString("Performs a Time-Frequency Analysis using CWT."); } +class CBoxAlgorithmContinuousWaveletAnalysisDesc final : virtual public IBoxAlgorithmDesc +{ +public: + void release() override { } + CString getName() const override { return CString("Continuous Wavelet Analysis"); } + CString getAuthorName() const override { return CString("Quentin Barthelemy"); } + CString getAuthorCompanyName() const override { return CString("Mensia Technologies SA"); } + CString getShortDescription() const override { return CString("Performs a Time-Frequency Analysis using CWT."); } - CString getDetailedDescription() const override { return CString("Performs a Time-Frequency Analysis using Continuous Wavelet Transform."); } + CString getDetailedDescription() const override { return CString("Performs a Time-Frequency Analysis using Continuous Wavelet Transform."); } - CString getCategory() const override { return CString("Signal processing/Spectral Analysis"); } - CString getVersion() const override { return CString("1.0"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("1.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("1.0.0"); } - CString getStockItemName() const override { return CString("gtk-execute"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_ContinuousWaveletAnalysis; } - IPluginObject* create() override { return new CBoxAlgorithmContinuousWaveletAnalysis(); } + CString getCategory() const override { return CString("Signal processing/Spectral Analysis"); } + CString getVersion() const override { return CString("1.0"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("1.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("1.0.0"); } + CString getStockItemName() const override { return CString("gtk-execute"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_ContinuousWaveletAnalysis; } + IPluginObject* create() override { return new CBoxAlgorithmContinuousWaveletAnalysis(); } - bool getBoxPrototype(Kernel::IBoxProto& prototype) const override - { - prototype.addInput("Input signal", OV_TypeId_Signal); + bool getBoxPrototype(Kernel::IBoxProto& prototype) const override + { + prototype.addInput("Input signal", OV_TypeId_Signal); - prototype.addOutput("Amplitude", OV_TypeId_TimeFrequency); - prototype.addOutput("Phase", OV_TypeId_TimeFrequency); - prototype.addOutput("Real Part", OV_TypeId_TimeFrequency); - prototype.addOutput("Imaginary Part", OV_TypeId_TimeFrequency); + prototype.addOutput("Amplitude", OV_TypeId_TimeFrequency); + prototype.addOutput("Phase", OV_TypeId_TimeFrequency); + prototype.addOutput("Real Part", OV_TypeId_TimeFrequency); + prototype.addOutput("Imaginary Part", OV_TypeId_TimeFrequency); - prototype.addSetting("Wavelet type", OVP_TypeId_ContinuousWaveletType, "Morlet wavelet"); - prototype.addSetting("Wavelet parameter", OV_TypeId_Float, "4"); - prototype.addSetting("Number of frequencies", OV_TypeId_Integer, "60"); - prototype.addSetting("Highest frequency", OV_TypeId_Float, "35"); - prototype.addSetting("Frequency spacing", OV_TypeId_Float, "12.5"); + prototype.addSetting("Wavelet type", OVP_TypeId_ContinuousWaveletType, "Morlet wavelet"); + prototype.addSetting("Wavelet parameter", OV_TypeId_Float, "4"); + prototype.addSetting("Number of frequencies", OV_TypeId_Integer, "60"); + prototype.addSetting("Highest frequency", OV_TypeId_Float, "35"); + prototype.addSetting("Frequency spacing", OV_TypeId_Float, "12.5"); - return true; - } + return true; + } - _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_ContinuousWaveletAnalysisDesc) - }; - } // namespace SignalProcessing - } // namespace Plugins + _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_ContinuousWaveletAnalysisDesc) +}; +} // namespace SignalProcessing +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/signal-processing/src/box-algorithms/spectral-analysis/ovpCBoxAlgorithmFrequencyBandSelector.cpp b/plugins/processing/signal-processing/src/box-algorithms/spectral-analysis/ovpCBoxAlgorithmFrequencyBandSelector.cpp index 361447856ce9dd885252116e15ac9e8265703e0a..4010b85f6973ae92c9151f926c6cc5b91f26475f 100755 --- a/plugins/processing/signal-processing/src/box-algorithms/spectral-analysis/ovpCBoxAlgorithmFrequencyBandSelector.cpp +++ b/plugins/processing/signal-processing/src/box-algorithms/spectral-analysis/ovpCBoxAlgorithmFrequencyBandSelector.cpp @@ -9,22 +9,21 @@ using namespace std; #include <vector> #include <string> -namespace +namespace { +vector<string> split(const string& str, const char c) { - vector<string> split(const string& str, const char c) + vector<string> result; + size_t i = 0; + while (i < str.length()) { - vector<string> result; - size_t i = 0; - while (i < str.length()) - { - size_t j = i; - while (j < str.length() && str[j] != c) { j++; } - if (i != j) { result.push_back(string(str, i, j - i)); } - i = j + 1; - } - return result; + size_t j = i; + while (j < str.length() && str[j] != c) { j++; } + if (i != j) { result.push_back(string(str, i, j - i)); } + i = j + 1; } -} // namespace + return result; +} +} // namespace bool CBoxAlgorithmFrequencyBandSelector::initialize() { diff --git a/plugins/processing/signal-processing/src/box-algorithms/spectral-analysis/ovpCBoxAlgorithmFrequencyBandSelector.h b/plugins/processing/signal-processing/src/box-algorithms/spectral-analysis/ovpCBoxAlgorithmFrequencyBandSelector.h index d2b29c4c22e4aa1615a5c2b795fe72d5f67ae8d9..3c098bea64a892c97b3d81f31344e3ecf6866f0c 100755 --- a/plugins/processing/signal-processing/src/box-algorithms/spectral-analysis/ovpCBoxAlgorithmFrequencyBandSelector.h +++ b/plugins/processing/signal-processing/src/box-algorithms/spectral-analysis/ovpCBoxAlgorithmFrequencyBandSelector.h @@ -8,77 +8,74 @@ #include <map> #include <algorithm> -namespace OpenViBE -{ - namespace Plugins - { - namespace SignalProcessing - { - typedef std::pair<double, double> BandRange; +namespace OpenViBE { +namespace Plugins { +namespace SignalProcessing { +typedef std::pair<double, double> BandRange; - class CBoxAlgorithmFrequencyBandSelector final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm> - { - public: - void release() override { delete this; } - bool initialize() override; - bool uninitialize() override; - bool processInput(const size_t index) override; - bool process() override; +class CBoxAlgorithmFrequencyBandSelector final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm> +{ +public: + void release() override { delete this; } + bool initialize() override; + bool uninitialize() override; + bool processInput(const size_t index) override; + bool process() override; - _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_FrequencyBandSelector) + _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_FrequencyBandSelector) - protected: +protected: - Kernel::IAlgorithmProxy* m_decoder = nullptr; - Kernel::TParameterHandler<const IMemoryBuffer*> ip_buffer; - Kernel::TParameterHandler<IMatrix*> op_matrix; - Kernel::TParameterHandler<IMatrix*> op_bands; + Kernel::IAlgorithmProxy* m_decoder = nullptr; + Kernel::TParameterHandler<const IMemoryBuffer*> ip_buffer; + Kernel::TParameterHandler<IMatrix*> op_matrix; + Kernel::TParameterHandler<IMatrix*> op_bands; - Kernel::IAlgorithmProxy* m_encoder = nullptr; - Kernel::TParameterHandler<IMatrix*> ip_matrix; - Kernel::TParameterHandler<IMatrix*> ip_frequencyAbscissa; - Kernel::TParameterHandler<IMemoryBuffer*> op_buffer; + Kernel::IAlgorithmProxy* m_encoder = nullptr; + Kernel::TParameterHandler<IMatrix*> ip_matrix; + Kernel::TParameterHandler<IMatrix*> ip_frequencyAbscissa; + Kernel::TParameterHandler<IMemoryBuffer*> op_buffer; - CMatrix m_oMatrix; - std::vector<BandRange> m_selecteds; - std::vector<double> m_selectionFactors; - }; + CMatrix m_oMatrix; + std::vector<BandRange> m_selecteds; + std::vector<double> m_selectionFactors; +}; - class CBoxAlgorithmFrequencyBandSelectorDesc final : public IBoxAlgorithmDesc - { - public: - void release() override { } - CString getName() const override { return CString("Frequency Band Selector"); } - CString getAuthorName() const override { return CString("Yann Renard"); } - CString getAuthorCompanyName() const override { return CString("INRIA"); } +class CBoxAlgorithmFrequencyBandSelectorDesc final : public IBoxAlgorithmDesc +{ +public: + void release() override { } + CString getName() const override { return CString("Frequency Band Selector"); } + CString getAuthorName() const override { return CString("Yann Renard"); } + CString getAuthorCompanyName() const override { return CString("INRIA"); } - CString getShortDescription() const override - { - return CString( - "Preserves some spectrum coefficients and puts the others to zero depending on a list of frequencies / frequency bands to select"); - } + CString getShortDescription() const override + { + return CString( + "Preserves some spectrum coefficients and puts the others to zero depending on a list of frequencies / frequency bands to select"); + } - CString getDetailedDescription() const override { return CString(""); } - CString getCategory() const override { return CString("Signal processing/Spectral Analysis"); } - CString getVersion() const override { return CString("1.0"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_FrequencyBandSelector; } - IPluginObject* create() override { return new CBoxAlgorithmFrequencyBandSelector; } + CString getDetailedDescription() const override { return CString(""); } + CString getCategory() const override { return CString("Signal processing/Spectral Analysis"); } + CString getVersion() const override { return CString("1.0"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_FrequencyBandSelector; } + IPluginObject* create() override { return new CBoxAlgorithmFrequencyBandSelector; } - bool getBoxPrototype(Kernel::IBoxProto& prototype) const override - { - prototype.addInput("Input spectrum", OV_TypeId_Spectrum); - prototype.addOutput("Output spectrum", OV_TypeId_Spectrum); - prototype.addSetting("Frequencies to select", OV_TypeId_String, "8:12;16:24"); - // @fixme Use OV_Value_RangeStringSeparator / OV_Value_EnumeratedStringSeparator tokens above + bool getBoxPrototype(Kernel::IBoxProto& prototype) const override + { + prototype.addInput("Input spectrum", OV_TypeId_Spectrum); + prototype.addOutput("Output spectrum", OV_TypeId_Spectrum); + prototype.addSetting("Frequencies to select", OV_TypeId_String, "8:12;16:24"); + // @fixme Use OV_Value_RangeStringSeparator / OV_Value_EnumeratedStringSeparator tokens above - return true; - } + return true; + } - _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_FrequencyBandSelectorDesc) - }; - } // namespace SignalProcessing - } // namespace Plugins + _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_FrequencyBandSelectorDesc) +}; +} // namespace SignalProcessing +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/signal-processing/src/box-algorithms/spectral-analysis/ovpCBoxAlgorithmSpectralAnalysis.cpp b/plugins/processing/signal-processing/src/box-algorithms/spectral-analysis/ovpCBoxAlgorithmSpectralAnalysis.cpp index 8aef4cf6cc0f5e526018d900f25e70c5e7931ebe..132b5845b6ab58fbce06fc525e2cc9dca2ee0f95 100755 --- a/plugins/processing/signal-processing/src/box-algorithms/spectral-analysis/ovpCBoxAlgorithmSpectralAnalysis.cpp +++ b/plugins/processing/signal-processing/src/box-algorithms/spectral-analysis/ovpCBoxAlgorithmSpectralAnalysis.cpp @@ -17,23 +17,21 @@ using namespace /*OpenViBE::*/Plugins; using namespace SignalProcessing; using namespace /*OpenViBE::*/Toolkit; -namespace +namespace { +double amplitude(const size_t channelIdx, const size_t fftIdx, const MatrixXcd& matrix) { - double amplitude(const size_t channelIdx, const size_t fftIdx, const MatrixXcd& matrix) - { - return sqrt( - matrix(channelIdx, fftIdx).real() * matrix(channelIdx, fftIdx).real() + matrix(channelIdx, fftIdx).imag() * matrix(channelIdx, fftIdx).imag()); - } + return sqrt(matrix(channelIdx, fftIdx).real() * matrix(channelIdx, fftIdx).real() + matrix(channelIdx, fftIdx).imag() * matrix(channelIdx, fftIdx).imag()); +} - double phase(const size_t channelIdx, const size_t fftIdx, const MatrixXcd& matrix) - { - return atan2(matrix(channelIdx, fftIdx).imag(), matrix(channelIdx, fftIdx).real()); - } +double phase(const size_t channelIdx, const size_t fftIdx, const MatrixXcd& matrix) +{ + return atan2(matrix(channelIdx, fftIdx).imag(), matrix(channelIdx, fftIdx).real()); +} - double realPart(const size_t channelIdx, const size_t fftIdx, const MatrixXcd& matrix) { return matrix(channelIdx, fftIdx).real(); } +double realPart(const size_t channelIdx, const size_t fftIdx, const MatrixXcd& matrix) { return matrix(channelIdx, fftIdx).real(); } - double imaginaryPart(const size_t channelIdx, const size_t fftIdx, const MatrixXcd& matrix) { return matrix(channelIdx, fftIdx).imag(); } -} // namespace +double imaginaryPart(const size_t channelIdx, const size_t fftIdx, const MatrixXcd& matrix) { return matrix(channelIdx, fftIdx).imag(); } +} // namespace bool CBoxAlgorithmSpectralAnalysis::initialize() { @@ -64,11 +62,8 @@ bool CBoxAlgorithmSpectralAnalysis::initialize() } this->getLogManager() << LogLevel_Trace << "Spectral components selected : [ " - << (m_isSpectrumEncoderActive[0] ? CString("AMP ") : "") - << (m_isSpectrumEncoderActive[1] ? CString("PHASE ") : "") - << (m_isSpectrumEncoderActive[2] ? CString("REAL ") : "") - << (m_isSpectrumEncoderActive[3] ? CString("IMG ") : "") - << "]\n"; + << (m_isSpectrumEncoderActive[0] ? CString("AMP ") : "") << (m_isSpectrumEncoderActive[1] ? CString("PHASE ") : "") + << (m_isSpectrumEncoderActive[2] ? CString("REAL ") : "") << (m_isSpectrumEncoderActive[3] ? CString("IMG ") : "") << "]\n"; return true; } diff --git a/plugins/processing/signal-processing/src/box-algorithms/spectral-analysis/ovpCBoxAlgorithmSpectralAnalysis.h b/plugins/processing/signal-processing/src/box-algorithms/spectral-analysis/ovpCBoxAlgorithmSpectralAnalysis.h index e188152083c2f4c654fed9153a7c81b39678c56b..a73ac1f1f56eb2a46613c01ba7e5abcf997837b4 100755 --- a/plugins/processing/signal-processing/src/box-algorithms/spectral-analysis/ovpCBoxAlgorithmSpectralAnalysis.h +++ b/plugins/processing/signal-processing/src/box-algorithms/spectral-analysis/ovpCBoxAlgorithmSpectralAnalysis.h @@ -3,75 +3,72 @@ #include "../../ovp_defines.h" #include <toolkit/ovtk_all.h> -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace SignalProcessing { +class CBoxAlgorithmSpectralAnalysis final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm> { - namespace Plugins - { - namespace SignalProcessing - { - class CBoxAlgorithmSpectralAnalysis final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm> - { - public: - void release() override { delete this; } - bool initialize() override; - bool uninitialize() override; - bool processInput(const size_t index) override; - bool process() override; +public: + void release() override { delete this; } + bool initialize() override; + bool uninitialize() override; + bool processInput(const size_t index) override; + bool process() override; - _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_SpectralAnalysis) + _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_SpectralAnalysis) - protected: - Toolkit::TSignalDecoder<CBoxAlgorithmSpectralAnalysis> m_decoder; +protected: + Toolkit::TSignalDecoder<CBoxAlgorithmSpectralAnalysis> m_decoder; - std::vector<Toolkit::TSpectrumEncoder<CBoxAlgorithmSpectralAnalysis> *> m_spectrumEncoders; - std::vector<bool> m_isSpectrumEncoderActive; + std::vector<Toolkit::TSpectrumEncoder<CBoxAlgorithmSpectralAnalysis>*> m_spectrumEncoders; + std::vector<bool> m_isSpectrumEncoderActive; - size_t m_nChannel = 0; - size_t m_nSample = 0; - size_t m_sampling = 0; + size_t m_nChannel = 0; + size_t m_nSample = 0; + size_t m_sampling = 0; - size_t m_sizeFFT = 0; + size_t m_sizeFFT = 0; - IMatrix* m_frequencyAbscissa = nullptr; - }; + IMatrix* m_frequencyAbscissa = nullptr; +}; - class CBoxAlgorithmSpectralAnalysisDesc final : virtual public IBoxAlgorithmDesc - { - public: - void release() override { } - CString getName() const override { return CString("Spectral Analysis"); } - CString getAuthorName() const override { return CString("Laurent Bonnet / Quentin Barthelemy"); } - CString getAuthorCompanyName() const override { return CString("Mensia Technologies SA"); } - CString getShortDescription() const override { return CString("Performs a Spectral Analysis using FFT."); } - CString getDetailedDescription() const override { return CString("Performs a Spectral Analysis using FFT."); } - CString getCategory() const override { return CString("Signal processing/Spectral Analysis"); } - CString getVersion() const override { return CString("1.2"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.1.0"); } - CString getStockItemName() const override { return CString("gtk-execute"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_SpectralAnalysis; } - IPluginObject* create() override { return new CBoxAlgorithmSpectralAnalysis(); } +class CBoxAlgorithmSpectralAnalysisDesc final : virtual public IBoxAlgorithmDesc +{ +public: + void release() override { } + CString getName() const override { return CString("Spectral Analysis"); } + CString getAuthorName() const override { return CString("Laurent Bonnet / Quentin Barthelemy"); } + CString getAuthorCompanyName() const override { return CString("Mensia Technologies SA"); } + CString getShortDescription() const override { return CString("Performs a Spectral Analysis using FFT."); } + CString getDetailedDescription() const override { return CString("Performs a Spectral Analysis using FFT."); } + CString getCategory() const override { return CString("Signal processing/Spectral Analysis"); } + CString getVersion() const override { return CString("1.2"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.1.0"); } + CString getStockItemName() const override { return CString("gtk-execute"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_SpectralAnalysis; } + IPluginObject* create() override { return new CBoxAlgorithmSpectralAnalysis(); } - bool getBoxPrototype(Kernel::IBoxProto& prototype) const override - { - prototype.addInput("Input signal", OV_TypeId_Signal); + bool getBoxPrototype(Kernel::IBoxProto& prototype) const override + { + prototype.addInput("Input signal", OV_TypeId_Signal); - prototype.addOutput("Amplitude", OV_TypeId_Spectrum); - prototype.addOutput("Phase", OV_TypeId_Spectrum); - prototype.addOutput("Real Part", OV_TypeId_Spectrum); - prototype.addOutput("Imaginary Part", OV_TypeId_Spectrum); + prototype.addOutput("Amplitude", OV_TypeId_Spectrum); + prototype.addOutput("Phase", OV_TypeId_Spectrum); + prototype.addOutput("Real Part", OV_TypeId_Spectrum); + prototype.addOutput("Imaginary Part", OV_TypeId_Spectrum); - prototype.addSetting("Amplitude", OV_TypeId_Boolean, "true"); - prototype.addSetting("Phase", OV_TypeId_Boolean, "false"); - prototype.addSetting("Real Part", OV_TypeId_Boolean, "false"); - prototype.addSetting("Imaginary Part", OV_TypeId_Boolean, "false"); + prototype.addSetting("Amplitude", OV_TypeId_Boolean, "true"); + prototype.addSetting("Phase", OV_TypeId_Boolean, "false"); + prototype.addSetting("Real Part", OV_TypeId_Boolean, "false"); + prototype.addSetting("Imaginary Part", OV_TypeId_Boolean, "false"); - return true; - } + return true; + } - _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_SpectralAnalysisDesc) - }; - } // namespace SignalProcessing - } // namespace Plugins + _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_SpectralAnalysisDesc) +}; +} // namespace SignalProcessing +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/signal-processing/src/box-algorithms/spectral-analysis/ovpCBoxAlgorithmSpectrumAverage.h b/plugins/processing/signal-processing/src/box-algorithms/spectral-analysis/ovpCBoxAlgorithmSpectrumAverage.h index c17b331b15b533e1606870456d3ee7c2598548d3..17c7a72ca94bd50798736f2259c39288c9eb59b4 100644 --- a/plugins/processing/signal-processing/src/box-algorithms/spectral-analysis/ovpCBoxAlgorithmSpectrumAverage.h +++ b/plugins/processing/signal-processing/src/box-algorithms/spectral-analysis/ovpCBoxAlgorithmSpectrumAverage.h @@ -5,74 +5,69 @@ #include <toolkit/ovtk_all.h> #include <vector> -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace SignalProcessing { +class CBoxAlgorithmSpectrumAverage final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm> { - namespace Plugins +public: + void release() override { delete this; } + + // virtual uint64_t getClockFrequency(); + bool initialize() override; + bool uninitialize() override; + // virtual bool processClock(Kernel::CMessageClock& msg); + bool processInput(const size_t index) override; + bool process() override; + + _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_SpectrumAverage) + +protected: + + bool m_bZeroCare = false; + + Kernel::IAlgorithmProxy* m_decoder = nullptr; + Kernel::IAlgorithmProxy* m_encoder = nullptr; + + Kernel::TParameterHandler<IMatrix*> ip_matrix; + Kernel::TParameterHandler<IMatrix*> op_matrix; + + Kernel::TParameterHandler<const IMemoryBuffer*> ip_buffer; + Kernel::TParameterHandler<IMemoryBuffer*> op_buffer; + + std::vector<size_t> m_selectedIndices; +}; + +class CBoxAlgorithmSpectrumAverageDesc final : public IBoxAlgorithmDesc +{ +public: + void release() override { } + CString getName() const override { return CString("Spectrum Average"); } + CString getAuthorName() const override { return CString("Yann Renard"); } + CString getAuthorCompanyName() const override { return CString("INRIA"); } + + CString getShortDescription() const override { return CString("Computes the average of all the frequency band powers for a spectrum"); } + + CString getDetailedDescription() const override { return CString(""); } + CString getCategory() const override { return CString("Signal processing/Spectral Analysis"); } + CString getVersion() const override { return CString("1.0"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_SpectrumAverage; } + IPluginObject* create() override { return new CBoxAlgorithmSpectrumAverage; } + + bool getBoxPrototype(Kernel::IBoxProto& prototype) const override { - namespace SignalProcessing - { - class CBoxAlgorithmSpectrumAverage final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm> - { - public: - void release() override { delete this; } - - // virtual uint64_t getClockFrequency(); - bool initialize() override; - bool uninitialize() override; - // virtual bool processEvent(CMessageEvent& messageEvent); - // virtual bool processSignal(CMessageSignal& messageSignal); - // virtual bool processClock(CMessageClock& messageClock); - bool processInput(const size_t index) override; - bool process() override; - - _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_SpectrumAverage) - - protected: - - bool m_bZeroCare = false; - - Kernel::IAlgorithmProxy* m_decoder = nullptr; - Kernel::IAlgorithmProxy* m_encoder = nullptr; - - Kernel::TParameterHandler<IMatrix*> ip_matrix; - Kernel::TParameterHandler<IMatrix*> op_matrix; - - Kernel::TParameterHandler<const IMemoryBuffer*> ip_buffer; - Kernel::TParameterHandler<IMemoryBuffer*> op_buffer; - - std::vector<size_t> m_selectedIndices; - }; - - class CBoxAlgorithmSpectrumAverageDesc final : public IBoxAlgorithmDesc - { - public: - void release() override { } - CString getName() const override { return CString("Spectrum Average"); } - CString getAuthorName() const override { return CString("Yann Renard"); } - CString getAuthorCompanyName() const override { return CString("INRIA"); } - - CString getShortDescription() const override { return CString("Computes the average of all the frequency band powers for a spectrum"); } - - CString getDetailedDescription() const override { return CString(""); } - CString getCategory() const override { return CString("Signal processing/Spectral Analysis"); } - CString getVersion() const override { return CString("1.0"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_SpectrumAverage; } - IPluginObject* create() override { return new CBoxAlgorithmSpectrumAverage; } - - bool getBoxPrototype(Kernel::IBoxProto& prototype) const override - { - prototype.addInput("Spectrum", OV_TypeId_Spectrum); - prototype.addOutput("Spectrum average", OV_TypeId_StreamedMatrix); - prototype.addSetting("Considers zeros", OV_TypeId_Boolean, "false"); - - return true; - } - - _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_SpectrumAverageDesc) - }; - } // namespace SignalProcessing - } // namespace Plugins + prototype.addInput("Spectrum", OV_TypeId_Spectrum); + prototype.addOutput("Spectrum average", OV_TypeId_StreamedMatrix); + prototype.addSetting("Considers zeros", OV_TypeId_Boolean, "false"); + + return true; + } + + _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_SpectrumAverageDesc) +}; +} // namespace SignalProcessing +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/signal-processing/src/ovpCSimpleDSP/ovpCAbstractTree.cpp b/plugins/processing/signal-processing/src/ovpCSimpleDSP/ovpCAbstractTree.cpp index d8e3dd2c44b811b0cebc02125466d5ca8546ac6d..e1a0c9fe719342829393d3d55d5cd2cb98c14837 100644 --- a/plugins/processing/signal-processing/src/ovpCSimpleDSP/ovpCAbstractTree.cpp +++ b/plugins/processing/signal-processing/src/ovpCSimpleDSP/ovpCAbstractTree.cpp @@ -33,7 +33,7 @@ void CAbstractTree::simplifyTree() } // Dirty hack to avoid GCC 4.3 crash at compilation time -static void ClearChildren(std::vector<CAbstractTreeNode *>& children) { for (size_t i = 0; i < children.size(); ++i) { delete children[i]; } } +static void ClearChildren(std::vector<CAbstractTreeNode*>& children) { for (size_t i = 0; i < children.size(); ++i) { delete children[i]; } } CAbstractTreeParentNode::~CAbstractTreeParentNode() { @@ -189,7 +189,6 @@ bool CAbstractTreeParentNode::simplify(CAbstractTreeNode*& node) //binary operator not associative else if (nChildren == 2 && !isAssociative()) { - //if we can already compute the result if (m_Children[0]->isConstant() && m_Children[1]->isConstant()) { @@ -252,7 +251,7 @@ bool CAbstractTreeParentNode::simplify(CAbstractTreeNode*& node) sort(m_Children.begin(), m_Children.end(), CAbstractTreeNodeOrderingFunction()); //the new children if there are changes - vector<CAbstractTreeNode *> newChildren; + vector<CAbstractTreeNode*> newChildren; //iterator on the children size_t i = 0; @@ -429,11 +428,11 @@ void CAbstractTree::recognizeSpecialTree(uint64_t& treeId, double& parameter) return; } - CAbstractTreeParentNode* parent = reinterpret_cast<CAbstractTreeParentNode *>(m_root); + CAbstractTreeParentNode* parent = reinterpret_cast<CAbstractTreeParentNode*>(m_root); - std::vector<CAbstractTreeNode *>& children = parent->getChildren(); - const size_t nChildren = children.size(); - const uint64_t nodeId = parent->getOperatorIdentifier(); + std::vector<CAbstractTreeNode*>& children = parent->getChildren(); + const size_t nChildren = children.size(); + const uint64_t nodeId = parent->getOperatorIdentifier(); //unary operator/function if (nChildren == 1) { if (children[0]->isTerminal() && !children[0]->isConstant()) { treeId = nodeId; } } diff --git a/plugins/processing/signal-processing/src/ovpCSimpleDSP/ovpCAbstractTree.h b/plugins/processing/signal-processing/src/ovpCSimpleDSP/ovpCAbstractTree.h index 7e787d2c56006c680ff18ba62ddcb32fec1f17c2..0cba7d4afe65afec2f2e3c336f8dbee5c892d8ca 100644 --- a/plugins/processing/signal-processing/src/ovpCSimpleDSP/ovpCAbstractTree.h +++ b/plugins/processing/signal-processing/src/ovpCSimpleDSP/ovpCAbstractTree.h @@ -86,7 +86,7 @@ class CAbstractTreeParentNode : public CAbstractTreeNode public: //! Children of this node - std::vector<CAbstractTreeNode *> m_Children; + std::vector<CAbstractTreeNode*> m_Children; //! The node operator's identifier uint64_t m_ID = 0; @@ -133,7 +133,7 @@ public: * Returns the vector of children of the node. * \return A reference to the vector of children. */ - virtual std::vector<CAbstractTreeNode *>& getChildren() { return m_Children; } + virtual std::vector<CAbstractTreeNode*>& getChildren() { return m_Children; } /** * Adds a child to this node. diff --git a/plugins/processing/signal-processing/src/ovpCSimpleDSP/ovpCEquationParser.cpp b/plugins/processing/signal-processing/src/ovpCSimpleDSP/ovpCEquationParser.cpp index 745243e4d49646cce2279018d6434a58e8c2bd92..b3f46e826eaa255c43381862bbef1e22c775b852 100644 --- a/plugins/processing/signal-processing/src/ovpCSimpleDSP/ovpCEquationParser.cpp +++ b/plugins/processing/signal-processing/src/ovpCSimpleDSP/ovpCEquationParser.cpp @@ -18,25 +18,24 @@ using namespace /*OpenViBE::*/Toolkit; #define _EQ_PARSER_DEBUG_LOG_(level, message) m_parentPlugin.getLogManager() << level << message << "\n"; #define _EQ_PARSER_DEBUG_PRINT_TREE_(level) { m_parentPlugin.getLogManager() << level; m_tree->printTree(m_parentPlugin.getLogManager()); m_parentPlugin.getLogManager() << "\n"; } -namespace +namespace { +// because std::tolower has multiple signatures, +// it can not be easily used in std::transform +// this workaround is taken from http://www.gcek.net/ref/books/sw/cpp/ticppv2/ +template <class TChar> +TChar ToLower(TChar c) { return std::tolower(c); } + +// BOOST::Ast should be able to remove spaces / tabs etc but +// unfortunately, it seems it does not work correcly in some +// cases so I add this sanitizer function to clear the Simple DSP +// equation before sending it to BOOST::Ast +std::string FindAndReplace(std::string s, const std::string& f, const std::string& r) { - // because std::tolower has multiple signatures, - // it can not be easily used in std::transform - // this workaround is taken from http://www.gcek.net/ref/books/sw/cpp/ticppv2/ - template <class TChar> - TChar ToLower(TChar c) { return std::tolower(c); } - - // BOOST::Ast should be able to remove spaces / tabs etc but - // unfortunately, it seems it does not work correcly in some - // cases so I add this sanitizer function to clear the Simple DSP - // equation before sending it to BOOST::Ast - std::string FindAndReplace(std::string s, const std::string& f, const std::string& r) - { - size_t i; - while ((i = s.find(f)) != std::string::npos) { s.replace(i, f.length(), r); } - return s; - } -} // namespace + size_t i; + while ((i = s.find(f)) != std::string::npos) { s.replace(i, f.length(), r); } + return s; +} +} // namespace std::array<functionPointer, 32> CEquationParser::m_functionTable = { diff --git a/plugins/processing/signal-processing/src/ovp_main.cpp b/plugins/processing/signal-processing/src/ovp_main.cpp index bc6ebcaf6b2ca2974ee758535ea8721c593c325e..a86a5eaee88dd0658330764354fe6d5951513ff5 100755 --- a/plugins/processing/signal-processing/src/ovp_main.cpp +++ b/plugins/processing/signal-processing/src/ovp_main.cpp @@ -35,7 +35,8 @@ using namespace /*OpenViBE::*/Plugins; OVP_Declare_Begin() context.getTypeManager().registerEnumerationType(OVP_TypeId_EpochAverageMethod, "Epoch Average method"); context.getTypeManager().registerEnumerationEntry(OVP_TypeId_EpochAverageMethod, "Moving epoch average", size_t(EEpochAverageMethod::Moving)); - context.getTypeManager().registerEnumerationEntry(OVP_TypeId_EpochAverageMethod, "Moving epoch average (Immediate)", size_t(EEpochAverageMethod::MovingImmediate)); + context.getTypeManager().registerEnumerationEntry(OVP_TypeId_EpochAverageMethod, "Moving epoch average (Immediate)", + size_t(EEpochAverageMethod::MovingImmediate)); context.getTypeManager().registerEnumerationEntry(OVP_TypeId_EpochAverageMethod, "Epoch block average", size_t(EEpochAverageMethod::Block)); context.getTypeManager().registerEnumerationEntry(OVP_TypeId_EpochAverageMethod, "Cumulative average", size_t(EEpochAverageMethod::Cumulative)); diff --git a/plugins/processing/stimulation/CMakeLists.txt b/plugins/processing/stimulation/CMakeLists.txt index fa57c0d96c7ce77d0d7af7662c8f84f644984af1..67b603ca643b4b5ec1f8b542bbf16982bba3507b 100755 --- a/plugins/processing/stimulation/CMakeLists.txt +++ b/plugins/processing/stimulation/CMakeLists.txt @@ -11,6 +11,7 @@ ADD_LIBRARY(${PROJECT_NAME} SHARED ${SRC_FILES}) SET_TARGET_PROPERTIES(${PROJECT_NAME} PROPERTIES VERSION ${PROJECT_VERSION} SOVERSION ${PROJECT_VERSION_MAJOR} + FOLDER ${PLUGINS_FOLDER} COMPILE_FLAGS "-DOVP_Exports -DOVP_Shared") INCLUDE("FindOpenViBE") @@ -38,9 +39,7 @@ ENDIF(WIN32) # --------------------------------- # Target macros -# Defines target operating system -# Defines target architecture -# Defines target compiler +# Defines target operating system, architecture and compiler # --------------------------------- SET_BUILD_PLATFORM() diff --git a/plugins/processing/stimulation/src/box-algorithms/ovpCBoxAlgorithmClockStimulator.cpp b/plugins/processing/stimulation/src/box-algorithms/ovpCBoxAlgorithmClockStimulator.cpp index ff4681c49b31c8bef42ed537caff638de747bf68..9edeacbae389d94fce65fca00d49e0dc630ad88e 100644 --- a/plugins/processing/stimulation/src/box-algorithms/ovpCBoxAlgorithmClockStimulator.cpp +++ b/plugins/processing/stimulation/src/box-algorithms/ovpCBoxAlgorithmClockStimulator.cpp @@ -33,7 +33,7 @@ bool CBoxAlgorithmClockStimulator::uninitialize() return true; } -bool CBoxAlgorithmClockStimulator::processClock(IMessageClock& /*messageClock*/) +bool CBoxAlgorithmClockStimulator::processClock(Kernel::CMessageClock& /*msg*/) { getBoxAlgorithmContext()->markAlgorithmAsReadyToProcess(); return true; diff --git a/plugins/processing/stimulation/src/box-algorithms/ovpCBoxAlgorithmClockStimulator.h b/plugins/processing/stimulation/src/box-algorithms/ovpCBoxAlgorithmClockStimulator.h index 09464eaef8e4be87a18147c9019940da3fe9a7b9..29bdcc50a7738a27405442b847f588140f150bd8 100644 --- a/plugins/processing/stimulation/src/box-algorithms/ovpCBoxAlgorithmClockStimulator.h +++ b/plugins/processing/stimulation/src/box-algorithms/ovpCBoxAlgorithmClockStimulator.h @@ -4,62 +4,59 @@ #include <openvibe/ov_all.h> #include <toolkit/ovtk_all.h> -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace Stimulation { +class CBoxAlgorithmClockStimulator final : virtual public Toolkit::TBoxAlgorithm<IBoxAlgorithm> { - namespace Plugins - { - namespace Stimulation - { - class CBoxAlgorithmClockStimulator final : virtual public Toolkit::TBoxAlgorithm<IBoxAlgorithm> - { - public: - void release() override { delete this; } - uint64_t getClockFrequency() override { return (1LL << 32) * 32; } - bool initialize() override; - bool uninitialize() override; - bool processClock(CMessageClock& messageClock) override; - bool process() override; - - _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_ClockStimulator) - - protected: +public: + void release() override { delete this; } + uint64_t getClockFrequency() override { return (1LL << 32) * 32; } + bool initialize() override; + bool uninitialize() override; + bool processClock(Kernel::CMessageClock& msg) override; + bool process() override; - Toolkit::TStimulationEncoder<CBoxAlgorithmClockStimulator> m_encoder; - uint64_t m_stimulationID = 0; - uint64_t m_lastStimulationDate = 0; - uint64_t m_lastEndTime = 0; + _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_ClockStimulator) - uint64_t m_nSentStimulation = 0; - double m_stimulationInterval = 0; - }; +protected: - class CBoxAlgorithmClockStimulatorDesc final : virtual public IBoxAlgorithmDesc - { - public: - void release() override { } - CString getName() const override { return CString("Clock stimulator"); } - CString getAuthorName() const override { return CString("Yann Renard"); } - CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } - CString getShortDescription() const override { return CString("Periodic stimulation generator"); } - CString getDetailedDescription() const override { return CString("Triggers stimulation at fixed frequency"); } - CString getCategory() const override { return CString("Stimulation"); } - CString getVersion() const override { return CString("1.0"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_ClockStimulator; } - IPluginObject* create() override { return new CBoxAlgorithmClockStimulator; } + Toolkit::TStimulationEncoder<CBoxAlgorithmClockStimulator> m_encoder; + uint64_t m_stimulationID = 0; + uint64_t m_lastStimulationDate = 0; + uint64_t m_lastEndTime = 0; - bool getBoxPrototype(Kernel::IBoxProto& prototype) const override - { - prototype.addOutput("Generated stimulations", OV_TypeId_Stimulations); - prototype.addSetting("Interstimulation interval (in sec)", OV_TypeId_Float, "1.0"); - prototype.addSetting("Stimulation", OV_TypeId_Stimulation, "OVTK_StimulationId_Label_00"); - return true; - } + uint64_t m_nSentStimulation = 0; + double m_stimulationInterval = 0; +}; - _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_ClockStimulatorDesc) - }; - } // namespace Stimulation - } // namespace Plugins +class CBoxAlgorithmClockStimulatorDesc final : virtual public IBoxAlgorithmDesc +{ +public: + void release() override { } + CString getName() const override { return CString("Clock stimulator"); } + CString getAuthorName() const override { return CString("Yann Renard"); } + CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } + CString getShortDescription() const override { return CString("Periodic stimulation generator"); } + CString getDetailedDescription() const override { return CString("Triggers stimulation at fixed frequency"); } + CString getCategory() const override { return CString("Stimulation"); } + CString getVersion() const override { return CString("1.0"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_ClockStimulator; } + IPluginObject* create() override { return new CBoxAlgorithmClockStimulator; } + + bool getBoxPrototype(Kernel::IBoxProto& prototype) const override + { + prototype.addOutput("Generated stimulations", OV_TypeId_Stimulations); + prototype.addSetting("Interstimulation interval (in sec)", OV_TypeId_Float, "1.0"); + prototype.addSetting("Stimulation", OV_TypeId_Stimulation, "OVTK_StimulationId_Label_00"); + return true; + } + + _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_ClockStimulatorDesc) +}; +} // namespace Stimulation +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/stimulation/src/box-algorithms/ovpCBoxAlgorithmPlayerController.cpp b/plugins/processing/stimulation/src/box-algorithms/ovpCBoxAlgorithmPlayerController.cpp index 2fa6d975aec2d93f003ba81b59ac9c6376953880..0a9bc47f164fcf7212ab98f2fa7a022d8a2dff27 100644 --- a/plugins/processing/stimulation/src/box-algorithms/ovpCBoxAlgorithmPlayerController.cpp +++ b/plugins/processing/stimulation/src/box-algorithms/ovpCBoxAlgorithmPlayerController.cpp @@ -57,8 +57,7 @@ bool CBoxAlgorithmPlayerController::process() if (stimSet->getStimulationIdentifier(j) == m_stimulationID) { this->getLogManager() << LogLevel_Trace << "Received stimulation [" - << this->getTypeManager().getEnumerationEntryNameFromValue(OV_TypeId_Stimulation, m_stimulationID) << - "] causing action [" + << this->getTypeManager().getEnumerationEntryNameFromValue(OV_TypeId_Stimulation, m_stimulationID) << "] causing action [" << this->getTypeManager().getEnumerationEntryNameFromValue(OV_TypeId_PlayerAction, m_actionID) << "]\n"; bool res = false; @@ -67,9 +66,8 @@ bool CBoxAlgorithmPlayerController::process() if (m_actionID == OV_TypeId_PlayerAction_Pause) { res = this->getPlayerContext().pause(); } if (m_actionID == OV_TypeId_PlayerAction_Forward) { res = this->getPlayerContext().forward(); } - OV_ERROR_UNLESS_KRF(res, - "Failed to request player action [" << this->getTypeManager().getEnumerationEntryNameFromValue(OV_TypeId_PlayerAction, - m_actionID) << "]", + OV_ERROR_UNLESS_KRF(res, "Failed to request player action [" + << this->getTypeManager().getEnumerationEntryNameFromValue(OV_TypeId_PlayerAction, m_actionID) << "]", ErrorType::BadConfig); } } diff --git a/plugins/processing/stimulation/src/box-algorithms/ovpCBoxAlgorithmPlayerController.h b/plugins/processing/stimulation/src/box-algorithms/ovpCBoxAlgorithmPlayerController.h index b010036c21005384c8cc83ea51c8cebf59250b1d..906dd787742a798d34e71160c72da05aa009891c 100644 --- a/plugins/processing/stimulation/src/box-algorithms/ovpCBoxAlgorithmPlayerController.h +++ b/plugins/processing/stimulation/src/box-algorithms/ovpCBoxAlgorithmPlayerController.h @@ -4,63 +4,60 @@ #include <openvibe/ov_all.h> #include <toolkit/ovtk_all.h> -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace Stimulation { +class CBoxAlgorithmPlayerController final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm> { - namespace Plugins - { - namespace Stimulation - { - class CBoxAlgorithmPlayerController final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm> - { - public: - void release() override { delete this; } - bool initialize() override; - bool uninitialize() override; - bool processInput(const size_t index) override; - bool process() override; - - _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_PlayerController) - - protected: +public: + void release() override { delete this; } + bool initialize() override; + bool uninitialize() override; + bool processInput(const size_t index) override; + bool process() override; - Kernel::IAlgorithmProxy* m_decoder = nullptr; - Kernel::TParameterHandler<const IMemoryBuffer*> ip_buffer; - Kernel::TParameterHandler<IStimulationSet*> op_stimulationSet; + _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_PlayerController) - uint64_t m_stimulationID = 0; - uint64_t m_actionID = 0; - }; +protected: - class CBoxAlgorithmPlayerControllerDesc final : public IBoxAlgorithmDesc - { - public: - void release() override { } - CString getName() const override { return CString("Player Controller"); } - CString getAuthorName() const override { return CString("Yann Renard"); } - CString getAuthorCompanyName() const override { return CString("INRIA"); } - CString getShortDescription() const override { return CString("Controls the player execution"); } + Kernel::IAlgorithmProxy* m_decoder = nullptr; + Kernel::TParameterHandler<const IMemoryBuffer*> ip_buffer; + Kernel::TParameterHandler<IStimulationSet*> op_stimulationSet; - CString getDetailedDescription() const override { return CString("Add some settings to configure the way you want to control the player"); } + uint64_t m_stimulationID = 0; + uint64_t m_actionID = 0; +}; - CString getCategory() const override { return CString("Stimulation"); } - CString getVersion() const override { return CString("1.0"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_PlayerController; } - IPluginObject* create() override { return new CBoxAlgorithmPlayerController; } - - bool getBoxPrototype(Kernel::IBoxProto& prototype) const override - { - prototype.addInput("Stimulations", OV_TypeId_Stimulations); - prototype.addSetting("Stimulation name", OV_TypeId_Stimulation, "OVTK_StimulationId_Label_00"); - prototype.addSetting("Action to perform", OV_TypeId_PlayerAction, OV_TypeId_PlayerAction_Pause.toString()); +class CBoxAlgorithmPlayerControllerDesc final : public IBoxAlgorithmDesc +{ +public: + void release() override { } + CString getName() const override { return CString("Player Controller"); } + CString getAuthorName() const override { return CString("Yann Renard"); } + CString getAuthorCompanyName() const override { return CString("INRIA"); } + CString getShortDescription() const override { return CString("Controls the player execution"); } + + CString getDetailedDescription() const override { return CString("Add some settings to configure the way you want to control the player"); } + + CString getCategory() const override { return CString("Stimulation"); } + CString getVersion() const override { return CString("1.0"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_PlayerController; } + IPluginObject* create() override { return new CBoxAlgorithmPlayerController; } + + bool getBoxPrototype(Kernel::IBoxProto& prototype) const override + { + prototype.addInput("Stimulations", OV_TypeId_Stimulations); + prototype.addSetting("Stimulation name", OV_TypeId_Stimulation, "OVTK_StimulationId_Label_00"); + prototype.addSetting("Action to perform", OV_TypeId_PlayerAction, OV_TypeId_PlayerAction_Pause.toString()); - return true; - } + return true; + } - _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_PlayerControllerDesc) - }; - } // namespace Stimulation - } // namespace Plugins + _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_PlayerControllerDesc) +}; +} // namespace Stimulation +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/stimulation/src/box-algorithms/ovpCBoxAlgorithmStimulationMultiplexer.h b/plugins/processing/stimulation/src/box-algorithms/ovpCBoxAlgorithmStimulationMultiplexer.h index 0a920d572027cb2c4cc77cdc3c562ad0c3e138fc..e916388113ce3ea0893dc302157fe7b20897fb51 100644 --- a/plugins/processing/stimulation/src/box-algorithms/ovpCBoxAlgorithmStimulationMultiplexer.h +++ b/plugins/processing/stimulation/src/box-algorithms/ovpCBoxAlgorithmStimulationMultiplexer.h @@ -6,101 +6,98 @@ #include <vector> #include <map> -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace Stimulation { +class CBoxAlgorithmStimulationMultiplexer final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm> { - namespace Plugins +public: + + void release() override { delete this; } + + bool initialize() override; + bool uninitialize() override; + bool processInput(const size_t index) override; + bool process() override; + + _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_StimulationMultiplexer) + +private: + + std::vector<Toolkit::TStimulationDecoder<CBoxAlgorithmStimulationMultiplexer>> m_decoders; + Toolkit::TStimulationEncoder<CBoxAlgorithmStimulationMultiplexer> m_encoder; + + std::vector<uint64_t> m_decoderEndTimes; + + uint64_t m_lastStartTime = 0; + uint64_t m_lastEndTime = 0; + bool m_wasHeaderSent = false; + + std::multimap<uint64_t, std::tuple<uint64_t, uint64_t, uint64_t>> m_stimulations; +}; + +class CBoxAlgorithmStimulationMultiplexerListener final : public Toolkit::TBoxListener<IBoxListener> +{ +public: + + bool check(Kernel::IBox& box) const { - namespace Stimulation + for (size_t input = 0; input < box.getInputCount(); ++input) { - class CBoxAlgorithmStimulationMultiplexer final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm> - { - public: - - void release() override { delete this; } - - bool initialize() override; - bool uninitialize() override; - bool processInput(const size_t index) override; - bool process() override; - - _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_StimulationMultiplexer) - - private: - - std::vector<Toolkit::TStimulationDecoder<CBoxAlgorithmStimulationMultiplexer>> m_decoders; - Toolkit::TStimulationEncoder<CBoxAlgorithmStimulationMultiplexer> m_encoder; - - std::vector<uint64_t> m_decoderEndTimes; - - uint64_t m_lastStartTime = 0; - uint64_t m_lastEndTime = 0; - bool m_wasHeaderSent = false; - - std::multimap<uint64_t, std::tuple<uint64_t, uint64_t, uint64_t>> m_stimulations; - }; - - class CBoxAlgorithmStimulationMultiplexerListener final : public Toolkit::TBoxListener<IBoxListener> - { - public: - - bool check(Kernel::IBox& box) const - { - for (size_t input = 0; input < box.getInputCount(); ++input) - { - box.setInputName(input, ("Input stimulations " + std::to_string(input + 1)).c_str()); - box.setInputType(input, OV_TypeId_Stimulations); - } - - return true; - } - - bool onInputRemoved(Kernel::IBox& box, const size_t /*index*/) override { return this->check(box); } - bool onInputAdded(Kernel::IBox& box, const size_t /*index*/) override { return this->check(box); } - - _IsDerivedFromClass_Final_(Toolkit::TBoxListener<IBoxListener>, OV_UndefinedIdentifier) - }; - - class CBoxAlgorithmStimulationMultiplexerDesc final : public IBoxAlgorithmDesc - { - public: - - void release() override { } - - CString getName() const override { return CString("Stimulation multiplexer"); } - CString getAuthorName() const override { return CString("Yann Renard"); } - CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } - CString getShortDescription() const override { return CString("Merges several stimulation streams into one."); } - - CString getDetailedDescription() const override - { - return CString( - "The stimulations are ordered according to their start date. Thus each time all the input have chunks covering a period of time, a new output chunk is sent. This box may eventually produce output chunk reflecting a different duration depending on the inputs."); - } - - CString getCategory() const override { return CString("Streaming"); } - CString getVersion() const override { return CString("1.1"); } - CString getStockItemName() const override { return CString("gtk-sort-ascending"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } - - CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_StimulationMultiplexer; } - IPluginObject* create() override { return new CBoxAlgorithmStimulationMultiplexer; } - IBoxListener* createBoxListener() const override { return new CBoxAlgorithmStimulationMultiplexerListener; } - void releaseBoxListener(IBoxListener* listener) const override { delete listener; } - - bool getBoxPrototype(Kernel::IBoxProto& prototype) const override - { - prototype.addInput("Input stimulations 1", OV_TypeId_Stimulations); - prototype.addInput("Input stimulations 2", OV_TypeId_Stimulations); - prototype.addOutput("Multiplexed stimulations", OV_TypeId_Stimulations); - prototype.addFlag(Kernel::BoxFlag_CanAddInput); - prototype.addInputSupport(OV_TypeId_Stimulations); - return true; - } - - _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_StimulationMultiplexerDesc) - }; - } // namespace Stimulation - } // namespace Plugins + box.setInputName(input, ("Input stimulations " + std::to_string(input + 1)).c_str()); + box.setInputType(input, OV_TypeId_Stimulations); + } + + return true; + } + + bool onInputRemoved(Kernel::IBox& box, const size_t /*index*/) override { return this->check(box); } + bool onInputAdded(Kernel::IBox& box, const size_t /*index*/) override { return this->check(box); } + + _IsDerivedFromClass_Final_(Toolkit::TBoxListener<IBoxListener>, OV_UndefinedIdentifier) +}; + +class CBoxAlgorithmStimulationMultiplexerDesc final : public IBoxAlgorithmDesc +{ +public: + + void release() override { } + + CString getName() const override { return CString("Stimulation multiplexer"); } + CString getAuthorName() const override { return CString("Yann Renard"); } + CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } + CString getShortDescription() const override { return CString("Merges several stimulation streams into one."); } + + CString getDetailedDescription() const override + { + return CString( + "The stimulations are ordered according to their start date. Thus each time all the input have chunks covering a period of time, a new output chunk is sent. This box may eventually produce output chunk reflecting a different duration depending on the inputs."); + } + + CString getCategory() const override { return CString("Streaming"); } + CString getVersion() const override { return CString("1.1"); } + CString getStockItemName() const override { return CString("gtk-sort-ascending"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } + + CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_StimulationMultiplexer; } + IPluginObject* create() override { return new CBoxAlgorithmStimulationMultiplexer; } + IBoxListener* createBoxListener() const override { return new CBoxAlgorithmStimulationMultiplexerListener; } + void releaseBoxListener(IBoxListener* listener) const override { delete listener; } + + bool getBoxPrototype(Kernel::IBoxProto& prototype) const override + { + prototype.addInput("Input stimulations 1", OV_TypeId_Stimulations); + prototype.addInput("Input stimulations 2", OV_TypeId_Stimulations); + prototype.addOutput("Multiplexed stimulations", OV_TypeId_Stimulations); + prototype.addFlag(Kernel::BoxFlag_CanAddInput); + prototype.addInputSupport(OV_TypeId_Stimulations); + return true; + } + + _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_StimulationMultiplexerDesc) +}; +} // namespace Stimulation +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/stimulation/src/box-algorithms/ovpCBoxAlgorithmStimulationVoter.h b/plugins/processing/stimulation/src/box-algorithms/ovpCBoxAlgorithmStimulationVoter.h index 86b39ff2616f5647eaf1bdd2ac911e7b26e804cc..cd92c03b24482b7241974bd06700e08012d4759e 100644 --- a/plugins/processing/stimulation/src/box-algorithms/ovpCBoxAlgorithmStimulationVoter.h +++ b/plugins/processing/stimulation/src/box-algorithms/ovpCBoxAlgorithmStimulationVoter.h @@ -7,101 +7,98 @@ #include <map> #include <deque> -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace Stimulation { +class CBoxAlgorithmStimulationVoter final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm> { - namespace Plugins +public: + void release() override { delete this; } + bool initialize() override; + bool uninitialize() override; + bool processInput(const size_t index) override; + bool process() override; + + _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_StimulationVoter) + +protected: + + uint64_t m_minimumVotes = 0; + double m_timeWindow = 0; + uint64_t m_rejectClassLabel = 0; + CIdentifier m_clearVotes = OV_UndefinedIdentifier; + CIdentifier m_outputDateMode = OV_UndefinedIdentifier; + CIdentifier m_rejectClassCanWin = OV_UndefinedIdentifier; + +private: + + Kernel::IAlgorithmProxy* m_encoder = nullptr; + Kernel::IAlgorithmProxy* m_decoder = nullptr; + Kernel::TParameterHandler<const IMemoryBuffer*> ip_buffer; + Kernel::TParameterHandler<IStimulationSet*> op_stimulationSet; + + std::deque<std::pair<uint64_t, uint64_t>> m_oStimulusDeque; // <label,time> + + uint64_t m_latestStimulusDate = 0; + uint64_t m_lastTime = 0; +}; + + +class CBoxAlgorithmStimulationVoterListener final : public Toolkit::TBoxListener<IBoxListener> +{ +public: + + CBoxAlgorithmStimulationVoterListener() : m_inputTypeID(OV_TypeId_Stimulations) { } + + _IsDerivedFromClass_Final_(Toolkit::TBoxListener<IBoxListener>, OV_UndefinedIdentifier) + +protected: + + CIdentifier m_inputTypeID = OV_UndefinedIdentifier; +}; + +class CBoxAlgorithmStimulationVoterDesc final : public IBoxAlgorithmDesc +{ +public: + void release() override { } + CString getName() const override { return CString("Stimulation Voter"); } + CString getAuthorName() const override { return CString("Jussi T. Lindgren"); } + CString getAuthorCompanyName() const override { return CString("Inria"); } + CString getShortDescription() const override { return CString("Performs majority vote on the input stimuli"); } + + CString getDetailedDescription() const override + { + return CString( + "Votes the most frequent stimulus ID in a given time window. Outputs the winning stimulus type. Several options are possible. To process multiple inputs, use Stimulation Multiplexer first."); + } + + CString getCategory() const override { return CString("Streaming"); } + CString getVersion() const override { return CString("1.0"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_StimulationVoter; } + IPluginObject* create() override { return new CBoxAlgorithmStimulationVoter; } + + bool getBoxPrototype(Kernel::IBoxProto& prototype) const override { - namespace Stimulation - { - class CBoxAlgorithmStimulationVoter final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm> - { - public: - void release() override { delete this; } - bool initialize() override; - bool uninitialize() override; - bool processInput(const size_t index) override; - bool process() override; - - _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_StimulationVoter) - - protected: - - uint64_t m_minimumVotes = 0; - double m_timeWindow = 0; - uint64_t m_rejectClassLabel = 0; - CIdentifier m_clearVotes = OV_UndefinedIdentifier; - CIdentifier m_outputDateMode = OV_UndefinedIdentifier; - CIdentifier m_rejectClassCanWin = OV_UndefinedIdentifier; - - private: - - Kernel::IAlgorithmProxy* m_encoder = nullptr; - Kernel::IAlgorithmProxy* m_decoder = nullptr; - Kernel::TParameterHandler<const IMemoryBuffer*> ip_buffer; - Kernel::TParameterHandler<IStimulationSet*> op_stimulationSet; - - std::deque<std::pair<uint64_t, uint64_t>> m_oStimulusDeque; // <label,time> - - uint64_t m_latestStimulusDate = 0; - uint64_t m_lastTime = 0; - }; - - - class CBoxAlgorithmStimulationVoterListener final : public Toolkit::TBoxListener<IBoxListener> - { - public: - - CBoxAlgorithmStimulationVoterListener() : m_inputTypeID(OV_TypeId_Stimulations) { } - - _IsDerivedFromClass_Final_(Toolkit::TBoxListener<IBoxListener>, OV_UndefinedIdentifier) - - protected: - - CIdentifier m_inputTypeID = OV_UndefinedIdentifier; - }; - - class CBoxAlgorithmStimulationVoterDesc final : public IBoxAlgorithmDesc - { - public: - void release() override { } - CString getName() const override { return CString("Stimulation Voter"); } - CString getAuthorName() const override { return CString("Jussi T. Lindgren"); } - CString getAuthorCompanyName() const override { return CString("Inria"); } - CString getShortDescription() const override { return CString("Performs majority vote on the input stimuli"); } - - CString getDetailedDescription() const override - { - return CString( - "Votes the most frequent stimulus ID in a given time window. Outputs the winning stimulus type. Several options are possible. To process multiple inputs, use Stimulation Multiplexer first."); - } - - CString getCategory() const override { return CString("Streaming"); } - CString getVersion() const override { return CString("1.0"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_StimulationVoter; } - IPluginObject* create() override { return new CBoxAlgorithmStimulationVoter; } - - bool getBoxPrototype(Kernel::IBoxProto& prototype) const override - { - prototype.addInput("Stimulus input", OV_TypeId_Stimulations); - prototype.addOutput("Selected stimulus", OV_TypeId_Stimulations); - prototype.addSetting("Number of stimuli required for vote", OV_TypeId_Integer, "4"); - prototype.addSetting("Time window (secs)", OV_TypeId_Float, "2"); - prototype.addSetting("Clear votes", OVP_TypeId_Voting_ClearVotes, "After output"); - prototype.addSetting("Output timestamp", OVP_TypeId_Voting_OutputTime, "Time of last voting stimulus"); - prototype.addSetting("Reject class label", OV_TypeId_Stimulation, "OVTK_StimulationId_Label_00"); - prototype.addSetting("Reject class can win", OVP_TypeId_Voting_RejectClass_CanWin, "No"); - - return true; - } - - IBoxListener* createBoxListener() const override { return new CBoxAlgorithmStimulationVoterListener; } - void releaseBoxListener(IBoxListener* listener) const override { delete listener; } - - _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_StimulationVoterDesc) - }; - } // namespace Stimulation - } // namespace Plugins + prototype.addInput("Stimulus input", OV_TypeId_Stimulations); + prototype.addOutput("Selected stimulus", OV_TypeId_Stimulations); + prototype.addSetting("Number of stimuli required for vote", OV_TypeId_Integer, "4"); + prototype.addSetting("Time window (secs)", OV_TypeId_Float, "2"); + prototype.addSetting("Clear votes", OVP_TypeId_Voting_ClearVotes, "After output"); + prototype.addSetting("Output timestamp", OVP_TypeId_Voting_OutputTime, "Time of last voting stimulus"); + prototype.addSetting("Reject class label", OV_TypeId_Stimulation, "OVTK_StimulationId_Label_00"); + prototype.addSetting("Reject class can win", OVP_TypeId_Voting_RejectClass_CanWin, "No"); + + return true; + } + + IBoxListener* createBoxListener() const override { return new CBoxAlgorithmStimulationVoterListener; } + void releaseBoxListener(IBoxListener* listener) const override { delete listener; } + + _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_StimulationVoterDesc) +}; +} // namespace Stimulation +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/stimulation/src/box-algorithms/ovpCBoxAlgorithmStreamEndDetector.h b/plugins/processing/stimulation/src/box-algorithms/ovpCBoxAlgorithmStreamEndDetector.h index 210b0495f7bed10d411bc85e0b1442e41e3c92df..b8b7c7436e62e7d8ac102cc46da7dd0c166f1188 100644 --- a/plugins/processing/stimulation/src/box-algorithms/ovpCBoxAlgorithmStreamEndDetector.h +++ b/plugins/processing/stimulation/src/box-algorithms/ovpCBoxAlgorithmStreamEndDetector.h @@ -4,81 +4,78 @@ #include <openvibe/ov_all.h> #include <toolkit/ovtk_all.h> -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace Stimulation { +class CBoxAlgorithmStreamEndDetector final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm> { - namespace Plugins - { - namespace Stimulation - { - class CBoxAlgorithmStreamEndDetector final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm> - { - public: - static CIdentifier inputEBMLId() { return CIdentifier(0x0, 0x1); } - static CIdentifier outputStimulationsID() { return CIdentifier(0x1, 0x1); } - static CIdentifier settingStimulationNameID() { return CIdentifier(0x2, 0x1); } - void release() override { delete this; } - bool initialize() override; - bool uninitialize() override; - bool processInput(const size_t index) override; - bool process() override; +public: + static CIdentifier inputEBMLId() { return CIdentifier(0x0, 0x1); } + static CIdentifier outputStimulationsID() { return CIdentifier(0x1, 0x1); } + static CIdentifier settingStimulationNameID() { return CIdentifier(0x2, 0x1); } + void release() override { delete this; } + bool initialize() override; + bool uninitialize() override; + bool processInput(const size_t index) override; + bool process() override; - _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_StreamEndDetector) + _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_StreamEndDetector) - protected: +protected: - Toolkit::TStreamStructureDecoder<CBoxAlgorithmStreamEndDetector> m_decoder; - Toolkit::TStimulationEncoder<CBoxAlgorithmStreamEndDetector> m_encoder; + Toolkit::TStreamStructureDecoder<CBoxAlgorithmStreamEndDetector> m_decoder; + Toolkit::TStimulationEncoder<CBoxAlgorithmStreamEndDetector> m_encoder; - uint64_t m_stimulationID = 0; - uint64_t m_actionID = 0; + uint64_t m_stimulationID = 0; + uint64_t m_actionID = 0; - private: - enum class EEndState - { - WaitingForEnd, - EndReceived, - StimulationSent, - Finished - }; +private: + enum class EEndState + { + WaitingForEnd, + EndReceived, + StimulationSent, + Finished + }; - uint64_t m_endDate = 0; - uint64_t m_currentChunkEndDate = 0; - uint64_t m_previousTime = 0; - size_t m_inputEBMLIdx = 0; - size_t m_outputStimulationsIdx = 0; - bool m_isHeaderSent = false; - EEndState m_endState = EEndState::WaitingForEnd; - }; + uint64_t m_endDate = 0; + uint64_t m_currentChunkEndDate = 0; + uint64_t m_previousTime = 0; + size_t m_inputEBMLIdx = 0; + size_t m_outputStimulationsIdx = 0; + bool m_isHeaderSent = false; + EEndState m_endState = EEndState::WaitingForEnd; +}; - class CBoxAlgorithmStreamEndDetectorDesc final : public IBoxAlgorithmDesc - { - public: - void release() override { } - CString getName() const override { return CString("Stream End Detector"); } - CString getAuthorName() const override { return CString("Jozef Legeny"); } - CString getAuthorCompanyName() const override { return CString("Mensia Technologies"); } - CString getShortDescription() const override { return CString("Sends a stimulation upon receiving an End chunk"); } - CString getDetailedDescription() const override { return CString("Sends a stimulation upon receiving an End chunk"); } - CString getCategory() const override { return CString("Stimulation"); } - CString getVersion() const override { return CString("1.0"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("2.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_StreamEndDetector; } - IPluginObject* create() override { return new CBoxAlgorithmStreamEndDetector; } +class CBoxAlgorithmStreamEndDetectorDesc final : public IBoxAlgorithmDesc +{ +public: + void release() override { } + CString getName() const override { return CString("Stream End Detector"); } + CString getAuthorName() const override { return CString("Jozef Legeny"); } + CString getAuthorCompanyName() const override { return CString("Mensia Technologies"); } + CString getShortDescription() const override { return CString("Sends a stimulation upon receiving an End chunk"); } + CString getDetailedDescription() const override { return CString("Sends a stimulation upon receiving an End chunk"); } + CString getCategory() const override { return CString("Stimulation"); } + CString getVersion() const override { return CString("1.0"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("2.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_StreamEndDetector; } + IPluginObject* create() override { return new CBoxAlgorithmStreamEndDetector; } - bool getBoxPrototype(Kernel::IBoxProto& prototype) const override - { - prototype.addInput("EBML Stream", OV_TypeId_EBMLStream, CBoxAlgorithmStreamEndDetector::inputEBMLId()); - prototype.addOutput("Output Stimulations", OV_TypeId_Stimulations, CBoxAlgorithmStreamEndDetector::outputStimulationsID()); - prototype.addSetting("Stimulation name", OV_TypeId_Stimulation, "OVTK_StimulationId_Label_00", false, - CBoxAlgorithmStreamEndDetector::settingStimulationNameID()); + bool getBoxPrototype(Kernel::IBoxProto& prototype) const override + { + prototype.addInput("EBML Stream", OV_TypeId_EBMLStream, CBoxAlgorithmStreamEndDetector::inputEBMLId()); + prototype.addOutput("Output Stimulations", OV_TypeId_Stimulations, CBoxAlgorithmStreamEndDetector::outputStimulationsID()); + prototype.addSetting("Stimulation name", OV_TypeId_Stimulation, "OVTK_StimulationId_Label_00", false, + CBoxAlgorithmStreamEndDetector::settingStimulationNameID()); - return true; - } + return true; + } - _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_StreamEndDetectorDesc) - }; - } // namespace Stimulation - } // namespace Plugins + _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_StreamEndDetectorDesc) +}; +} // namespace Stimulation +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/stimulation/src/box-algorithms/ovpCBoxAlgorithmTimeout.cpp b/plugins/processing/stimulation/src/box-algorithms/ovpCBoxAlgorithmTimeout.cpp index 142c63685893ac96a3dbd091c7eadc684a29dfdb..8a7bf45aa5c9197ef35a3bbe1f558f818f173850 100644 --- a/plugins/processing/stimulation/src/box-algorithms/ovpCBoxAlgorithmTimeout.cpp +++ b/plugins/processing/stimulation/src/box-algorithms/ovpCBoxAlgorithmTimeout.cpp @@ -35,8 +35,7 @@ bool CBoxAlgorithmTimeout::uninitialize() } /*******************************************************************************/ - -bool CBoxAlgorithmTimeout::processClock(Kernel::IMessageClock& /*messageClock*/) +bool CBoxAlgorithmTimeout::processClock(Kernel::CMessageClock& /*msg*/) { // if there was nothing received on the input for a period of time we raise the // timeout flag and let the box send a stimulation @@ -52,14 +51,9 @@ bool CBoxAlgorithmTimeout::processClock(Kernel::IMessageClock& /*messageClock*/) } /*******************************************************************************/ - -uint64_t CBoxAlgorithmTimeout::getClockFrequency() -{ - return 16LL << 32; // the box clock frequency -} +uint64_t CBoxAlgorithmTimeout::getClockFrequency() { return 16LL << 32; } // the box clock frequency /*******************************************************************************/ - bool CBoxAlgorithmTimeout::processInput(const size_t /*index*/) { this->getBoxAlgorithmContext()->markAlgorithmAsReadyToProcess(); @@ -107,6 +101,6 @@ bool CBoxAlgorithmTimeout::process() return true; } -} // namespace Stimulation -} // namespace Plugins -} // namespace OpenViBE +} // namespace Stimulation +} // namespace Plugins +} // namespace OpenViBE diff --git a/plugins/processing/stimulation/src/box-algorithms/ovpCBoxAlgorithmTimeout.h b/plugins/processing/stimulation/src/box-algorithms/ovpCBoxAlgorithmTimeout.h index 20ee76a6e1137a99365b6466e4af5b6d3dedaa77..c986ae87ab2f710124054e9acd76420c653ffb08 100644 --- a/plugins/processing/stimulation/src/box-algorithms/ovpCBoxAlgorithmTimeout.h +++ b/plugins/processing/stimulation/src/box-algorithms/ovpCBoxAlgorithmTimeout.h @@ -22,7 +22,7 @@ public: void release() override { delete this; } bool initialize() override; bool uninitialize() override; - bool processClock(CMessageClock& messageClock) override; + bool processClock(Kernel::CMessageClock& msg) override; bool processInput(const size_t index) override; uint64_t getClockFrequency() override; bool process() override; @@ -87,6 +87,6 @@ public: _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_TimeoutDesc) }; -} // namespace Stimulation -} // namespace Plugins -} // namespace OpenViBE +} // namespace Stimulation +} // namespace Plugins +} // namespace OpenViBE diff --git a/plugins/processing/stream-codecs/CMakeLists.txt b/plugins/processing/stream-codecs/CMakeLists.txt index 9d6d046a4cc15093494440cbaab69bf55223e2c1..314a31840659a4d07dc200948623cbc343661398 100644 --- a/plugins/processing/stream-codecs/CMakeLists.txt +++ b/plugins/processing/stream-codecs/CMakeLists.txt @@ -11,6 +11,7 @@ ADD_LIBRARY(${PROJECT_NAME} SHARED ${SRC_FILES}) SET_TARGET_PROPERTIES(${PROJECT_NAME} PROPERTIES VERSION ${PROJECT_VERSION} SOVERSION ${PROJECT_VERSION_MAJOR} + FOLDER ${PLUGINS_FOLDER} COMPILE_FLAGS "-DOVP_Exports -DOVP_Shared") # --------------------------------- @@ -21,9 +22,7 @@ INCLUDE("FindOpenViBEModuleEBML") # --------------------------------- # Target macros -# Defines target operating system -# Defines target architecture -# Defines target compiler +# Defines target operating system, architecture and compiler # --------------------------------- SET_BUILD_PLATFORM() diff --git a/plugins/processing/stream-codecs/src/algorithms/decoders/ovpCAcquisitionDecoder.h b/plugins/processing/stream-codecs/src/algorithms/decoders/ovpCAcquisitionDecoder.h index 8ad151f695f975c72ed4e2ac88e91b5c8da5ff3b..26a0355cddf4178e7f46c9ee513d029935adcffb 100644 --- a/plugins/processing/stream-codecs/src/algorithms/decoders/ovpCAcquisitionDecoder.h +++ b/plugins/processing/stream-codecs/src/algorithms/decoders/ovpCAcquisitionDecoder.h @@ -4,86 +4,79 @@ #include "ovpCEBMLBaseDecoder.h" #include <stack> -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace StreamCodecs { +class CAcquisitionDecoder final : public CEBMLBaseDecoder { - namespace Plugins - { - namespace StreamCodecs - { - class CAcquisitionDecoder final : public CEBMLBaseDecoder - { - public: +public: - CAcquisitionDecoder(); - void release() override { delete this; } - bool initialize() override; - bool uninitialize() override; + CAcquisitionDecoder(); + void release() override { delete this; } + bool initialize() override; + bool uninitialize() override; - _IsDerivedFromClass_Final_(StreamCodecs::CEBMLBaseDecoder, OVP_ClassId_Algorithm_AcquisitionDecoder) + _IsDerivedFromClass_Final_(StreamCodecs::CEBMLBaseDecoder, OVP_ClassId_Algorithm_AcquisitionDecoder) - // ebml callbacks - bool isMasterChild(const EBML::CIdentifier& identifier) override; - void openChild(const EBML::CIdentifier& identifier) override; - void processChildData(const void* buffer, const size_t size) override; - void closeChild() override; + // ebml callbacks + bool isMasterChild(const EBML::CIdentifier& identifier) override; + void openChild(const EBML::CIdentifier& identifier) override; + void processChildData(const void* buffer, const size_t size) override; + void closeChild() override; - protected: +protected: - static void appendMemoryBuffer(IMemoryBuffer* memoryBuffer, const void* buffer, size_t size); + static void appendMemoryBuffer(IMemoryBuffer* memoryBuffer, const void* buffer, size_t size); - Kernel::TParameterHandler<uint64_t> op_bufferDuration; - Kernel::TParameterHandler<IMemoryBuffer*> op_experimentInfoStream; - Kernel::TParameterHandler<IMemoryBuffer*> op_signalStream; - Kernel::TParameterHandler<IMemoryBuffer*> op_stimulationStream; - Kernel::TParameterHandler<IMemoryBuffer*> op_channelLocalisationStream; - Kernel::TParameterHandler<IMemoryBuffer*> op_channelUnitsStream; + Kernel::TParameterHandler<uint64_t> op_bufferDuration; + Kernel::TParameterHandler<IMemoryBuffer*> op_experimentInfoStream; + Kernel::TParameterHandler<IMemoryBuffer*> op_signalStream; + Kernel::TParameterHandler<IMemoryBuffer*> op_stimulationStream; + Kernel::TParameterHandler<IMemoryBuffer*> op_channelLocalisationStream; + Kernel::TParameterHandler<IMemoryBuffer*> op_channelUnitsStream; - private: +private: - std::stack<EBML::CIdentifier> m_nodes; - }; + std::stack<EBML::CIdentifier> m_nodes; +}; - class CAcquisitionDecoderDesc final : public CEBMLBaseDecoderDesc - { - public: - void release() override { } - CString getName() const override { return CString("Acquisition stream decoder"); } - CString getAuthorName() const override { return CString("Yann Renard"); } - CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } - CString getShortDescription() const override { return CString(""); } - CString getDetailedDescription() const override { return CString(""); } - CString getCategory() const override { return CString("Stream codecs/Decoders"); } - CString getVersion() const override { return CString("1.1"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_Algorithm_AcquisitionDecoder; } - IPluginObject* create() override { return new CAcquisitionDecoder(); } +class CAcquisitionDecoderDesc final : public CEBMLBaseDecoderDesc +{ +public: + void release() override { } + CString getName() const override { return CString("Acquisition stream decoder"); } + CString getAuthorName() const override { return CString("Yann Renard"); } + CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } + CString getShortDescription() const override { return CString(""); } + CString getDetailedDescription() const override { return CString(""); } + CString getCategory() const override { return CString("Stream codecs/Decoders"); } + CString getVersion() const override { return CString("1.1"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_Algorithm_AcquisitionDecoder; } + IPluginObject* create() override { return new CAcquisitionDecoder(); } - bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override - { - CEBMLBaseDecoderDesc::getAlgorithmPrototype(prototype); + bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override + { + CEBMLBaseDecoderDesc::getAlgorithmPrototype(prototype); - prototype.addOutputParameter( - OVP_Algorithm_AcquisitionDecoder_OutputParameterId_BufferDuration, "Buffer duration", Kernel::ParameterType_UInteger); - prototype.addOutputParameter( - OVP_Algorithm_AcquisitionDecoder_OutputParameterId_ExperimentInfoStream, "Experiment information stream", - Kernel::ParameterType_MemoryBuffer); - prototype.addOutputParameter( - OVP_Algorithm_AcquisitionDecoder_OutputParameterId_SignalStream, "Signal stream", Kernel::ParameterType_MemoryBuffer); - prototype.addOutputParameter( - OVP_Algorithm_AcquisitionDecoder_OutputParameterId_StimulationStream, "Stimulation stream", Kernel::ParameterType_MemoryBuffer); - prototype.addOutputParameter( - OVP_Algorithm_AcquisitionDecoder_OutputParameterId_ChannelLocalisationStream, "Channel localisation stream", - Kernel::ParameterType_MemoryBuffer); - prototype.addOutputParameter( - OVP_Algorithm_AcquisitionDecoder_OutputParameterId_ChannelUnitsStream, "Channel units stream", Kernel::ParameterType_MemoryBuffer); + prototype.addOutputParameter(OVP_Algorithm_AcquisitionDecoder_OutputParameterId_BufferDuration, "Buffer duration", Kernel::ParameterType_UInteger); + prototype.addOutputParameter(OVP_Algorithm_AcquisitionDecoder_OutputParameterId_ExperimentInfoStream, "Experiment information stream", + Kernel::ParameterType_MemoryBuffer); + prototype.addOutputParameter(OVP_Algorithm_AcquisitionDecoder_OutputParameterId_SignalStream, "Signal stream", Kernel::ParameterType_MemoryBuffer); + prototype.addOutputParameter(OVP_Algorithm_AcquisitionDecoder_OutputParameterId_StimulationStream, "Stimulation stream", + Kernel::ParameterType_MemoryBuffer); + prototype.addOutputParameter(OVP_Algorithm_AcquisitionDecoder_OutputParameterId_ChannelLocalisationStream, "Channel localisation stream", + Kernel::ParameterType_MemoryBuffer); + prototype.addOutputParameter(OVP_Algorithm_AcquisitionDecoder_OutputParameterId_ChannelUnitsStream, "Channel units stream", + Kernel::ParameterType_MemoryBuffer); - return true; - } + return true; + } - _IsDerivedFromClass_Final_(StreamCodecs::CEBMLBaseDecoderDesc, OVP_ClassId_Algorithm_AcquisitionDecoderDesc) - }; - } // namespace StreamCodecs - } // namespace Plugins + _IsDerivedFromClass_Final_(StreamCodecs::CEBMLBaseDecoderDesc, OVP_ClassId_Algorithm_AcquisitionDecoderDesc) +}; +} // namespace StreamCodecs +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/stream-codecs/src/algorithms/decoders/ovpCChannelLocalisationDecoder.cpp b/plugins/processing/stream-codecs/src/algorithms/decoders/ovpCChannelLocalisationDecoder.cpp index 2212ed00d05a0b577476417cc39491f2110e9e9e..f006aa4563aacd03283429ed5081aac2ff11fd2e 100644 --- a/plugins/processing/stream-codecs/src/algorithms/decoders/ovpCChannelLocalisationDecoder.cpp +++ b/plugins/processing/stream-codecs/src/algorithms/decoders/ovpCChannelLocalisationDecoder.cpp @@ -11,18 +11,14 @@ using namespace StreamCodecs; bool CChannelLocalisationDecoder::initialize() { CStreamedMatrixDecoder::initialize(); - op_bDynamic.initialize(getOutputParameter(OVP_Algorithm_ChannelLocalisationDecoder_OutputParameterId_Dynamic)); - return true; } bool CChannelLocalisationDecoder::uninitialize() { op_bDynamic.uninitialize(); - CStreamedMatrixDecoder::uninitialize(); - return true; } @@ -50,8 +46,7 @@ void CChannelLocalisationDecoder::processChildData(const void* buffer, const siz { EBML::CIdentifier& top = m_nodes.top(); - if ((top == OVTK_NodeId_Header_ChannelLocalisation) - || (top == OVTK_NodeId_Header_ChannelLocalisation_Dynamic)) + if ((top == OVTK_NodeId_Header_ChannelLocalisation) || (top == OVTK_NodeId_Header_ChannelLocalisation_Dynamic)) { if (top == OVTK_NodeId_Header_ChannelLocalisation_Dynamic) { op_bDynamic = (m_readerHelper->getUInt(buffer, size) ? true : false); } } @@ -62,8 +57,7 @@ void CChannelLocalisationDecoder::closeChild() { EBML::CIdentifier& top = m_nodes.top(); - if ((top == OVTK_NodeId_Header_ChannelLocalisation) - || (top == OVTK_NodeId_Header_ChannelLocalisation_Dynamic)) { } + if ((top == OVTK_NodeId_Header_ChannelLocalisation) || (top == OVTK_NodeId_Header_ChannelLocalisation_Dynamic)) { } else { CStreamedMatrixDecoder::closeChild(); } m_nodes.pop(); diff --git a/plugins/processing/stream-codecs/src/algorithms/decoders/ovpCChannelLocalisationDecoder.h b/plugins/processing/stream-codecs/src/algorithms/decoders/ovpCChannelLocalisationDecoder.h index aa7abf758d493f304a0221b3c67fd3e24d9a8bdf..27725d7aa5fcd5ef331d58f857ad68d5b9f6d4c7 100644 --- a/plugins/processing/stream-codecs/src/algorithms/decoders/ovpCChannelLocalisationDecoder.h +++ b/plugins/processing/stream-codecs/src/algorithms/decoders/ovpCChannelLocalisationDecoder.h @@ -4,64 +4,61 @@ #include "ovpCStreamedMatrixDecoder.h" #include <stack> -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace StreamCodecs { +class CChannelLocalisationDecoder final : public CStreamedMatrixDecoder { - namespace Plugins - { - namespace StreamCodecs - { - class CChannelLocalisationDecoder final : public CStreamedMatrixDecoder - { - public: - void release() override { delete this; } - bool initialize() override; - bool uninitialize() override; +public: + void release() override { delete this; } + bool initialize() override; + bool uninitialize() override; - _IsDerivedFromClass_Final_(StreamCodecs::CStreamedMatrixDecoder, OVP_ClassId_Algorithm_ChannelLocalisationDecoder) + _IsDerivedFromClass_Final_(StreamCodecs::CStreamedMatrixDecoder, OVP_ClassId_Algorithm_ChannelLocalisationDecoder) - // ebml callbacks - bool isMasterChild(const EBML::CIdentifier& identifier) override; - void openChild(const EBML::CIdentifier& identifier) override; - void processChildData(const void* buffer, const size_t size) override; - void closeChild() override; + // ebml callbacks + bool isMasterChild(const EBML::CIdentifier& identifier) override; + void openChild(const EBML::CIdentifier& identifier) override; + void processChildData(const void* buffer, const size_t size) override; + void closeChild() override; - protected: +protected: - Kernel::TParameterHandler<bool> op_bDynamic; + Kernel::TParameterHandler<bool> op_bDynamic; - private: +private: - std::stack<EBML::CIdentifier> m_nodes; - }; + std::stack<EBML::CIdentifier> m_nodes; +}; - class CChannelLocalisationDecoderDesc final : public CStreamedMatrixDecoderDesc - { - public: - void release() override { } - CString getName() const override { return CString("Channel localisation stream decoder"); } - CString getAuthorName() const override { return CString("Yann Renard"); } - CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } - CString getShortDescription() const override { return CString(""); } - CString getDetailedDescription() const override { return CString(""); } - CString getCategory() const override { return CString("Stream codecs/Decoders"); } - CString getVersion() const override { return CString("1.0"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_Algorithm_ChannelLocalisationDecoder; } - IPluginObject* create() override { return new CChannelLocalisationDecoder(); } +class CChannelLocalisationDecoderDesc final : public CStreamedMatrixDecoderDesc +{ +public: + void release() override { } + CString getName() const override { return CString("Channel localisation stream decoder"); } + CString getAuthorName() const override { return CString("Yann Renard"); } + CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } + CString getShortDescription() const override { return CString(""); } + CString getDetailedDescription() const override { return CString(""); } + CString getCategory() const override { return CString("Stream codecs/Decoders"); } + CString getVersion() const override { return CString("1.0"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_Algorithm_ChannelLocalisationDecoder; } + IPluginObject* create() override { return new CChannelLocalisationDecoder(); } - bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override - { - CStreamedMatrixDecoderDesc::getAlgorithmPrototype(prototype); + bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override + { + CStreamedMatrixDecoderDesc::getAlgorithmPrototype(prototype); - prototype.addOutputParameter(OVP_Algorithm_ChannelLocalisationDecoder_OutputParameterId_Dynamic, "Dynamic", Kernel::ParameterType_Boolean); + prototype.addOutputParameter(OVP_Algorithm_ChannelLocalisationDecoder_OutputParameterId_Dynamic, "Dynamic", Kernel::ParameterType_Boolean); - return true; - } + return true; + } - _IsDerivedFromClass_Final_(StreamCodecs::CStreamedMatrixDecoderDesc, OVP_ClassId_Algorithm_ChannelLocalisationDecoderDesc) - }; - } // namespace StreamCodecs - } // namespace Plugins + _IsDerivedFromClass_Final_(StreamCodecs::CStreamedMatrixDecoderDesc, OVP_ClassId_Algorithm_ChannelLocalisationDecoderDesc) +}; +} // namespace StreamCodecs +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/stream-codecs/src/algorithms/decoders/ovpCChannelUnitsDecoder.h b/plugins/processing/stream-codecs/src/algorithms/decoders/ovpCChannelUnitsDecoder.h index ee5fd6f3de8dfe5be63b2d7edcc92fdac893e861..2f9edb5dcd48ee54f9d2db83f1d42dc3e95be172 100644 --- a/plugins/processing/stream-codecs/src/algorithms/decoders/ovpCChannelUnitsDecoder.h +++ b/plugins/processing/stream-codecs/src/algorithms/decoders/ovpCChannelUnitsDecoder.h @@ -4,66 +4,62 @@ #include "ovpCStreamedMatrixDecoder.h" #include <stack> -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace StreamCodecs { +class CChannelUnitsDecoder final : public CStreamedMatrixDecoder { - namespace Plugins - { - namespace StreamCodecs - { - class CChannelUnitsDecoder final : public CStreamedMatrixDecoder - { - public: - void release() override { delete this; } - bool initialize() override; - bool uninitialize() override; +public: + void release() override { delete this; } + bool initialize() override; + bool uninitialize() override; - _IsDerivedFromClass_Final_(StreamCodecs::CStreamedMatrixDecoder, OVP_ClassId_Algorithm_ChannelUnitsDecoder) + _IsDerivedFromClass_Final_(StreamCodecs::CStreamedMatrixDecoder, OVP_ClassId_Algorithm_ChannelUnitsDecoder) - // ebml callbacks - bool isMasterChild(const EBML::CIdentifier& identifier) override; - void openChild(const EBML::CIdentifier& identifier) override; - void processChildData(const void* buffer, const size_t size) override; - void closeChild() override; + // ebml callbacks + bool isMasterChild(const EBML::CIdentifier& identifier) override; + void openChild(const EBML::CIdentifier& identifier) override; + void processChildData(const void* buffer, const size_t size) override; + void closeChild() override; - protected: +protected: - Kernel::TParameterHandler<bool> op_bDynamic; + Kernel::TParameterHandler<bool> op_bDynamic; - private: +private: - std::stack<EBML::CIdentifier> m_nodes; - // size_t m_unitIdx = 0; - }; + std::stack<EBML::CIdentifier> m_nodes; + // size_t m_unitIdx = 0; +}; - class CChannelUnitsDecoderDesc final : public CStreamedMatrixDecoderDesc - { - public: - void release() override { } - CString getName() const override { return CString("Channel units stream decoder"); } - CString getAuthorName() const override { return CString("Yann Renard"); } - CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } - CString getShortDescription() const override { return CString(""); } - CString getDetailedDescription() const override { return CString(""); } - CString getCategory() const override { return CString("Stream codecs/Decoders"); } - CString getVersion() const override { return CString("1.0"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_Algorithm_ChannelUnitsDecoder; } - IPluginObject* create() override { return new CChannelUnitsDecoder(); } +class CChannelUnitsDecoderDesc final : public CStreamedMatrixDecoderDesc +{ +public: + void release() override { } + CString getName() const override { return CString("Channel units stream decoder"); } + CString getAuthorName() const override { return CString("Yann Renard"); } + CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } + CString getShortDescription() const override { return CString(""); } + CString getDetailedDescription() const override { return CString(""); } + CString getCategory() const override { return CString("Stream codecs/Decoders"); } + CString getVersion() const override { return CString("1.0"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_Algorithm_ChannelUnitsDecoder; } + IPluginObject* create() override { return new CChannelUnitsDecoder(); } - bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override - { - CStreamedMatrixDecoderDesc::getAlgorithmPrototype(prototype); + bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override + { + CStreamedMatrixDecoderDesc::getAlgorithmPrototype(prototype); - prototype.addOutputParameter( - OVP_Algorithm_ChannelUnitsDecoder_OutputParameterId_Dynamic, "Dynamic", Kernel::ParameterType_Boolean); + prototype.addOutputParameter(OVP_Algorithm_ChannelUnitsDecoder_OutputParameterId_Dynamic, "Dynamic", Kernel::ParameterType_Boolean); - return true; - } + return true; + } - _IsDerivedFromClass_Final_(StreamCodecs::CStreamedMatrixDecoderDesc, OVP_ClassId_Algorithm_ChannelUnitsDecoderDesc) - }; - } // namespace StreamCodecs - } // namespace Plugins + _IsDerivedFromClass_Final_(StreamCodecs::CStreamedMatrixDecoderDesc, OVP_ClassId_Algorithm_ChannelUnitsDecoderDesc) +}; +} // namespace StreamCodecs +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/stream-codecs/src/algorithms/decoders/ovpCEBMLBaseDecoder.h b/plugins/processing/stream-codecs/src/algorithms/decoders/ovpCEBMLBaseDecoder.h index 5d2c82670e33d9b89fee3bd13b906d3c46fde089..63ca120ee3b4e5ec4b817afe614ffa0a7d26ad8a 100644 --- a/plugins/processing/stream-codecs/src/algorithms/decoders/ovpCEBMLBaseDecoder.h +++ b/plugins/processing/stream-codecs/src/algorithms/decoders/ovpCEBMLBaseDecoder.h @@ -8,57 +8,53 @@ #include <ebml/IReaderHelper.h> #include <ebml/TReaderCallbackProxy.h> -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace StreamCodecs { +class CEBMLBaseDecoder : public Toolkit::TAlgorithm<IAlgorithm> { - namespace Plugins - { - namespace StreamCodecs - { - class CEBMLBaseDecoder : public Toolkit::TAlgorithm<IAlgorithm> - { - public: +public: - CEBMLBaseDecoder(); - void release() override { delete this; } - bool initialize() override; - bool uninitialize() override; - bool process() override; + CEBMLBaseDecoder(); + void release() override { delete this; } + bool initialize() override; + bool uninitialize() override; + bool process() override; - _IsDerivedFromClass_Final_(Toolkit::TAlgorithm<IAlgorithm>, OVP_ClassId_Algorithm_EBMLBaseDecoder) + _IsDerivedFromClass_Final_(Toolkit::TAlgorithm<IAlgorithm>, OVP_ClassId_Algorithm_EBMLBaseDecoder) - // ebml callbacks - virtual bool isMasterChild(const EBML::CIdentifier& identifier); - virtual void openChild(const EBML::CIdentifier& identifier); - virtual void processChildData(const void* /*buffer*/, const size_t /*size*/) { } - virtual void closeChild() { } + // ebml callbacks + virtual bool isMasterChild(const EBML::CIdentifier& identifier); + virtual void openChild(const EBML::CIdentifier& identifier); + virtual void processChildData(const void* /*buffer*/, const size_t /*size*/) { } + virtual void closeChild() { } - protected: +protected: - EBML::IReaderHelper* m_readerHelper = nullptr; - EBML::IReader* m_reader = nullptr; - EBML::TReaderCallbackProxy1<CEBMLBaseDecoder> m_callbackProxy; + EBML::IReaderHelper* m_readerHelper = nullptr; + EBML::IReader* m_reader = nullptr; + EBML::TReaderCallbackProxy1<CEBMLBaseDecoder> m_callbackProxy; - Kernel::TParameterHandler<IMemoryBuffer*> ip_bufferToDecode; - }; + Kernel::TParameterHandler<IMemoryBuffer*> ip_bufferToDecode; +}; - class CEBMLBaseDecoderDesc : public IAlgorithmDesc - { - public: - bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override - { - prototype.addInputParameter( - OVP_Algorithm_EBMLDecoder_InputParameterId_MemoryBufferToDecode, "Memory buffer to decode", - Kernel::ParameterType_MemoryBuffer); +class CEBMLBaseDecoderDesc : public IAlgorithmDesc +{ +public: + bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override + { + prototype.addInputParameter(OVP_Algorithm_EBMLDecoder_InputParameterId_MemoryBufferToDecode, "Memory buffer to decode", + Kernel::ParameterType_MemoryBuffer); - prototype.addOutputTrigger(OVP_Algorithm_EBMLDecoder_OutputTriggerId_ReceivedHeader, "Received header"); - prototype.addOutputTrigger(OVP_Algorithm_EBMLDecoder_OutputTriggerId_ReceivedBuffer, "Received buffer"); - prototype.addOutputTrigger(OVP_Algorithm_EBMLDecoder_OutputTriggerId_ReceivedEnd, "Received end"); + prototype.addOutputTrigger(OVP_Algorithm_EBMLDecoder_OutputTriggerId_ReceivedHeader, "Received header"); + prototype.addOutputTrigger(OVP_Algorithm_EBMLDecoder_OutputTriggerId_ReceivedBuffer, "Received buffer"); + prototype.addOutputTrigger(OVP_Algorithm_EBMLDecoder_OutputTriggerId_ReceivedEnd, "Received end"); - return true; - } + return true; + } - _IsDerivedFromClass_(IAlgorithmDesc, OVP_ClassId_Algorithm_EBMLBaseDecoderDesc) - }; - } // namespace StreamCodecs - } // namespace Plugins + _IsDerivedFromClass_(IAlgorithmDesc, OVP_ClassId_Algorithm_EBMLBaseDecoderDesc) +}; +} // namespace StreamCodecs +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/stream-codecs/src/algorithms/decoders/ovpCExperimentInfoDecoder.h b/plugins/processing/stream-codecs/src/algorithms/decoders/ovpCExperimentInfoDecoder.h index df94ab7d56e6eb9c575c4a0f2a85eb868b630963..da8d6481335fdaa07e3310859f9bb6a51c5876ed 100644 --- a/plugins/processing/stream-codecs/src/algorithms/decoders/ovpCExperimentInfoDecoder.h +++ b/plugins/processing/stream-codecs/src/algorithms/decoders/ovpCExperimentInfoDecoder.h @@ -4,96 +4,86 @@ #include "ovpCEBMLBaseDecoder.h" #include <stack> -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace StreamCodecs { +class CExperimentInfoDecoder final : public CEBMLBaseDecoder { - namespace Plugins +public: + + CExperimentInfoDecoder(); + void release() override { delete this; } + bool initialize() override; + bool uninitialize() override; + + _IsDerivedFromClass_Final_(StreamCodecs::CEBMLBaseDecoder, OVP_ClassId_Algorithm_ExperimentInfoDecoder) + + // ebml callbacks + bool isMasterChild(const EBML::CIdentifier& identifier) override; + void openChild(const EBML::CIdentifier& identifier) override; + void processChildData(const void* buffer, const size_t size) override; + void closeChild() override; + +protected: + + Kernel::TParameterHandler<uint64_t> op_ExperimentID; + Kernel::TParameterHandler<CString*> op_experimentDate; + + Kernel::TParameterHandler<uint64_t> op_subjectID; + Kernel::TParameterHandler<CString*> op_subjectName; + Kernel::TParameterHandler<uint64_t> op_subjectAge; + Kernel::TParameterHandler<uint64_t> op_subjectGender; + + Kernel::TParameterHandler<uint64_t> op_LaboratoryID; + Kernel::TParameterHandler<CString*> op_pLaboratoryName; + Kernel::TParameterHandler<uint64_t> op_TechnicianID; + Kernel::TParameterHandler<CString*> op_pTechnicianName; + +private: + + std::stack<EBML::CIdentifier> m_nodes; +}; + +class CExperimentInfoDecoderDesc final : public CEBMLBaseDecoderDesc +{ +public: + void release() override { } + CString getName() const override { return CString("Experiment information stream decoder"); } + CString getAuthorName() const override { return CString("Yann Renard"); } + CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } + CString getShortDescription() const override { return CString(""); } + CString getDetailedDescription() const override { return CString(""); } + CString getCategory() const override { return CString("Stream codecs/Decoders"); } + CString getVersion() const override { return CString("1.0"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_Algorithm_ExperimentInfoDecoder; } + IPluginObject* create() override { return new CExperimentInfoDecoder(); } + + bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override { - namespace StreamCodecs - { - class CExperimentInfoDecoder final : public CEBMLBaseDecoder - { - public: - - CExperimentInfoDecoder(); - void release() override { delete this; } - bool initialize() override; - bool uninitialize() override; - - _IsDerivedFromClass_Final_(StreamCodecs::CEBMLBaseDecoder, OVP_ClassId_Algorithm_ExperimentInfoDecoder) - - // ebml callbacks - bool isMasterChild(const EBML::CIdentifier& identifier) override; - void openChild(const EBML::CIdentifier& identifier) override; - void processChildData(const void* buffer, const size_t size) override; - void closeChild() override; - - protected: - - Kernel::TParameterHandler<uint64_t> op_ExperimentID; - Kernel::TParameterHandler<CString*> op_experimentDate; - - Kernel::TParameterHandler<uint64_t> op_subjectID; - Kernel::TParameterHandler<CString*> op_subjectName; - Kernel::TParameterHandler<uint64_t> op_subjectAge; - Kernel::TParameterHandler<uint64_t> op_subjectGender; - - Kernel::TParameterHandler<uint64_t> op_LaboratoryID; - Kernel::TParameterHandler<CString*> op_pLaboratoryName; - Kernel::TParameterHandler<uint64_t> op_TechnicianID; - Kernel::TParameterHandler<CString*> op_pTechnicianName; - - private: - - std::stack<EBML::CIdentifier> m_nodes; - }; - - class CExperimentInfoDecoderDesc final : public CEBMLBaseDecoderDesc - { - public: - void release() override { } - CString getName() const override { return CString("Experiment information stream decoder"); } - CString getAuthorName() const override { return CString("Yann Renard"); } - CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } - CString getShortDescription() const override { return CString(""); } - CString getDetailedDescription() const override { return CString(""); } - CString getCategory() const override { return CString("Stream codecs/Decoders"); } - CString getVersion() const override { return CString("1.0"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_Algorithm_ExperimentInfoDecoder; } - IPluginObject* create() override { return new CExperimentInfoDecoder(); } - - bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override - { - CEBMLBaseDecoderDesc::getAlgorithmPrototype(prototype); - - prototype.addOutputParameter( - OVP_Algorithm_ExperimentInfoDecoder_OutputParameterId_ExperimentID, "Experiment identifier", Kernel::ParameterType_UInteger); - prototype.addOutputParameter( - OVP_Algorithm_ExperimentInfoDecoder_OutputParameterId_ExperimentDate, "Experiment date", Kernel::ParameterType_String); - prototype.addOutputParameter( - OVP_Algorithm_ExperimentInfoDecoder_OutputParameterId_SubjectID, "Subject identifier", Kernel::ParameterType_UInteger); - prototype.addOutputParameter( - OVP_Algorithm_ExperimentInfoDecoder_OutputParameterId_SubjectName, "Subject name", Kernel::ParameterType_String); - prototype.addOutputParameter( - OVP_Algorithm_ExperimentInfoDecoder_OutputParameterId_SubjectAge, "Subject age", Kernel::ParameterType_UInteger); - prototype.addOutputParameter( - OVP_Algorithm_ExperimentInfoDecoder_OutputParameterId_SubjectGender, "Subject gender", Kernel::ParameterType_UInteger); - prototype.addOutputParameter( - OVP_Algorithm_ExperimentInfoDecoder_OutputParameterId_LaboratoryID, "Laboratory identifier", Kernel::ParameterType_UInteger); - prototype.addOutputParameter( - OVP_Algorithm_ExperimentInfoDecoder_OutputParameterId_LaboratoryName, "Laboratory name", Kernel::ParameterType_String); - prototype.addOutputParameter( - OVP_Algorithm_ExperimentInfoDecoder_OutputParameterId_TechnicianID, "Technician identifier", Kernel::ParameterType_UInteger); - prototype.addOutputParameter( - OVP_Algorithm_ExperimentInfoDecoder_OutputParameterId_TechnicianName, "Technician name", Kernel::ParameterType_String); - - return true; - } - - _IsDerivedFromClass_Final_(StreamCodecs::CEBMLBaseDecoderDesc, OVP_ClassId_Algorithm_ExperimentInfoDecoderDesc) - }; - } // namespace StreamCodecs - } // namespace Plugins + CEBMLBaseDecoderDesc::getAlgorithmPrototype(prototype); + + prototype.addOutputParameter(OVP_Algorithm_ExperimentInfoDecoder_OutputParameterId_ExperimentID, "Experiment identifier", + Kernel::ParameterType_UInteger); + prototype.addOutputParameter(OVP_Algorithm_ExperimentInfoDecoder_OutputParameterId_ExperimentDate, "Experiment date", Kernel::ParameterType_String); + prototype.addOutputParameter(OVP_Algorithm_ExperimentInfoDecoder_OutputParameterId_SubjectID, "Subject identifier", Kernel::ParameterType_UInteger); + prototype.addOutputParameter(OVP_Algorithm_ExperimentInfoDecoder_OutputParameterId_SubjectName, "Subject name", Kernel::ParameterType_String); + prototype.addOutputParameter(OVP_Algorithm_ExperimentInfoDecoder_OutputParameterId_SubjectAge, "Subject age", Kernel::ParameterType_UInteger); + prototype.addOutputParameter(OVP_Algorithm_ExperimentInfoDecoder_OutputParameterId_SubjectGender, "Subject gender", Kernel::ParameterType_UInteger); + prototype.addOutputParameter(OVP_Algorithm_ExperimentInfoDecoder_OutputParameterId_LaboratoryID, "Laboratory identifier", + Kernel::ParameterType_UInteger); + prototype.addOutputParameter(OVP_Algorithm_ExperimentInfoDecoder_OutputParameterId_LaboratoryName, "Laboratory name", Kernel::ParameterType_String); + prototype.addOutputParameter(OVP_Algorithm_ExperimentInfoDecoder_OutputParameterId_TechnicianID, "Technician identifier", + Kernel::ParameterType_UInteger); + prototype.addOutputParameter(OVP_Algorithm_ExperimentInfoDecoder_OutputParameterId_TechnicianName, "Technician name", Kernel::ParameterType_String); + + return true; + } + + _IsDerivedFromClass_Final_(StreamCodecs::CEBMLBaseDecoderDesc, OVP_ClassId_Algorithm_ExperimentInfoDecoderDesc) +}; +} // namespace StreamCodecs +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/stream-codecs/src/algorithms/decoders/ovpCFeatureVectorDecoder.h b/plugins/processing/stream-codecs/src/algorithms/decoders/ovpCFeatureVectorDecoder.h index 88bfa80e9fd3e7a59870d25d36656e504d8f0b62..adc779b1c07e3f72e29ba168cbaecdd6ab2ee253 100644 --- a/plugins/processing/stream-codecs/src/algorithms/decoders/ovpCFeatureVectorDecoder.h +++ b/plugins/processing/stream-codecs/src/algorithms/decoders/ovpCFeatureVectorDecoder.h @@ -3,52 +3,48 @@ #include "../../ovp_defines.h" #include "ovpCStreamedMatrixDecoder.h" -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace StreamCodecs { +class CFeatureVectorDecoder final : public CStreamedMatrixDecoder { - namespace Plugins +public: + void release() override { delete this; } + void openChild(const EBML::CIdentifier& identifier) override; + void processChildData(const void* buffer, const size_t size) override; + + _IsDerivedFromClass_Final_(StreamCodecs::CStreamedMatrixDecoder, OVP_ClassId_Algorithm_FeatureVectorDecoder) + +private: + + EBML::CIdentifier m_oTop; +}; + +class CFeatureVectorDecoderDesc final : public CStreamedMatrixDecoderDesc +{ +public: + void release() override { } + CString getName() const override { return CString("Feature vector stream decoder"); } + CString getAuthorName() const override { return CString("Yann Renard"); } + CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } + CString getShortDescription() const override { return CString(""); } + CString getDetailedDescription() const override { return CString(""); } + CString getCategory() const override { return CString("Stream codecs/Decoders"); } + CString getVersion() const override { return CString("1.0"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_Algorithm_FeatureVectorDecoder; } + IPluginObject* create() override { return new CFeatureVectorDecoder(); } + + bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override { - namespace StreamCodecs - { - class CFeatureVectorDecoder final : public CStreamedMatrixDecoder - { - public: - void release() override { delete this; } - void openChild(const EBML::CIdentifier& identifier) override; - void processChildData(const void* buffer, const size_t size) override; - - _IsDerivedFromClass_Final_(StreamCodecs::CStreamedMatrixDecoder, OVP_ClassId_Algorithm_FeatureVectorDecoder) - - private: - - EBML::CIdentifier m_oTop; - }; - - class CFeatureVectorDecoderDesc final : public CStreamedMatrixDecoderDesc - { - public: - void release() override { } - CString getName() const override { return CString("Feature vector stream decoder"); } - CString getAuthorName() const override { return CString("Yann Renard"); } - CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } - CString getShortDescription() const override { return CString(""); } - CString getDetailedDescription() const override { return CString(""); } - CString getCategory() const override { return CString("Stream codecs/Decoders"); } - CString getVersion() const override { return CString("1.0"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_Algorithm_FeatureVectorDecoder; } - IPluginObject* create() override { return new CFeatureVectorDecoder(); } - - bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override - { - CStreamedMatrixDecoderDesc::getAlgorithmPrototype(prototype); - - return true; - } - - _IsDerivedFromClass_Final_(StreamCodecs::CStreamedMatrixDecoderDesc, OVP_ClassId_Algorithm_FeatureVectorDecoderDesc) - }; - } // namespace StreamCodecs - } // namespace Plugins + CStreamedMatrixDecoderDesc::getAlgorithmPrototype(prototype); + return true; + } + + _IsDerivedFromClass_Final_(StreamCodecs::CStreamedMatrixDecoderDesc, OVP_ClassId_Algorithm_FeatureVectorDecoderDesc) +}; +} // namespace StreamCodecs +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/stream-codecs/src/algorithms/decoders/ovpCSignalDecoder.cpp b/plugins/processing/stream-codecs/src/algorithms/decoders/ovpCSignalDecoder.cpp index fa304f2579d2793d72039589bdde72acf3661521..f38a80f6c38d45def6f7b1e011cbe9b5b7fd6ad5 100644 --- a/plugins/processing/stream-codecs/src/algorithms/decoders/ovpCSignalDecoder.cpp +++ b/plugins/processing/stream-codecs/src/algorithms/decoders/ovpCSignalDecoder.cpp @@ -11,18 +11,14 @@ using namespace StreamCodecs; bool CSignalDecoder::initialize() { CStreamedMatrixDecoder::initialize(); - op_sampling.initialize(getOutputParameter(OVP_Algorithm_SignalDecoder_OutputParameterId_Sampling)); - return true; } bool CSignalDecoder::uninitialize() { op_sampling.uninitialize(); - CStreamedMatrixDecoder::uninitialize(); - return true; } @@ -42,8 +38,7 @@ void CSignalDecoder::openChild(const EBML::CIdentifier& identifier) EBML::CIdentifier& top = m_nodes.top(); - if ((top == OVTK_NodeId_Header_Signal) - || (top == OVTK_NodeId_Header_Signal_Sampling)) { } + if ((top == OVTK_NodeId_Header_Signal) || (top == OVTK_NodeId_Header_Signal_Sampling)) { } else { CStreamedMatrixDecoder::openChild(identifier); } } @@ -51,8 +46,7 @@ void CSignalDecoder::processChildData(const void* buffer, const size_t size) { EBML::CIdentifier& top = m_nodes.top(); - if ((top == OVTK_NodeId_Header_Signal) - || (top == OVTK_NodeId_Header_Signal_Sampling)) + if ((top == OVTK_NodeId_Header_Signal) || (top == OVTK_NodeId_Header_Signal_Sampling)) { if (top == OVTK_NodeId_Header_Signal_Sampling) { op_sampling = m_readerHelper->getUInt(buffer, size); } } @@ -63,8 +57,7 @@ void CSignalDecoder::closeChild() { EBML::CIdentifier& top = m_nodes.top(); - if ((top == OVTK_NodeId_Header_Signal) - || (top == OVTK_NodeId_Header_Signal_Sampling)) { } + if ((top == OVTK_NodeId_Header_Signal) || (top == OVTK_NodeId_Header_Signal_Sampling)) { } else { CStreamedMatrixDecoder::closeChild(); } m_nodes.pop(); diff --git a/plugins/processing/stream-codecs/src/algorithms/decoders/ovpCSignalDecoder.h b/plugins/processing/stream-codecs/src/algorithms/decoders/ovpCSignalDecoder.h index 2271300a0e438ec24cd62153a0cc206e87ef536a..6630766f9c212f608768169cd12c0334e0816570 100644 --- a/plugins/processing/stream-codecs/src/algorithms/decoders/ovpCSignalDecoder.h +++ b/plugins/processing/stream-codecs/src/algorithms/decoders/ovpCSignalDecoder.h @@ -4,65 +4,59 @@ #include "ovpCStreamedMatrixDecoder.h" #include <stack> -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace StreamCodecs { +class CSignalDecoder final : public CStreamedMatrixDecoder { - namespace Plugins - { - namespace StreamCodecs - { - class CSignalDecoder final : public CStreamedMatrixDecoder - { - public: - void release() override { delete this; } - bool initialize() override; - bool uninitialize() override; - - _IsDerivedFromClass_Final_(StreamCodecs::CStreamedMatrixDecoder, OVP_ClassId_Algorithm_SignalDecoder) - - // ebml callbacks - bool isMasterChild(const EBML::CIdentifier& identifier) override; - void openChild(const EBML::CIdentifier& identifier) override; - void processChildData(const void* buffer, const size_t size) override; - void closeChild() override; - - protected: +public: + void release() override { delete this; } + bool initialize() override; + bool uninitialize() override; - Kernel::TParameterHandler<uint64_t> op_sampling; + _IsDerivedFromClass_Final_(StreamCodecs::CStreamedMatrixDecoder, OVP_ClassId_Algorithm_SignalDecoder) - private: + // ebml callbacks + bool isMasterChild(const EBML::CIdentifier& identifier) override; + void openChild(const EBML::CIdentifier& identifier) override; + void processChildData(const void* buffer, const size_t size) override; + void closeChild() override; - std::stack<EBML::CIdentifier> m_nodes; - }; +protected: - class CSignalDecoderDesc final : public CStreamedMatrixDecoderDesc - { - public: - void release() override { } - CString getName() const override { return CString("Signal stream decoder"); } - CString getAuthorName() const override { return CString("Yann Renard"); } - CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } - CString getShortDescription() const override { return CString(""); } - CString getDetailedDescription() const override { return CString(""); } - CString getCategory() const override { return CString("Stream codecs/Decoders"); } - CString getVersion() const override { return CString("1.0"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_Algorithm_SignalDecoder; } - IPluginObject* create() override { return new CSignalDecoder(); } + Kernel::TParameterHandler<uint64_t> op_sampling; - bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override - { - CStreamedMatrixDecoderDesc::getAlgorithmPrototype(prototype); +private: - prototype.addOutputParameter( - OVP_Algorithm_SignalDecoder_OutputParameterId_Sampling, "Sampling rate", Kernel::ParameterType_UInteger); + std::stack<EBML::CIdentifier> m_nodes; +}; - return true; - } - - _IsDerivedFromClass_Final_(StreamCodecs::CStreamedMatrixDecoderDesc, OVP_ClassId_Algorithm_SignalDecoderDesc) - }; - } // namespace StreamCodecs - } // namespace Plugins +class CSignalDecoderDesc final : public CStreamedMatrixDecoderDesc +{ +public: + void release() override { } + CString getName() const override { return CString("Signal stream decoder"); } + CString getAuthorName() const override { return CString("Yann Renard"); } + CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } + CString getShortDescription() const override { return CString(""); } + CString getDetailedDescription() const override { return CString(""); } + CString getCategory() const override { return CString("Stream codecs/Decoders"); } + CString getVersion() const override { return CString("1.0"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_Algorithm_SignalDecoder; } + IPluginObject* create() override { return new CSignalDecoder(); } + + bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override + { + CStreamedMatrixDecoderDesc::getAlgorithmPrototype(prototype); + prototype.addOutputParameter(OVP_Algorithm_SignalDecoder_OutputParameterId_Sampling, "Sampling rate", Kernel::ParameterType_UInteger); + return true; + } + + _IsDerivedFromClass_Final_(StreamCodecs::CStreamedMatrixDecoderDesc, OVP_ClassId_Algorithm_SignalDecoderDesc) +}; +} // namespace StreamCodecs +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/stream-codecs/src/algorithms/decoders/ovpCSpectrumDecoder.cpp b/plugins/processing/stream-codecs/src/algorithms/decoders/ovpCSpectrumDecoder.cpp index 1746eebb77abe77ec3ca2211e6b7fa9f97d1a0ad..ea0d84662f2d0a37725c76875544b4d41681ec1b 100755 --- a/plugins/processing/stream-codecs/src/algorithms/decoders/ovpCSpectrumDecoder.cpp +++ b/plugins/processing/stream-codecs/src/algorithms/decoders/ovpCSpectrumDecoder.cpp @@ -11,10 +11,8 @@ using namespace StreamCodecs; bool CSpectrumDecoder::initialize() { CStreamedMatrixDecoder::initialize(); - op_frequencyAbscissa.initialize(getOutputParameter(OVP_Algorithm_SpectrumDecoder_OutputParameterId_FrequencyAbscissa)); op_sampling.initialize(getOutputParameter(OVP_Algorithm_SpectrumDecoder_OutputParameterId_Sampling)); - return true; } @@ -22,9 +20,7 @@ bool CSpectrumDecoder::uninitialize() { op_frequencyAbscissa.uninitialize(); op_sampling.uninitialize(); - CStreamedMatrixDecoder::uninitialize(); - return true; } @@ -61,8 +57,7 @@ void CSpectrumDecoder::openChild(const EBML::CIdentifier& identifier) void CSpectrumDecoder::processChildData(const void* buffer, const size_t size) { EBML::CIdentifier& top = m_nodes.top(); - if ((top == OVTK_NodeId_Header_Spectrum) - || (top == OVTK_NodeId_Header_Spectrum_FrequencyBand_Deprecated)) { } + if ((top == OVTK_NodeId_Header_Spectrum) || (top == OVTK_NodeId_Header_Spectrum_FrequencyBand_Deprecated)) { } else if (top == OVTK_NodeId_Header_Spectrum_FrequencyBand_Start_Deprecated) { m_lowerFreq = m_readerHelper->getDouble(buffer, size); } else if (top == OVTK_NodeId_Header_Spectrum_FrequencyBand_Stop_Deprecated) { @@ -95,7 +90,7 @@ void CSpectrumDecoder::closeChild() { EBML::CIdentifier& top = m_nodes.top(); - if ((top == OVTK_NodeId_Header_Spectrum) + if ((top == OVTK_NodeId_Header_Spectrum) || (top == OVTK_NodeId_Header_Spectrum_FrequencyBand_Start_Deprecated) || (top == OVTK_NodeId_Header_Spectrum_FrequencyBand_Stop_Deprecated)) { } else if ((top == OVTK_NodeId_Header_Spectrum_FrequencyBand_Deprecated) || (top == OVTK_NodeId_Header_Spectrum_FrequencyAbscissa)) { m_frequencyBandIdx++; } diff --git a/plugins/processing/stream-codecs/src/algorithms/decoders/ovpCSpectrumDecoder.h b/plugins/processing/stream-codecs/src/algorithms/decoders/ovpCSpectrumDecoder.h index 431d1226f927060d1bb33e6cca5ccc282c435886..ab39e4fc61b389aef851a4436bd3d61138b7581c 100755 --- a/plugins/processing/stream-codecs/src/algorithms/decoders/ovpCSpectrumDecoder.h +++ b/plugins/processing/stream-codecs/src/algorithms/decoders/ovpCSpectrumDecoder.h @@ -4,74 +4,69 @@ #include "ovpCStreamedMatrixDecoder.h" #include <iomanip> -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace StreamCodecs { +class CSpectrumDecoder final : public CStreamedMatrixDecoder { - namespace Plugins +public: + void release() override { delete this; } + bool initialize() override; + bool uninitialize() override; + + _IsDerivedFromClass_Final_(StreamCodecs::CStreamedMatrixDecoder, OVP_ClassId_Algorithm_SpectrumDecoder) + + // ebml callbacks + bool isMasterChild(const EBML::CIdentifier& identifier) override; + void openChild(const EBML::CIdentifier& identifier) override; + void processChildData(const void* buffer, const size_t size) override; + void closeChild() override; + +protected: + + Kernel::TParameterHandler<IMatrix*> op_frequencyAbscissa; + Kernel::TParameterHandler<uint64_t> op_sampling; + + +private: + + std::stack<EBML::CIdentifier> m_nodes; + + size_t m_frequencyBandIdx = 0; + + // Value of the current lower frequency of the band. Only used to read old spectrum format. + double m_lowerFreq = 0; +}; + +class CSpectrumDecoderDesc final : public CStreamedMatrixDecoderDesc +{ +public: + void release() override { } + CString getName() const override { return CString("Spectrum stream decoder"); } + CString getAuthorName() const override { return CString("Yann Renard"); } + CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } + CString getShortDescription() const override { return CString("Decodes the Spectrum type streams."); } + CString getDetailedDescription() const override { return CString(""); } + CString getCategory() const override { return CString("Stream codecs/Decoders"); } + CString getVersion() const override { return CString("1.0"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.1.0"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_Algorithm_SpectrumDecoder; } + IPluginObject* create() override { return new CSpectrumDecoder(); } + + bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override { - namespace StreamCodecs - { - class CSpectrumDecoder final : public CStreamedMatrixDecoder - { - public: - void release() override { delete this; } - bool initialize() override; - bool uninitialize() override; - - _IsDerivedFromClass_Final_(StreamCodecs::CStreamedMatrixDecoder, OVP_ClassId_Algorithm_SpectrumDecoder) - - // ebml callbacks - bool isMasterChild(const EBML::CIdentifier& identifier) override; - void openChild(const EBML::CIdentifier& identifier) override; - void processChildData(const void* buffer, const size_t size) override; - void closeChild() override; - - protected: - - Kernel::TParameterHandler<IMatrix*> op_frequencyAbscissa; - Kernel::TParameterHandler<uint64_t> op_sampling; - - - private: - - std::stack<EBML::CIdentifier> m_nodes; - - size_t m_frequencyBandIdx = 0; - - // Value of the current lower frequency of the band. Only used to read old spectrum format. - double m_lowerFreq = 0; - }; - - class CSpectrumDecoderDesc final : public CStreamedMatrixDecoderDesc - { - public: - void release() override { } - CString getName() const override { return CString("Spectrum stream decoder"); } - CString getAuthorName() const override { return CString("Yann Renard"); } - CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } - CString getShortDescription() const override { return CString("Decodes the Spectrum type streams."); } - CString getDetailedDescription() const override { return CString(""); } - CString getCategory() const override { return CString("Stream codecs/Decoders"); } - CString getVersion() const override { return CString("1.0"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.1.0"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_Algorithm_SpectrumDecoder; } - IPluginObject* create() override { return new CSpectrumDecoder(); } - - bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override - { - CStreamedMatrixDecoderDesc::getAlgorithmPrototype(prototype); - - prototype.addOutputParameter( - OVP_Algorithm_SpectrumDecoder_OutputParameterId_FrequencyAbscissa, "Frequency abscissa", Kernel::ParameterType_Matrix); - prototype.addOutputParameter( - OVP_Algorithm_SpectrumDecoder_OutputParameterId_Sampling, "Sampling rate", Kernel::ParameterType_UInteger); - - return true; - } - - _IsDerivedFromClass_Final_(StreamCodecs::CStreamedMatrixDecoderDesc, OVP_ClassId_Algorithm_SpectrumDecoderDesc) - }; - } // namespace StreamCodecs - } // namespace Plugins + CStreamedMatrixDecoderDesc::getAlgorithmPrototype(prototype); + + prototype.addOutputParameter(OVP_Algorithm_SpectrumDecoder_OutputParameterId_FrequencyAbscissa, "Frequency abscissa", Kernel::ParameterType_Matrix); + prototype.addOutputParameter(OVP_Algorithm_SpectrumDecoder_OutputParameterId_Sampling, "Sampling rate", Kernel::ParameterType_UInteger); + + return true; + } + + _IsDerivedFromClass_Final_(StreamCodecs::CStreamedMatrixDecoderDesc, OVP_ClassId_Algorithm_SpectrumDecoderDesc) +}; +} // namespace StreamCodecs +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/stream-codecs/src/algorithms/decoders/ovpCStimulationDecoder.h b/plugins/processing/stream-codecs/src/algorithms/decoders/ovpCStimulationDecoder.h index 69a18798bc1ddb7de0a8a60a6cab24d8903ac523..80114b0a20b52450eccf6c15525df578f567b8f7 100644 --- a/plugins/processing/stream-codecs/src/algorithms/decoders/ovpCStimulationDecoder.h +++ b/plugins/processing/stream-codecs/src/algorithms/decoders/ovpCStimulationDecoder.h @@ -4,68 +4,63 @@ #include "ovpCEBMLBaseDecoder.h" #include <stack> -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace StreamCodecs { +class CStimulationDecoder final : public CEBMLBaseDecoder { - namespace Plugins - { - namespace StreamCodecs - { - class CStimulationDecoder final : public CEBMLBaseDecoder - { - public: - void release() override { delete this; } - bool initialize() override; - bool uninitialize() override; - - _IsDerivedFromClass_Final_(StreamCodecs::CEBMLBaseDecoder, OVP_ClassId_Algorithm_StimulationDecoder) - - // ebml callbacks - bool isMasterChild(const EBML::CIdentifier& identifier) override; - void openChild(const EBML::CIdentifier& identifier) override; - void processChildData(const void* buffer, const size_t size) override; - void closeChild() override; +public: + void release() override { delete this; } + bool initialize() override; + bool uninitialize() override; - protected: + _IsDerivedFromClass_Final_(StreamCodecs::CEBMLBaseDecoder, OVP_ClassId_Algorithm_StimulationDecoder) - Kernel::TParameterHandler<IStimulationSet*> op_stimulationSet; + // ebml callbacks + bool isMasterChild(const EBML::CIdentifier& identifier) override; + void openChild(const EBML::CIdentifier& identifier) override; + void processChildData(const void* buffer, const size_t size) override; + void closeChild() override; - private: +protected: - std::stack<EBML::CIdentifier> m_nodes; + Kernel::TParameterHandler<IStimulationSet*> op_stimulationSet; - size_t m_stimulationIdx = 0; - CStimulationSet m_stimSet; - }; +private: - class CStimulationDecoderDesc final : public CEBMLBaseDecoderDesc - { - public: - void release() override { } - CString getName() const override { return CString("Stimulation stream decoder"); } - CString getAuthorName() const override { return CString("Yann Renard"); } - CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } - CString getShortDescription() const override { return CString(""); } - CString getDetailedDescription() const override { return CString(""); } - CString getCategory() const override { return CString("Stream codecs/Decoders"); } - CString getVersion() const override { return CString("1.0"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_Algorithm_StimulationDecoder; } - IPluginObject* create() override { return new CStimulationDecoder(); } + std::stack<EBML::CIdentifier> m_nodes; - bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override - { - CEBMLBaseDecoderDesc::getAlgorithmPrototype(prototype); + size_t m_stimulationIdx = 0; + CStimulationSet m_stimSet; +}; - prototype.addOutputParameter( - OVP_Algorithm_StimulationDecoder_OutputParameterId_StimulationSet, "Stimulation set", Kernel::ParameterType_StimulationSet); +class CStimulationDecoderDesc final : public CEBMLBaseDecoderDesc +{ +public: + void release() override { } + CString getName() const override { return CString("Stimulation stream decoder"); } + CString getAuthorName() const override { return CString("Yann Renard"); } + CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } + CString getShortDescription() const override { return CString(""); } + CString getDetailedDescription() const override { return CString(""); } + CString getCategory() const override { return CString("Stream codecs/Decoders"); } + CString getVersion() const override { return CString("1.0"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_Algorithm_StimulationDecoder; } + IPluginObject* create() override { return new CStimulationDecoder(); } - return true; - } + bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override + { + CEBMLBaseDecoderDesc::getAlgorithmPrototype(prototype); + prototype.addOutputParameter(OVP_Algorithm_StimulationDecoder_OutputParameterId_StimulationSet, "Stimulation set", + Kernel::ParameterType_StimulationSet); + return true; + } - _IsDerivedFromClass_Final_(StreamCodecs::CEBMLBaseDecoderDesc, OVP_ClassId_Algorithm_StimulationDecoderDesc) - }; - } // namespace StreamCodecs - } // namespace Plugins + _IsDerivedFromClass_Final_(StreamCodecs::CEBMLBaseDecoderDesc, OVP_ClassId_Algorithm_StimulationDecoderDesc) +}; +} // namespace StreamCodecs +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/stream-codecs/src/algorithms/decoders/ovpCStreamStructureDecoder.cpp b/plugins/processing/stream-codecs/src/algorithms/decoders/ovpCStreamStructureDecoder.cpp index df21f426cd9182a3298135e75be90974ec50acc7..d256dfb7461462756b63f82c2d4c6793a87c2687 100644 --- a/plugins/processing/stream-codecs/src/algorithms/decoders/ovpCStreamStructureDecoder.cpp +++ b/plugins/processing/stream-codecs/src/algorithms/decoders/ovpCStreamStructureDecoder.cpp @@ -26,9 +26,6 @@ bool CStreamStructureDecoder::uninitialize() // bool CStreamStructureDecoder::isMasterChild(const EBML::CIdentifier& identifier) { return CEBMLBaseDecoder::isMasterChild(identifier); } - void CStreamStructureDecoder::openChild(const EBML::CIdentifier& identifier) { CEBMLBaseDecoder::openChild(identifier); } - void CStreamStructureDecoder::processChildData(const void* buffer, const size_t size) { CEBMLBaseDecoder::processChildData(buffer, size); } - void CStreamStructureDecoder::closeChild() { CEBMLBaseDecoder::closeChild(); } diff --git a/plugins/processing/stream-codecs/src/algorithms/decoders/ovpCStreamStructureDecoder.h b/plugins/processing/stream-codecs/src/algorithms/decoders/ovpCStreamStructureDecoder.h index b2260788bb9a6aa9a6d7b60aa0f567ad25afd9c0..23c14f3db8051111d7d103573b01e0d4b9cfd928 100644 --- a/plugins/processing/stream-codecs/src/algorithms/decoders/ovpCStreamStructureDecoder.h +++ b/plugins/processing/stream-codecs/src/algorithms/decoders/ovpCStreamStructureDecoder.h @@ -3,55 +3,52 @@ #include "../../ovp_defines.h" #include "ovpCEBMLBaseDecoder.h" -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace StreamCodecs { +class CStreamStructureDecoder final : public CEBMLBaseDecoder { - namespace Plugins +public: + + CStreamStructureDecoder(); + void release() override { delete this; } + bool initialize() override; + bool uninitialize() override; + + _IsDerivedFromClass_Final_(StreamCodecs::CEBMLBaseDecoder, OVP_ClassId_Algorithm_StreamStructureDecoder) + + // ebml callbacks + bool isMasterChild(const EBML::CIdentifier& identifier) override; + void openChild(const EBML::CIdentifier& identifier) override; + void processChildData(const void* buffer, const size_t size) override; + void closeChild() override; +}; + +class CStreamStructureDecoderDesc final : public CEBMLBaseDecoderDesc +{ +public: + void release() override { } + CString getName() const override { return CString("Stream Structure Decoder"); } + CString getAuthorName() const override { return CString("Jozef Legeny"); } + CString getAuthorCompanyName() const override { return CString("Mensia Technologies"); } + CString getShortDescription() const override { return CString(""); } + CString getDetailedDescription() const override { return CString(""); } + CString getCategory() const override { return CString("Stream codecs/Decoders"); } + CString getVersion() const override { return CString("1.0"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("2.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_Algorithm_StreamStructureDecoder; } + IPluginObject* create() override { return new CStreamStructureDecoder(); } + + bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override { - namespace StreamCodecs - { - class CStreamStructureDecoder final : public CEBMLBaseDecoder - { - public: - - CStreamStructureDecoder(); - void release() override { delete this; } - bool initialize() override; - bool uninitialize() override; - - _IsDerivedFromClass_Final_(StreamCodecs::CEBMLBaseDecoder, OVP_ClassId_Algorithm_StreamStructureDecoder) - - // ebml callbacks - bool isMasterChild(const EBML::CIdentifier& identifier) override; - void openChild(const EBML::CIdentifier& identifier) override; - void processChildData(const void* buffer, const size_t size) override; - void closeChild() override; - }; - - class CStreamStructureDecoderDesc final : public CEBMLBaseDecoderDesc - { - public: - void release() override { } - CString getName() const override { return CString("Stream Structure Decoder"); } - CString getAuthorName() const override { return CString("Jozef Legeny"); } - CString getAuthorCompanyName() const override { return CString("Mensia Technologies"); } - CString getShortDescription() const override { return CString(""); } - CString getDetailedDescription() const override { return CString(""); } - CString getCategory() const override { return CString("Stream codecs/Decoders"); } - CString getVersion() const override { return CString("1.0"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("2.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_Algorithm_StreamStructureDecoder; } - IPluginObject* create() override { return new CStreamStructureDecoder(); } - - bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override - { - CEBMLBaseDecoderDesc::getAlgorithmPrototype(prototype); - return true; - } - - _IsDerivedFromClass_Final_(StreamCodecs::CEBMLBaseDecoderDesc, OVP_ClassId_Algorithm_StreamStructureDecoderDesc) - }; - } // namespace StreamCodecs - } // namespace Plugins + CEBMLBaseDecoderDesc::getAlgorithmPrototype(prototype); + return true; + } + + _IsDerivedFromClass_Final_(StreamCodecs::CEBMLBaseDecoderDesc, OVP_ClassId_Algorithm_StreamStructureDecoderDesc) +}; +} // namespace StreamCodecs +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/stream-codecs/src/algorithms/decoders/ovpCStreamedMatrixDecoder.cpp b/plugins/processing/stream-codecs/src/algorithms/decoders/ovpCStreamedMatrixDecoder.cpp index 243f438cdc5f68c534c9e88020a504fc01b9ebcf..dd015bcd4de24ddee55670dc4e324fc65c4fb007 100644 --- a/plugins/processing/stream-codecs/src/algorithms/decoders/ovpCStreamedMatrixDecoder.cpp +++ b/plugins/processing/stream-codecs/src/algorithms/decoders/ovpCStreamedMatrixDecoder.cpp @@ -7,20 +7,19 @@ using namespace /*OpenViBE::*/Kernel; using namespace /*OpenViBE::*/Plugins; using namespace /*OpenViBE::Plugins::*/StreamCodecs; -namespace +namespace { +// removes pre and post spaces, tabs and carriage returns +void trim(char* dst, const char* src1, const char* src2) { - // removes pre and post spaces, tabs and carriage returns - void trim(char* dst, const char* src1, const char* src2) - { - if (!src1 || *src1 == '\0') { dst[0] = '\0'; } - if (!src2) { src2 = src1 + strlen(src1) - 1; } - while (src1 < src2 && (*src1 == ' ' || *src1 == '\t' || *src1 == '\r' || *src1 == '\n')) { src1++; } - while (src1 < src2 && (*src2 == ' ' || *src2 == '\t' || *src2 == '\r' || *src2 == '\n')) { src2--; } - src2++; - strncpy(dst, src1, src2 - src1); - dst[src2 - src1] = '\0'; - } -} // namespace + if (!src1 || *src1 == '\0') { dst[0] = '\0'; } + if (!src2) { src2 = src1 + strlen(src1) - 1; } + while (src1 < src2 && (*src1 == ' ' || *src1 == '\t' || *src1 == '\r' || *src1 == '\n')) { src1++; } + while (src1 < src2 && (*src2 == ' ' || *src2 == '\t' || *src2 == '\r' || *src2 == '\n')) { src2--; } + src2++; + strncpy(dst, src1, src2 - src1); + dst[src2 - src1] = '\0'; +} +} // namespace // ________________________________________________________________________________________________________________ // @@ -65,7 +64,7 @@ void CStreamedMatrixDecoder::openChild(const EBML::CIdentifier& id) || (top == OVTK_NodeId_Header_StreamedMatrix_DimensionCount) || (top == OVTK_NodeId_Header_StreamedMatrix_Dimension_Size) || (top == OVTK_NodeId_Header_StreamedMatrix_Dimension_Label) - || (top == OVTK_NodeId_Buffer_StreamedMatrix) + || (top == OVTK_NodeId_Buffer_StreamedMatrix) || (top == OVTK_NodeId_Buffer_StreamedMatrix_RawBuffer)) { if (top == OVTK_NodeId_Header_StreamedMatrix && m_status == EParsingStatus::Nothing) diff --git a/plugins/processing/stream-codecs/src/algorithms/decoders/ovpCStreamedMatrixDecoder.h b/plugins/processing/stream-codecs/src/algorithms/decoders/ovpCStreamedMatrixDecoder.h index 63e2eb6adeb5c4a13bd1a3242651c14d1a6dd22c..9175e694ba5bd5c4580bdd32f753adff2ac22a7d 100644 --- a/plugins/processing/stream-codecs/src/algorithms/decoders/ovpCStreamedMatrixDecoder.h +++ b/plugins/processing/stream-codecs/src/algorithms/decoders/ovpCStreamedMatrixDecoder.h @@ -4,75 +4,69 @@ #include "ovpCEBMLBaseDecoder.h" #include <stack> -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace StreamCodecs { +class CStreamedMatrixDecoder : public CEBMLBaseDecoder { - namespace Plugins - { - namespace StreamCodecs - { - class CStreamedMatrixDecoder : public CEBMLBaseDecoder - { - public: - - CStreamedMatrixDecoder() { } - void release() override { delete this; } - bool initialize() override; - bool uninitialize() override; - - _IsDerivedFromClass_Final_(StreamCodecs::CEBMLBaseDecoder, OVP_ClassId_Algorithm_StreamedMatrixDecoder) - - // ebml callbacks - bool isMasterChild(const EBML::CIdentifier& id) override; - void openChild(const EBML::CIdentifier& id) override; - void processChildData(const void* buffer, const size_t size) override; - void closeChild() override; +public: - protected: + CStreamedMatrixDecoder() { } + void release() override { delete this; } + bool initialize() override; + bool uninitialize() override; - Kernel::TParameterHandler<IMatrix*> op_pMatrix; + _IsDerivedFromClass_Final_(StreamCodecs::CEBMLBaseDecoder, OVP_ClassId_Algorithm_StreamedMatrixDecoder) - private: + // ebml callbacks + bool isMasterChild(const EBML::CIdentifier& id) override; + void openChild(const EBML::CIdentifier& id) override; + void processChildData(const void* buffer, const size_t size) override; + void closeChild() override; - enum class EParsingStatus { Nothing, Header, Buffer, Dimension }; +protected: - std::stack<EBML::CIdentifier> m_nodes; + Kernel::TParameterHandler<IMatrix*> op_pMatrix; - EParsingStatus m_status = EParsingStatus::Nothing; - size_t m_dimensionIdx = 0; - size_t m_dimensionEntryIdx = 0; - // size_t mdimensionEntryIdxUnit = 0; - size_t m_size = 0; - }; +private: - class CStreamedMatrixDecoderDesc : public CEBMLBaseDecoderDesc - { - public: - void release() override { } - CString getName() const override { return CString("Streamed matrix stream decoder"); } - CString getAuthorName() const override { return CString("Yann Renard"); } - CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } - CString getShortDescription() const override { return CString(""); } - CString getDetailedDescription() const override { return CString(""); } - CString getCategory() const override { return CString("Stream codecs/Decoders"); } - CString getVersion() const override { return CString("1.0"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_Algorithm_StreamedMatrixDecoder; } - IPluginObject* create() override { return new CStreamedMatrixDecoder(); } + enum class EParsingStatus { Nothing, Header, Buffer, Dimension }; - bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override - { - CEBMLBaseDecoderDesc::getAlgorithmPrototype(prototype); + std::stack<EBML::CIdentifier> m_nodes; - prototype.addOutputParameter( - OVP_Algorithm_StreamedMatrixDecoder_OutputParameterId_Matrix, "Matrix", Kernel::ParameterType_Matrix); + EParsingStatus m_status = EParsingStatus::Nothing; + size_t m_dimensionIdx = 0; + size_t m_dimensionEntryIdx = 0; + // size_t mdimensionEntryIdxUnit = 0; + size_t m_size = 0; +}; - return true; - } - - _IsDerivedFromClass_Final_(StreamCodecs::CEBMLBaseDecoderDesc, OVP_ClassId_Algorithm_StreamedMatrixDecoderDesc) - }; - } // namespace StreamCodecs - } // namespace Plugins +class CStreamedMatrixDecoderDesc : public CEBMLBaseDecoderDesc +{ +public: + void release() override { } + CString getName() const override { return CString("Streamed matrix stream decoder"); } + CString getAuthorName() const override { return CString("Yann Renard"); } + CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } + CString getShortDescription() const override { return CString(""); } + CString getDetailedDescription() const override { return CString(""); } + CString getCategory() const override { return CString("Stream codecs/Decoders"); } + CString getVersion() const override { return CString("1.0"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_Algorithm_StreamedMatrixDecoder; } + IPluginObject* create() override { return new CStreamedMatrixDecoder(); } + + bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override + { + CEBMLBaseDecoderDesc::getAlgorithmPrototype(prototype); + prototype.addOutputParameter(OVP_Algorithm_StreamedMatrixDecoder_OutputParameterId_Matrix, "Matrix", Kernel::ParameterType_Matrix); + return true; + } + + _IsDerivedFromClass_Final_(StreamCodecs::CEBMLBaseDecoderDesc, OVP_ClassId_Algorithm_StreamedMatrixDecoderDesc) +}; +} // namespace StreamCodecs +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/stream-codecs/src/algorithms/encoders/ovpCAcquisitionEncoder.h b/plugins/processing/stream-codecs/src/algorithms/encoders/ovpCAcquisitionEncoder.h index 14dd8c90d0c431be976ee8ebeff8216c536dec1a..526a311ceccf9314a6be9ffeb230f09ed008dd6f 100644 --- a/plugins/processing/stream-codecs/src/algorithms/encoders/ovpCAcquisitionEncoder.h +++ b/plugins/processing/stream-codecs/src/algorithms/encoders/ovpCAcquisitionEncoder.h @@ -3,76 +3,67 @@ #include "../../ovp_defines.h" #include "ovpCEBMLBaseEncoder.h" -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace StreamCodecs { +class CAcquisitionEncoder final : public CEBMLBaseEncoder { - namespace Plugins - { - namespace StreamCodecs - { - class CAcquisitionEncoder final : public CEBMLBaseEncoder - { - public: - void release() override { delete this; } - bool initialize() override; - bool uninitialize() override; - bool processHeader() override; - bool processBuffer() override; +public: + void release() override { delete this; } + bool initialize() override; + bool uninitialize() override; + bool processHeader() override; + bool processBuffer() override; - _IsDerivedFromClass_Final_(StreamCodecs::CEBMLBaseEncoder, OVP_ClassId_Algorithm_AcquisitionEncoder) + _IsDerivedFromClass_Final_(StreamCodecs::CEBMLBaseEncoder, OVP_ClassId_Algorithm_AcquisitionEncoder) - protected: +protected: - Kernel::TParameterHandler<uint64_t> ip_bufferDuration; - Kernel::TParameterHandler<IMemoryBuffer*> ip_experimentInfoStream; - Kernel::TParameterHandler<IMemoryBuffer*> ip_signalStream; - Kernel::TParameterHandler<IMemoryBuffer*> ip_stimulationStream; - Kernel::TParameterHandler<IMemoryBuffer*> ip_channelLocalisationStream; - Kernel::TParameterHandler<IMemoryBuffer*> ip_channelUnitsStream; - }; + Kernel::TParameterHandler<uint64_t> ip_bufferDuration; + Kernel::TParameterHandler<IMemoryBuffer*> ip_experimentInfoStream; + Kernel::TParameterHandler<IMemoryBuffer*> ip_signalStream; + Kernel::TParameterHandler<IMemoryBuffer*> ip_stimulationStream; + Kernel::TParameterHandler<IMemoryBuffer*> ip_channelLocalisationStream; + Kernel::TParameterHandler<IMemoryBuffer*> ip_channelUnitsStream; +}; - class CAcquisitionEncoderDesc final : public CEBMLBaseEncoderDesc - { - public: - void release() override { } - CString getName() const override { return CString("Acquisition stream encoder"); } - CString getAuthorName() const override { return CString("Yann Renard"); } - CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } - CString getShortDescription() const override { return CString(""); } - CString getDetailedDescription() const override { return CString(""); } - CString getCategory() const override { return CString("Stream codecs/Encoders"); } - CString getVersion() const override { return CString("1.1"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_Algorithm_AcquisitionEncoder; } - IPluginObject* create() override { return new CAcquisitionEncoder(); } +class CAcquisitionEncoderDesc final : public CEBMLBaseEncoderDesc +{ +public: + void release() override { } + CString getName() const override { return CString("Acquisition stream encoder"); } + CString getAuthorName() const override { return CString("Yann Renard"); } + CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } + CString getShortDescription() const override { return CString(""); } + CString getDetailedDescription() const override { return CString(""); } + CString getCategory() const override { return CString("Stream codecs/Encoders"); } + CString getVersion() const override { return CString("1.1"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_Algorithm_AcquisitionEncoder; } + IPluginObject* create() override { return new CAcquisitionEncoder(); } - bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override - { - CEBMLBaseEncoderDesc::getAlgorithmPrototype(prototype); + bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override + { + CEBMLBaseEncoderDesc::getAlgorithmPrototype(prototype); - prototype.addInputParameter( - OVP_Algorithm_AcquisitionEncoder_InputParameterId_BufferDuration, "Buffer duration", Kernel::ParameterType_UInteger); - prototype.addInputParameter( - OVP_Algorithm_AcquisitionEncoder_InputParameterId_ExperimentInfoStream, "Experiment information stream", - Kernel::ParameterType_MemoryBuffer); - prototype.addInputParameter( - OVP_Algorithm_AcquisitionEncoder_InputParameterId_SignalStream, "Signal stream", Kernel::ParameterType_MemoryBuffer); - prototype.addInputParameter( - OVP_Algorithm_AcquisitionEncoder_InputParameterId_StimulationStream, "Stimulation stream", - Kernel::ParameterType_MemoryBuffer); - prototype.addInputParameter( - OVP_Algorithm_AcquisitionEncoder_InputParameterId_ChannelLocalisationStream, "Channel localisation stream", - Kernel::ParameterType_MemoryBuffer); - prototype.addInputParameter( - OVP_Algorithm_AcquisitionEncoder_InputParameterId_ChannelUnitsStream, "Channel units stream", - Kernel::ParameterType_MemoryBuffer); + prototype.addInputParameter(OVP_Algorithm_AcquisitionEncoder_InputParameterId_BufferDuration, "Buffer duration", Kernel::ParameterType_UInteger); + prototype.addInputParameter(OVP_Algorithm_AcquisitionEncoder_InputParameterId_ExperimentInfoStream, "Experiment information stream", + Kernel::ParameterType_MemoryBuffer); + prototype.addInputParameter(OVP_Algorithm_AcquisitionEncoder_InputParameterId_SignalStream, "Signal stream", Kernel::ParameterType_MemoryBuffer); + prototype.addInputParameter(OVP_Algorithm_AcquisitionEncoder_InputParameterId_StimulationStream, "Stimulation stream", + Kernel::ParameterType_MemoryBuffer); + prototype.addInputParameter(OVP_Algorithm_AcquisitionEncoder_InputParameterId_ChannelLocalisationStream, "Channel localisation stream", + Kernel::ParameterType_MemoryBuffer); + prototype.addInputParameter(OVP_Algorithm_AcquisitionEncoder_InputParameterId_ChannelUnitsStream, "Channel units stream", + Kernel::ParameterType_MemoryBuffer); - return true; - } + return true; + } - _IsDerivedFromClass_Final_(StreamCodecs::CEBMLBaseEncoderDesc, OVP_ClassId_Algorithm_AcquisitionEncoderDesc) - }; - } // namespace StreamCodecs - } // namespace Plugins + _IsDerivedFromClass_Final_(StreamCodecs::CEBMLBaseEncoderDesc, OVP_ClassId_Algorithm_AcquisitionEncoderDesc) +}; +} // namespace StreamCodecs +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/stream-codecs/src/algorithms/encoders/ovpCChannelLocalisationEncoder.cpp b/plugins/processing/stream-codecs/src/algorithms/encoders/ovpCChannelLocalisationEncoder.cpp index e1462174f465945cf1fd688bf1fcde4759718515..b82d23c8552ce513fdf43902fa94209a60e45db9 100644 --- a/plugins/processing/stream-codecs/src/algorithms/encoders/ovpCChannelLocalisationEncoder.cpp +++ b/plugins/processing/stream-codecs/src/algorithms/encoders/ovpCChannelLocalisationEncoder.cpp @@ -8,18 +8,14 @@ using namespace StreamCodecs; bool CChannelLocalisationEncoder::initialize() { CStreamedMatrixEncoder::initialize(); - ip_bDynamic.initialize(getInputParameter(OVP_Algorithm_ChannelLocalisationEncoder_InputParameterId_Dynamic)); - return true; } bool CChannelLocalisationEncoder::uninitialize() { ip_bDynamic.uninitialize(); - CStreamedMatrixEncoder::uninitialize(); - return true; } diff --git a/plugins/processing/stream-codecs/src/algorithms/encoders/ovpCChannelLocalisationEncoder.h b/plugins/processing/stream-codecs/src/algorithms/encoders/ovpCChannelLocalisationEncoder.h index d2feb3e3ae92d905ef8c3fcb97c7ca8add34e60d..fdee02ea53a35d0ad9587f8487b5fac9ab50aaed 100644 --- a/plugins/processing/stream-codecs/src/algorithms/encoders/ovpCChannelLocalisationEncoder.h +++ b/plugins/processing/stream-codecs/src/algorithms/encoders/ovpCChannelLocalisationEncoder.h @@ -3,57 +3,53 @@ #include "../../ovp_defines.h" #include "ovpCStreamedMatrixEncoder.h" -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace StreamCodecs { +class CChannelLocalisationEncoder final : public CStreamedMatrixEncoder { - namespace Plugins +public: + void release() override { delete this; } + bool initialize() override; + bool uninitialize() override; + bool processHeader() override; + + _IsDerivedFromClass_Final_(StreamCodecs::CStreamedMatrixEncoder, OVP_ClassId_Algorithm_ChannelLocalisationEncoder) + +protected: + + Kernel::TParameterHandler<bool> ip_bDynamic; +}; + + +class CChannelLocalisationEncoderDesc final : public CStreamedMatrixEncoderDesc +{ +public: + void release() override { } + CString getName() const override { return CString("Channel localisation stream encoder"); } + CString getAuthorName() const override { return CString("Yann Renard"); } + CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } + CString getShortDescription() const override { return CString(""); } + CString getDetailedDescription() const override { return CString(""); } + CString getCategory() const override { return CString("Stream codecs/Encoders"); } + CString getVersion() const override { return CString("1.0"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_Algorithm_ChannelLocalisationEncoder; } + IPluginObject* create() override { return new CChannelLocalisationEncoder(); } + + bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override { - namespace StreamCodecs - { - class CChannelLocalisationEncoder final : public CStreamedMatrixEncoder - { - public: - void release() override { delete this; } - bool initialize() override; - bool uninitialize() override; - bool processHeader() override; - - _IsDerivedFromClass_Final_(StreamCodecs::CStreamedMatrixEncoder, OVP_ClassId_Algorithm_ChannelLocalisationEncoder) - - protected: - - Kernel::TParameterHandler<bool> ip_bDynamic; - }; - - - class CChannelLocalisationEncoderDesc final : public CStreamedMatrixEncoderDesc - { - public: - void release() override { } - CString getName() const override { return CString("Channel localisation stream encoder"); } - CString getAuthorName() const override { return CString("Yann Renard"); } - CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } - CString getShortDescription() const override { return CString(""); } - CString getDetailedDescription() const override { return CString(""); } - CString getCategory() const override { return CString("Stream codecs/Encoders"); } - CString getVersion() const override { return CString("1.0"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_Algorithm_ChannelLocalisationEncoder; } - IPluginObject* create() override { return new CChannelLocalisationEncoder(); } - - bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override - { - CStreamedMatrixEncoderDesc::getAlgorithmPrototype(prototype); - - prototype.addInputParameter( - OVP_Algorithm_ChannelLocalisationEncoder_InputParameterId_Dynamic, "Dynamic", Kernel::ParameterType_Boolean); - - return true; - } - - _IsDerivedFromClass_Final_(StreamCodecs::CStreamedMatrixEncoderDesc, OVP_ClassId_Algorithm_ChannelLocalisationEncoderDesc) - }; - } // namespace StreamCodecs - } // namespace Plugins + CStreamedMatrixEncoderDesc::getAlgorithmPrototype(prototype); + + prototype.addInputParameter(OVP_Algorithm_ChannelLocalisationEncoder_InputParameterId_Dynamic, "Dynamic", Kernel::ParameterType_Boolean); + + return true; + } + + _IsDerivedFromClass_Final_(StreamCodecs::CStreamedMatrixEncoderDesc, OVP_ClassId_Algorithm_ChannelLocalisationEncoderDesc) +}; +} // namespace StreamCodecs +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/stream-codecs/src/algorithms/encoders/ovpCChannelUnitsEncoder.cpp b/plugins/processing/stream-codecs/src/algorithms/encoders/ovpCChannelUnitsEncoder.cpp index 0de13852f28c124dbd9da3606c7d84cbe1ed3c8f..161286e99d96cd20d5c3e7495e7e1c163d4c1174 100644 --- a/plugins/processing/stream-codecs/src/algorithms/encoders/ovpCChannelUnitsEncoder.cpp +++ b/plugins/processing/stream-codecs/src/algorithms/encoders/ovpCChannelUnitsEncoder.cpp @@ -8,18 +8,14 @@ using namespace StreamCodecs; bool CChannelUnitsEncoder::initialize() { CStreamedMatrixEncoder::initialize(); - ip_bDynamic.initialize(getInputParameter(OVP_Algorithm_ChannelUnitsEncoder_InputParameterId_Dynamic)); - return true; } bool CChannelUnitsEncoder::uninitialize() { ip_bDynamic.uninitialize(); - CStreamedMatrixEncoder::uninitialize(); - return true; } diff --git a/plugins/processing/stream-codecs/src/algorithms/encoders/ovpCChannelUnitsEncoder.h b/plugins/processing/stream-codecs/src/algorithms/encoders/ovpCChannelUnitsEncoder.h index c8a545da8bf368208f70a29d3d2e2972b8acdd14..641dc7567c1b564a4690762055abaf7e2bfaf219 100644 --- a/plugins/processing/stream-codecs/src/algorithms/encoders/ovpCChannelUnitsEncoder.h +++ b/plugins/processing/stream-codecs/src/algorithms/encoders/ovpCChannelUnitsEncoder.h @@ -3,58 +3,54 @@ #include "../../ovp_defines.h" #include "ovpCStreamedMatrixEncoder.h" -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace StreamCodecs { +class CChannelUnitsEncoder final : public CStreamedMatrixEncoder { - namespace Plugins +public: + void release() override { delete this; } + bool initialize() override; + bool uninitialize() override; + bool processHeader() override; + + _IsDerivedFromClass_Final_(StreamCodecs::CStreamedMatrixEncoder, OVP_ClassId_Algorithm_ChannelUnitsEncoder) + +protected: + + Kernel::TParameterHandler<bool> ip_bDynamic; +}; + + +class CChannelUnitsEncoderDesc final : public CStreamedMatrixEncoderDesc +{ +public: + void release() override { } + CString getName() const override { return CString("Channel units stream encoder"); } + CString getAuthorName() const override { return CString("Yann Renard"); } + CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } + CString getShortDescription() const override { return CString(""); } + CString getDetailedDescription() const override { return CString(""); } + CString getCategory() const override { return CString("Stream codecs/Encoders"); } + CString getVersion() const override { return CString("1.0"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_Algorithm_ChannelUnitsEncoder; } + IPluginObject* create() override { return new CChannelUnitsEncoder(); } + + bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override { - namespace StreamCodecs - { - class CChannelUnitsEncoder final : public CStreamedMatrixEncoder - { - public: - void release() override { delete this; } - bool initialize() override; - bool uninitialize() override; - bool processHeader() override; - - _IsDerivedFromClass_Final_(StreamCodecs::CStreamedMatrixEncoder, OVP_ClassId_Algorithm_ChannelUnitsEncoder) - - protected: - - Kernel::TParameterHandler<bool> ip_bDynamic; - }; - - - class CChannelUnitsEncoderDesc final : public CStreamedMatrixEncoderDesc - { - public: - void release() override { } - CString getName() const override { return CString("Channel units stream encoder"); } - CString getAuthorName() const override { return CString("Yann Renard"); } - CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } - CString getShortDescription() const override { return CString(""); } - CString getDetailedDescription() const override { return CString(""); } - CString getCategory() const override { return CString("Stream codecs/Encoders"); } - CString getVersion() const override { return CString("1.0"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_Algorithm_ChannelUnitsEncoder; } - IPluginObject* create() override { return new CChannelUnitsEncoder(); } - - bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override - { - CStreamedMatrixEncoderDesc::getAlgorithmPrototype(prototype); - - prototype.addInputParameter( - OVP_Algorithm_ChannelUnitsEncoder_InputParameterId_Dynamic, "Dynamic", Kernel::ParameterType_Boolean); - // prototype.addInputParameter(OVP_Algorithm_ChannelUnitsEncoder_InputParameterId_MeasurementUnits, "Measurement units", Kernel::ParameterType_Matrix); - - return true; - } - - _IsDerivedFromClass_Final_(StreamCodecs::CStreamedMatrixEncoderDesc, OVP_ClassId_Algorithm_ChannelUnitsEncoderDesc) - }; - } // namespace StreamCodecs - } // namespace Plugins + CStreamedMatrixEncoderDesc::getAlgorithmPrototype(prototype); + + prototype.addInputParameter(OVP_Algorithm_ChannelUnitsEncoder_InputParameterId_Dynamic, "Dynamic", Kernel::ParameterType_Boolean); + // prototype.addInputParameter(OVP_Algorithm_ChannelUnitsEncoder_InputParameterId_MeasurementUnits, "Measurement units", Kernel::ParameterType_Matrix); + + return true; + } + + _IsDerivedFromClass_Final_(StreamCodecs::CStreamedMatrixEncoderDesc, OVP_ClassId_Algorithm_ChannelUnitsEncoderDesc) +}; +} // namespace StreamCodecs +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/stream-codecs/src/algorithms/encoders/ovpCEBMLBaseEncoder.h b/plugins/processing/stream-codecs/src/algorithms/encoders/ovpCEBMLBaseEncoder.h index e710fa866464f1b3151cabe75162e8caefa7d80b..e04cfa34ba77e10227a91def9dac14774eeacd2e 100644 --- a/plugins/processing/stream-codecs/src/algorithms/encoders/ovpCEBMLBaseEncoder.h +++ b/plugins/processing/stream-codecs/src/algorithms/encoders/ovpCEBMLBaseEncoder.h @@ -8,55 +8,52 @@ #include <ebml/IWriterHelper.h> #include <ebml/TWriterCallbackProxy.h> -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace StreamCodecs { +class CEBMLBaseEncoder : public Toolkit::TAlgorithm<IAlgorithm> { - namespace Plugins +public: + + CEBMLBaseEncoder() : m_callbackProxy(*this, &CEBMLBaseEncoder::write) {} + void release() override { delete this; } + bool initialize() override; + bool uninitialize() override; + bool process() override; + virtual bool processHeader() { return true; } + virtual bool processBuffer() { return true; } + virtual bool processEnd() { return true; } + + _IsDerivedFromClass_Final_(Toolkit::TAlgorithm<IAlgorithm>, OVP_ClassId_Algorithm_EBMLBaseEncoder) + + // ebml callbacks + virtual void write(const void* buffer, size_t size); + +protected: + + Kernel::TParameterHandler<IMemoryBuffer*> op_buffer; + + EBML::IWriterHelper* m_writerHelper = nullptr; + EBML::IWriter* m_writer = nullptr; + EBML::TWriterCallbackProxy1<CEBMLBaseEncoder> m_callbackProxy; +}; + +class CEBMLBaseEncoderDesc : public IAlgorithmDesc +{ +public: + bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override { - namespace StreamCodecs - { - class CEBMLBaseEncoder : public Toolkit::TAlgorithm<IAlgorithm> - { - public: - - CEBMLBaseEncoder() : m_callbackProxy(*this, &CEBMLBaseEncoder::write) {} - void release() override { delete this; } - bool initialize() override; - bool uninitialize() override; - bool process() override; - virtual bool processHeader() { return true; } - virtual bool processBuffer() { return true; } - virtual bool processEnd() { return true; } - - _IsDerivedFromClass_Final_(Toolkit::TAlgorithm<IAlgorithm>, OVP_ClassId_Algorithm_EBMLBaseEncoder) - - // ebml callbacks - virtual void write(const void* buffer, size_t size); - - protected: - - Kernel::TParameterHandler<IMemoryBuffer*> op_buffer; - - EBML::IWriterHelper* m_writerHelper = nullptr; - EBML::IWriter* m_writer = nullptr; - EBML::TWriterCallbackProxy1<CEBMLBaseEncoder> m_callbackProxy; - }; - - class CEBMLBaseEncoderDesc : public IAlgorithmDesc - { - public: - bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override - { - prototype.addOutputParameter( - OVP_Algorithm_EBMLEncoder_OutputParameterId_EncodedMemoryBuffer, "Encoded memory buffer", Kernel::ParameterType_MemoryBuffer); - prototype.addInputTrigger(OVP_Algorithm_EBMLEncoder_InputTriggerId_EncodeHeader, "Encode header"); - prototype.addInputTrigger(OVP_Algorithm_EBMLEncoder_InputTriggerId_EncodeBuffer, "Encode buffer"); - prototype.addInputTrigger(OVP_Algorithm_EBMLEncoder_InputTriggerId_EncodeEnd, "Encode end"); - - return true; - } - - _IsDerivedFromClass_(IAlgorithmDesc, OVP_ClassId_Algorithm_EBMLBaseEncoderDesc) - }; - } // namespace StreamCodecs - } // namespace Plugins + prototype.addOutputParameter(OVP_Algorithm_EBMLEncoder_OutputParameterId_EncodedMemoryBuffer, "Encoded memory buffer", + Kernel::ParameterType_MemoryBuffer); + prototype.addInputTrigger(OVP_Algorithm_EBMLEncoder_InputTriggerId_EncodeHeader, "Encode header"); + prototype.addInputTrigger(OVP_Algorithm_EBMLEncoder_InputTriggerId_EncodeBuffer, "Encode buffer"); + prototype.addInputTrigger(OVP_Algorithm_EBMLEncoder_InputTriggerId_EncodeEnd, "Encode end"); + + return true; + } + + _IsDerivedFromClass_(IAlgorithmDesc, OVP_ClassId_Algorithm_EBMLBaseEncoderDesc) +}; +} // namespace StreamCodecs +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/stream-codecs/src/algorithms/encoders/ovpCExperimentInfoEncoder.h b/plugins/processing/stream-codecs/src/algorithms/encoders/ovpCExperimentInfoEncoder.h index aad5cb6132e2d228b3434f8167fea6f39298c2a0..92d9f9647193d7fcdb083ed56a11c7a8d1fc0e8b 100644 --- a/plugins/processing/stream-codecs/src/algorithms/encoders/ovpCExperimentInfoEncoder.h +++ b/plugins/processing/stream-codecs/src/algorithms/encoders/ovpCExperimentInfoEncoder.h @@ -3,83 +3,72 @@ #include "../../ovp_defines.h" #include "ovpCEBMLBaseEncoder.h" -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace StreamCodecs { +class CExperimentInfoEncoder final : public CEBMLBaseEncoder { - namespace Plugins - { - namespace StreamCodecs - { - class CExperimentInfoEncoder final : public CEBMLBaseEncoder - { - public: - void release() override { delete this; } - bool initialize() override; - bool uninitialize() override; - bool processHeader() override; +public: + void release() override { delete this; } + bool initialize() override; + bool uninitialize() override; + bool processHeader() override; - _IsDerivedFromClass_Final_(StreamCodecs::CEBMLBaseEncoder, OVP_ClassId_Algorithm_ExperimentInfoEncoder) + _IsDerivedFromClass_Final_(StreamCodecs::CEBMLBaseEncoder, OVP_ClassId_Algorithm_ExperimentInfoEncoder) - protected: +protected: - Kernel::TParameterHandler<uint64_t> ip_ExperimentID; - Kernel::TParameterHandler<CString*> ip_experimentDate; + Kernel::TParameterHandler<uint64_t> ip_ExperimentID; + Kernel::TParameterHandler<CString*> ip_experimentDate; - Kernel::TParameterHandler<uint64_t> ip_subjectID; - Kernel::TParameterHandler<CString*> ip_subjectName; - Kernel::TParameterHandler<uint64_t> ip_subjectAge; - Kernel::TParameterHandler<uint64_t> ip_subjectGender; + Kernel::TParameterHandler<uint64_t> ip_subjectID; + Kernel::TParameterHandler<CString*> ip_subjectName; + Kernel::TParameterHandler<uint64_t> ip_subjectAge; + Kernel::TParameterHandler<uint64_t> ip_subjectGender; - Kernel::TParameterHandler<uint64_t> ip_LaboratoryID; - Kernel::TParameterHandler<CString*> ip_pLaboratoryName; - Kernel::TParameterHandler<uint64_t> ip_TechnicianID; - Kernel::TParameterHandler<CString*> ip_pTechnicianName; - }; + Kernel::TParameterHandler<uint64_t> ip_LaboratoryID; + Kernel::TParameterHandler<CString*> ip_pLaboratoryName; + Kernel::TParameterHandler<uint64_t> ip_TechnicianID; + Kernel::TParameterHandler<CString*> ip_pTechnicianName; +}; - class CExperimentInfoEncoderDesc final : public CEBMLBaseEncoderDesc - { - public: - void release() override { } - CString getName() const override { return CString("Experiment information stream encoder"); } - CString getAuthorName() const override { return CString("Yann Renard"); } - CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } - CString getShortDescription() const override { return CString(""); } - CString getDetailedDescription() const override { return CString(""); } - CString getCategory() const override { return CString("Stream codecs/Encoders"); } - CString getVersion() const override { return CString("1.0"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_Algorithm_ExperimentInfoEncoder; } - IPluginObject* create() override { return new CExperimentInfoEncoder(); } +class CExperimentInfoEncoderDesc final : public CEBMLBaseEncoderDesc +{ +public: + void release() override { } + CString getName() const override { return CString("Experiment information stream encoder"); } + CString getAuthorName() const override { return CString("Yann Renard"); } + CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } + CString getShortDescription() const override { return CString(""); } + CString getDetailedDescription() const override { return CString(""); } + CString getCategory() const override { return CString("Stream codecs/Encoders"); } + CString getVersion() const override { return CString("1.0"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_Algorithm_ExperimentInfoEncoder; } + IPluginObject* create() override { return new CExperimentInfoEncoder(); } - bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override - { - CEBMLBaseEncoderDesc::getAlgorithmPrototype(prototype); + bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override + { + CEBMLBaseEncoderDesc::getAlgorithmPrototype(prototype); - prototype.addInputParameter( - OVP_Algorithm_ExperimentInfoEncoder_InputParameterId_ExperimentID, "Experiment identifier", Kernel::ParameterType_UInteger); - prototype.addInputParameter( - OVP_Algorithm_ExperimentInfoEncoder_InputParameterId_ExperimentDate, "Experiment date", Kernel::ParameterType_String); - prototype.addInputParameter( - OVP_Algorithm_ExperimentInfoEncoder_InputParameterId_SubjectID, "Subject identifier", Kernel::ParameterType_UInteger); - prototype.addInputParameter(OVP_Algorithm_ExperimentInfoEncoder_InputParameterId_SubjectName, "Subject name", Kernel::ParameterType_String); - prototype.addInputParameter(OVP_Algorithm_ExperimentInfoEncoder_InputParameterId_SubjectAge, "Subject age", Kernel::ParameterType_UInteger); - prototype.addInputParameter( - OVP_Algorithm_ExperimentInfoEncoder_InputParameterId_SubjectGender, "Subject gender", Kernel::ParameterType_UInteger); - prototype.addInputParameter( - OVP_Algorithm_ExperimentInfoEncoder_InputParameterId_LaboratoryID, "Laboratory identifier", Kernel::ParameterType_UInteger); - prototype.addInputParameter( - OVP_Algorithm_ExperimentInfoEncoder_InputParameterId_LaboratoryName, "Laboratory name", Kernel::ParameterType_String); - prototype.addInputParameter( - OVP_Algorithm_ExperimentInfoEncoder_InputParameterId_TechnicianID, "Technician identifier", Kernel::ParameterType_UInteger); - prototype.addInputParameter( - OVP_Algorithm_ExperimentInfoEncoder_InputParameterId_TechnicianName, "Technician name", Kernel::ParameterType_String); + prototype.addInputParameter(OVP_Algorithm_ExperimentInfoEncoder_InputParameterId_ExperimentID, "Experiment identifier", Kernel::ParameterType_UInteger); + prototype.addInputParameter(OVP_Algorithm_ExperimentInfoEncoder_InputParameterId_ExperimentDate, "Experiment date", Kernel::ParameterType_String); + prototype.addInputParameter(OVP_Algorithm_ExperimentInfoEncoder_InputParameterId_SubjectID, "Subject identifier", Kernel::ParameterType_UInteger); + prototype.addInputParameter(OVP_Algorithm_ExperimentInfoEncoder_InputParameterId_SubjectName, "Subject name", Kernel::ParameterType_String); + prototype.addInputParameter(OVP_Algorithm_ExperimentInfoEncoder_InputParameterId_SubjectAge, "Subject age", Kernel::ParameterType_UInteger); + prototype.addInputParameter(OVP_Algorithm_ExperimentInfoEncoder_InputParameterId_SubjectGender, "Subject gender", Kernel::ParameterType_UInteger); + prototype.addInputParameter(OVP_Algorithm_ExperimentInfoEncoder_InputParameterId_LaboratoryID, "Laboratory identifier", Kernel::ParameterType_UInteger); + prototype.addInputParameter(OVP_Algorithm_ExperimentInfoEncoder_InputParameterId_LaboratoryName, "Laboratory name", Kernel::ParameterType_String); + prototype.addInputParameter(OVP_Algorithm_ExperimentInfoEncoder_InputParameterId_TechnicianID, "Technician identifier", Kernel::ParameterType_UInteger); + prototype.addInputParameter(OVP_Algorithm_ExperimentInfoEncoder_InputParameterId_TechnicianName, "Technician name", Kernel::ParameterType_String); - return true; - } + return true; + } - _IsDerivedFromClass_Final_(StreamCodecs::CEBMLBaseEncoderDesc, OVP_ClassId_Algorithm_ExperimentInfoEncoderDesc) - }; - } // namespace StreamCodecs - } // namespace Plugins + _IsDerivedFromClass_Final_(StreamCodecs::CEBMLBaseEncoderDesc, OVP_ClassId_Algorithm_ExperimentInfoEncoderDesc) +}; +} // namespace StreamCodecs +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/stream-codecs/src/algorithms/encoders/ovpCFeatureVectorEncoder.cpp b/plugins/processing/stream-codecs/src/algorithms/encoders/ovpCFeatureVectorEncoder.cpp index 330b957ae8da39a958354099cc52e01e8612b074..4266883ec4107ebdba2ff1cb88b3c10e9323f1a9 100644 --- a/plugins/processing/stream-codecs/src/algorithms/encoders/ovpCFeatureVectorEncoder.cpp +++ b/plugins/processing/stream-codecs/src/algorithms/encoders/ovpCFeatureVectorEncoder.cpp @@ -5,7 +5,6 @@ using namespace /*OpenViBE::*/Kernel; using namespace /*OpenViBE::*/Plugins; using namespace StreamCodecs; - bool CFeatureVectorEncoder::processHeader() { OV_ERROR_UNLESS_KRF(ip_pMatrix->getDimensionCount() == 1, "Invalid feature vector: found " << ip_pMatrix->getDimensionCount() << " dimensions, 1 expected", diff --git a/plugins/processing/stream-codecs/src/algorithms/encoders/ovpCFeatureVectorEncoder.h b/plugins/processing/stream-codecs/src/algorithms/encoders/ovpCFeatureVectorEncoder.h index b87d69b559ada94780c433470aaa286a7480817e..9d0e610b41e747463cea981f407b22fcc2229aae 100644 --- a/plugins/processing/stream-codecs/src/algorithms/encoders/ovpCFeatureVectorEncoder.h +++ b/plugins/processing/stream-codecs/src/algorithms/encoders/ovpCFeatureVectorEncoder.h @@ -3,47 +3,43 @@ #include "../../ovp_defines.h" #include "ovpCStreamedMatrixEncoder.h" -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace StreamCodecs { +class CFeatureVectorEncoder final : public CStreamedMatrixEncoder { - namespace Plugins - { - namespace StreamCodecs - { - class CFeatureVectorEncoder final : public CStreamedMatrixEncoder - { - public: - void release() override { delete this; } - bool processHeader() override; - - _IsDerivedFromClass_Final_(StreamCodecs::CStreamedMatrixEncoder, OVP_ClassId_Algorithm_FeatureVectorEncoder) - }; +public: + void release() override { delete this; } + bool processHeader() override; - class CFeatureVectorEncoderDesc final : public CStreamedMatrixEncoderDesc - { - public: - void release() override { } - CString getName() const override { return CString("Feature vector stream encoder"); } - CString getAuthorName() const override { return CString("Yann Renard"); } - CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } - CString getShortDescription() const override { return CString(""); } - CString getDetailedDescription() const override { return CString(""); } - CString getCategory() const override { return CString("Stream codecs/Encoders"); } - CString getVersion() const override { return CString("1.0"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_Algorithm_FeatureVectorEncoder; } - IPluginObject* create() override { return new CFeatureVectorEncoder(); } + _IsDerivedFromClass_Final_(StreamCodecs::CStreamedMatrixEncoder, OVP_ClassId_Algorithm_FeatureVectorEncoder) +}; - bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override - { - CStreamedMatrixEncoderDesc::getAlgorithmPrototype(prototype); +class CFeatureVectorEncoderDesc final : public CStreamedMatrixEncoderDesc +{ +public: + void release() override { } + CString getName() const override { return CString("Feature vector stream encoder"); } + CString getAuthorName() const override { return CString("Yann Renard"); } + CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } + CString getShortDescription() const override { return CString(""); } + CString getDetailedDescription() const override { return CString(""); } + CString getCategory() const override { return CString("Stream codecs/Encoders"); } + CString getVersion() const override { return CString("1.0"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_Algorithm_FeatureVectorEncoder; } + IPluginObject* create() override { return new CFeatureVectorEncoder(); } - return true; - } + bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override + { + CStreamedMatrixEncoderDesc::getAlgorithmPrototype(prototype); + return true; + } - _IsDerivedFromClass_Final_(StreamCodecs::CStreamedMatrixEncoderDesc, OVP_ClassId_Algorithm_FeatureVectorEncoderDesc) - }; - } // namespace StreamCodecs - } // namespace Plugins + _IsDerivedFromClass_Final_(StreamCodecs::CStreamedMatrixEncoderDesc, OVP_ClassId_Algorithm_FeatureVectorEncoderDesc) +}; +} // namespace StreamCodecs +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/stream-codecs/src/algorithms/encoders/ovpCMasterAcquisitionEncoder.cpp b/plugins/processing/stream-codecs/src/algorithms/encoders/ovpCMasterAcquisitionEncoder.cpp index f9a4291a9208be1fd28aff9845763575b6888b80..af5a64bff4d1cff63274af253b5e785863a3c822 100644 --- a/plugins/processing/stream-codecs/src/algorithms/encoders/ovpCMasterAcquisitionEncoder.cpp +++ b/plugins/processing/stream-codecs/src/algorithms/encoders/ovpCMasterAcquisitionEncoder.cpp @@ -12,7 +12,7 @@ using namespace /*OpenViBE::*/Plugins; using namespace StreamCodecs; bool CMasterAcquisitionEncoder::initialize() -{ +{ // Manages sub-algorithms m_acquisitionStreamEncoder = &this->getAlgorithmManager().getAlgorithm( @@ -107,7 +107,6 @@ bool CMasterAcquisitionEncoder::initialize() m_channelUnitsStreamEncoder->getOutputParameter(OVP_Algorithm_EBMLEncoder_OutputParameterId_EncodedMemoryBuffer)); - // Manage parameter connection / referencing | this algorithm to sub algorithm ip_ExperimentInfoSubjectID.setReferenceTarget(ip_subjectID); diff --git a/plugins/processing/stream-codecs/src/algorithms/encoders/ovpCMasterAcquisitionEncoder.h b/plugins/processing/stream-codecs/src/algorithms/encoders/ovpCMasterAcquisitionEncoder.h index 3222c65d9e09e301e344cbef0c49a55516d3f031..7b06109aed8065a0c189546b8cc641910c28822b 100644 --- a/plugins/processing/stream-codecs/src/algorithms/encoders/ovpCMasterAcquisitionEncoder.h +++ b/plugins/processing/stream-codecs/src/algorithms/encoders/ovpCMasterAcquisitionEncoder.h @@ -3,88 +3,77 @@ #include "../../ovp_defines.h" #include "ovpCEBMLBaseEncoder.h" -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace StreamCodecs { +class CMasterAcquisitionEncoder final : public Toolkit::TAlgorithm<IAlgorithm> { - namespace Plugins - { - namespace StreamCodecs - { - class CMasterAcquisitionEncoder final : public Toolkit::TAlgorithm<IAlgorithm> - { - public: - void release() override { delete this; } - bool initialize() override; - bool uninitialize() override; - bool process() override; +public: + void release() override { delete this; } + bool initialize() override; + bool uninitialize() override; + bool process() override; - _IsDerivedFromClass_Final_(Toolkit::TAlgorithm<IAlgorithm>, OVP_ClassId_Algorithm_MasterAcquisitionEncoder) + _IsDerivedFromClass_Final_(Toolkit::TAlgorithm<IAlgorithm>, OVP_ClassId_Algorithm_MasterAcquisitionEncoder) - protected: +protected: - Kernel::IAlgorithmProxy* m_acquisitionStreamEncoder = nullptr; - Kernel::IAlgorithmProxy* m_experimentInfoStreamEncoder = nullptr; - Kernel::IAlgorithmProxy* m_signalStreamEncoder = nullptr; - Kernel::IAlgorithmProxy* m_stimulationStreamEncoder = nullptr; - Kernel::IAlgorithmProxy* m_channelLocalisationStreamEncoder = nullptr; - Kernel::IAlgorithmProxy* m_channelUnitsStreamEncoder = nullptr; - }; + Kernel::IAlgorithmProxy* m_acquisitionStreamEncoder = nullptr; + Kernel::IAlgorithmProxy* m_experimentInfoStreamEncoder = nullptr; + Kernel::IAlgorithmProxy* m_signalStreamEncoder = nullptr; + Kernel::IAlgorithmProxy* m_stimulationStreamEncoder = nullptr; + Kernel::IAlgorithmProxy* m_channelLocalisationStreamEncoder = nullptr; + Kernel::IAlgorithmProxy* m_channelUnitsStreamEncoder = nullptr; +}; - class CMasterAcquisitionEncoderDesc final : public IAlgorithmDesc - { - public: - void release() override { } - CString getName() const override { return CString("Master acquisition stream encoder"); } - CString getAuthorName() const override { return CString("Yann Renard"); } - CString getAuthorCompanyName() const override { return CString("INRIA"); } - CString getShortDescription() const override { return CString(""); } - CString getDetailedDescription() const override { return CString(""); } - CString getCategory() const override { return CString("Stream codecs/Encoders"); } - CString getVersion() const override { return CString("1.1"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_Algorithm_MasterAcquisitionEncoder; } - IPluginObject* create() override { return new CMasterAcquisitionEncoder(); } +class CMasterAcquisitionEncoderDesc final : public IAlgorithmDesc +{ +public: + void release() override { } + CString getName() const override { return CString("Master acquisition stream encoder"); } + CString getAuthorName() const override { return CString("Yann Renard"); } + CString getAuthorCompanyName() const override { return CString("INRIA"); } + CString getShortDescription() const override { return CString(""); } + CString getDetailedDescription() const override { return CString(""); } + CString getCategory() const override { return CString("Stream codecs/Encoders"); } + CString getVersion() const override { return CString("1.1"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_Algorithm_MasterAcquisitionEncoder; } + IPluginObject* create() override { return new CMasterAcquisitionEncoder(); } - bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override - { - prototype.addInputTrigger(OVP_Algorithm_EBMLEncoder_InputTriggerId_EncodeHeader, "Encode header"); - prototype.addInputTrigger(OVP_Algorithm_EBMLEncoder_InputTriggerId_EncodeBuffer, "Encode buffer"); - prototype.addInputTrigger(OVP_Algorithm_EBMLEncoder_InputTriggerId_EncodeEnd, "Encode end"); + bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override + { + prototype.addInputTrigger(OVP_Algorithm_EBMLEncoder_InputTriggerId_EncodeHeader, "Encode header"); + prototype.addInputTrigger(OVP_Algorithm_EBMLEncoder_InputTriggerId_EncodeBuffer, "Encode buffer"); + prototype.addInputTrigger(OVP_Algorithm_EBMLEncoder_InputTriggerId_EncodeEnd, "Encode end"); - prototype.addInputParameter( - OVP_Algorithm_MasterAcquisitionEncoder_InputParameterId_SubjectID, "Subject identifier", Kernel::ParameterType_UInteger); - prototype.addInputParameter( - OVP_Algorithm_MasterAcquisitionEncoder_InputParameterId_SubjectAge, "Subject age", Kernel::ParameterType_UInteger); - prototype.addInputParameter( - OVP_Algorithm_MasterAcquisitionEncoder_InputParameterId_SubjectGender, "Subject gender", Kernel::ParameterType_UInteger); - prototype.addInputParameter( - OVP_Algorithm_MasterAcquisitionEncoder_InputParameterId_SignalMatrix, "Signal matrix", Kernel::ParameterType_Matrix); - prototype.addInputParameter( - OVP_Algorithm_MasterAcquisitionEncoder_InputParameterId_SignalSampling, "Signal sampling rate", Kernel::ParameterType_UInteger); - prototype.addInputParameter( - OVP_Algorithm_MasterAcquisitionEncoder_InputParameterId_StimulationSet, "Stimulation set", Kernel::ParameterType_StimulationSet); - prototype.addInputParameter( - OVP_Algorithm_MasterAcquisitionEncoder_InputParameterId_BufferDuration, "Buffer duration", Kernel::ParameterType_UInteger); - prototype.addInputParameter( - OVP_Algorithm_MasterAcquisitionEncoder_InputParameterId_ChannelLocalisation, "Channel localisation", Kernel::ParameterType_Matrix); - prototype.addInputParameter( - OVP_Algorithm_MasterAcquisitionEncoder_InputParameterId_ChannelUnits, "Channel units", Kernel::ParameterType_Matrix); - prototype.addInputParameter( - OVP_Algorithm_MasterAcquisitionEncoder_InputParameterId_EncodeChannelLocalisationData, "Encode channel localisation data", - Kernel::ParameterType_Boolean); - prototype.addInputParameter( - OVP_Algorithm_MasterAcquisitionEncoder_InputParameterId_EncodeChannelUnitData, "Encode channel unit data", - Kernel::ParameterType_Boolean); + prototype.addInputParameter(OVP_Algorithm_MasterAcquisitionEncoder_InputParameterId_SubjectID, "Subject identifier", Kernel::ParameterType_UInteger); + prototype.addInputParameter(OVP_Algorithm_MasterAcquisitionEncoder_InputParameterId_SubjectAge, "Subject age", Kernel::ParameterType_UInteger); + prototype.addInputParameter(OVP_Algorithm_MasterAcquisitionEncoder_InputParameterId_SubjectGender, "Subject gender", Kernel::ParameterType_UInteger); + prototype.addInputParameter(OVP_Algorithm_MasterAcquisitionEncoder_InputParameterId_SignalMatrix, "Signal matrix", Kernel::ParameterType_Matrix); + prototype.addInputParameter(OVP_Algorithm_MasterAcquisitionEncoder_InputParameterId_SignalSampling, "Signal sampling rate", + Kernel::ParameterType_UInteger); + prototype.addInputParameter(OVP_Algorithm_MasterAcquisitionEncoder_InputParameterId_StimulationSet, "Stimulation set", + Kernel::ParameterType_StimulationSet); + prototype.addInputParameter(OVP_Algorithm_MasterAcquisitionEncoder_InputParameterId_BufferDuration, "Buffer duration", Kernel::ParameterType_UInteger); + prototype.addInputParameter(OVP_Algorithm_MasterAcquisitionEncoder_InputParameterId_ChannelLocalisation, "Channel localisation", + Kernel::ParameterType_Matrix); + prototype.addInputParameter(OVP_Algorithm_MasterAcquisitionEncoder_InputParameterId_ChannelUnits, "Channel units", Kernel::ParameterType_Matrix); + prototype.addInputParameter(OVP_Algorithm_MasterAcquisitionEncoder_InputParameterId_EncodeChannelLocalisationData, "Encode channel localisation data", + Kernel::ParameterType_Boolean); + prototype.addInputParameter(OVP_Algorithm_MasterAcquisitionEncoder_InputParameterId_EncodeChannelUnitData, "Encode channel unit data", + Kernel::ParameterType_Boolean); - prototype.addOutputParameter( - OVP_Algorithm_EBMLEncoder_OutputParameterId_EncodedMemoryBuffer, "Encoded memory buffer", Kernel::ParameterType_MemoryBuffer); + prototype.addOutputParameter(OVP_Algorithm_EBMLEncoder_OutputParameterId_EncodedMemoryBuffer, "Encoded memory buffer", + Kernel::ParameterType_MemoryBuffer); - return true; - } + return true; + } - _IsDerivedFromClass_Final_(IAlgorithmDesc, OVP_ClassId_Algorithm_MasterAcquisitionEncoderDesc) - }; - } // namespace StreamCodecs - } // namespace Plugins + _IsDerivedFromClass_Final_(IAlgorithmDesc, OVP_ClassId_Algorithm_MasterAcquisitionEncoderDesc) +}; +} // namespace StreamCodecs +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/stream-codecs/src/algorithms/encoders/ovpCSignalEncoder.cpp b/plugins/processing/stream-codecs/src/algorithms/encoders/ovpCSignalEncoder.cpp index b729c4af7226eaf95b0c146d15110703b8db6d40..5fa3e012eded45670867c2af03a532585f2df289 100644 --- a/plugins/processing/stream-codecs/src/algorithms/encoders/ovpCSignalEncoder.cpp +++ b/plugins/processing/stream-codecs/src/algorithms/encoders/ovpCSignalEncoder.cpp @@ -8,18 +8,14 @@ using namespace StreamCodecs; bool CSignalEncoder::initialize() { CStreamedMatrixEncoder::initialize(); - ip_sampling.initialize(getInputParameter(OVP_Algorithm_SignalEncoder_InputParameterId_Sampling)); - return true; } bool CSignalEncoder::uninitialize() { ip_sampling.uninitialize(); - CStreamedMatrixEncoder::uninitialize(); - return true; } diff --git a/plugins/processing/stream-codecs/src/algorithms/encoders/ovpCSignalEncoder.h b/plugins/processing/stream-codecs/src/algorithms/encoders/ovpCSignalEncoder.h index dc12056c326ae6af5695ea95ad4356811522b2ab..477743071a91265d9fbfc39b4ce29cb1ccbc7b51 100644 --- a/plugins/processing/stream-codecs/src/algorithms/encoders/ovpCSignalEncoder.h +++ b/plugins/processing/stream-codecs/src/algorithms/encoders/ovpCSignalEncoder.h @@ -3,57 +3,51 @@ #include "../../ovp_defines.h" #include "ovpCStreamedMatrixEncoder.h" -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace StreamCodecs { +class CSignalEncoder final : public CStreamedMatrixEncoder { - namespace Plugins +public: + void release() override { delete this; } + bool initialize() override; + bool uninitialize() override; + bool processHeader() override; + + _IsDerivedFromClass_Final_(StreamCodecs::CStreamedMatrixEncoder, OVP_ClassId_Algorithm_SignalEncoder) + +protected: + + Kernel::TParameterHandler<uint64_t> ip_sampling; +}; + + +class CSignalEncoderDesc final : public CStreamedMatrixEncoderDesc +{ +public: + void release() override { } + CString getName() const override { return CString("Signal stream encoder"); } + CString getAuthorName() const override { return CString("Yann Renard"); } + CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } + CString getShortDescription() const override { return CString(""); } + CString getDetailedDescription() const override { return CString(""); } + CString getCategory() const override { return CString("Stream codecs/Encoders"); } + CString getVersion() const override { return CString("1.0"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_Algorithm_SignalEncoder; } + IPluginObject* create() override { return new CSignalEncoder(); } + + bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override { - namespace StreamCodecs - { - class CSignalEncoder final : public CStreamedMatrixEncoder - { - public: - void release() override { delete this; } - bool initialize() override; - bool uninitialize() override; - bool processHeader() override; - - _IsDerivedFromClass_Final_(StreamCodecs::CStreamedMatrixEncoder, OVP_ClassId_Algorithm_SignalEncoder) - - protected: - - Kernel::TParameterHandler<uint64_t> ip_sampling; - }; - - - class CSignalEncoderDesc final : public CStreamedMatrixEncoderDesc - { - public: - void release() override { } - CString getName() const override { return CString("Signal stream encoder"); } - CString getAuthorName() const override { return CString("Yann Renard"); } - CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } - CString getShortDescription() const override { return CString(""); } - CString getDetailedDescription() const override { return CString(""); } - CString getCategory() const override { return CString("Stream codecs/Encoders"); } - CString getVersion() const override { return CString("1.0"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_Algorithm_SignalEncoder; } - IPluginObject* create() override { return new CSignalEncoder(); } - - bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override - { - CStreamedMatrixEncoderDesc::getAlgorithmPrototype(prototype); - - prototype.addInputParameter( - OVP_Algorithm_SignalEncoder_InputParameterId_Sampling, "Sampling rate", Kernel::ParameterType_UInteger); - - return true; - } - - _IsDerivedFromClass_Final_(StreamCodecs::CStreamedMatrixEncoderDesc, OVP_ClassId_Algorithm_SignalEncoderDesc) - }; - } // namespace StreamCodecs - } // namespace Plugins + CStreamedMatrixEncoderDesc::getAlgorithmPrototype(prototype); + prototype.addInputParameter(OVP_Algorithm_SignalEncoder_InputParameterId_Sampling, "Sampling rate", Kernel::ParameterType_UInteger); + return true; + } + + _IsDerivedFromClass_Final_(StreamCodecs::CStreamedMatrixEncoderDesc, OVP_ClassId_Algorithm_SignalEncoderDesc) +}; +} // namespace StreamCodecs +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/stream-codecs/src/algorithms/encoders/ovpCSpectrumEncoder.h b/plugins/processing/stream-codecs/src/algorithms/encoders/ovpCSpectrumEncoder.h index 1e8c6727d841056127fcd71136df7438d1831588..c22d1d0706f84801121a84979fb071836a2114f2 100755 --- a/plugins/processing/stream-codecs/src/algorithms/encoders/ovpCSpectrumEncoder.h +++ b/plugins/processing/stream-codecs/src/algorithms/encoders/ovpCSpectrumEncoder.h @@ -3,58 +3,53 @@ #include "../../ovp_defines.h" #include "ovpCStreamedMatrixEncoder.h" -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace StreamCodecs { +class CSpectrumEncoder final : public CStreamedMatrixEncoder { - namespace Plugins +public: + void release() override { delete this; } + bool initialize() override; + bool uninitialize() override; + bool processHeader() override; + + _IsDerivedFromClass_Final_(StreamCodecs::CStreamedMatrixEncoder, OVP_ClassId_Algorithm_SpectrumEncoder) + +protected: + Kernel::TParameterHandler<IMatrix*> ip_frequencyAbscissa; + Kernel::TParameterHandler<uint64_t> ip_sampling; +}; + +class CSpectrumEncoderDesc final : public CStreamedMatrixEncoderDesc +{ +public: + void release() override { } + CString getName() const override { return CString("Spectrum stream encoder"); } + CString getAuthorName() const override { return CString("Yann Renard"); } + CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } + CString getShortDescription() const override { return CString("Encodes a Spectrum stream."); } + CString getDetailedDescription() const override { return CString(""); } + CString getCategory() const override { return CString("Stream codecs/Encoders"); } + CString getVersion() const override { return CString("1.0"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.1.0"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_Algorithm_SpectrumEncoder; } + IPluginObject* create() override { return new CSpectrumEncoder(); } + + bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override { - namespace StreamCodecs - { - class CSpectrumEncoder final : public CStreamedMatrixEncoder - { - public: - void release() override { delete this; } - bool initialize() override; - bool uninitialize() override; - bool processHeader() override; - - _IsDerivedFromClass_Final_(StreamCodecs::CStreamedMatrixEncoder, OVP_ClassId_Algorithm_SpectrumEncoder) - - protected: - Kernel::TParameterHandler<IMatrix*> ip_frequencyAbscissa; - Kernel::TParameterHandler<uint64_t> ip_sampling; - }; - - class CSpectrumEncoderDesc final : public CStreamedMatrixEncoderDesc - { - public: - void release() override { } - CString getName() const override { return CString("Spectrum stream encoder"); } - CString getAuthorName() const override { return CString("Yann Renard"); } - CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } - CString getShortDescription() const override { return CString("Encodes a Spectrum stream."); } - CString getDetailedDescription() const override { return CString(""); } - CString getCategory() const override { return CString("Stream codecs/Encoders"); } - CString getVersion() const override { return CString("1.0"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.1.0"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_Algorithm_SpectrumEncoder; } - IPluginObject* create() override { return new CSpectrumEncoder(); } - - bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override - { - CStreamedMatrixEncoderDesc::getAlgorithmPrototype(prototype); - - prototype.addInputParameter( - OVP_Algorithm_SpectrumEncoder_InputParameterId_FrequencyAbscissa, "Frequency abscissa", Kernel::ParameterType_Matrix); - prototype.addInputParameter( - OVP_Algorithm_SpectrumEncoder_InputParameterId_Sampling, "Sampling rate", Kernel::ParameterType_UInteger); - - return true; - } - - _IsDerivedFromClass_Final_(StreamCodecs::CStreamedMatrixEncoderDesc, OVP_ClassId_Algorithm_SpectrumEncoderDesc) - }; - } // namespace StreamCodecs - } // namespace Plugins + CStreamedMatrixEncoderDesc::getAlgorithmPrototype(prototype); + + prototype.addInputParameter(OVP_Algorithm_SpectrumEncoder_InputParameterId_FrequencyAbscissa, "Frequency abscissa", Kernel::ParameterType_Matrix); + prototype.addInputParameter(OVP_Algorithm_SpectrumEncoder_InputParameterId_Sampling, "Sampling rate", Kernel::ParameterType_UInteger); + + return true; + } + + _IsDerivedFromClass_Final_(StreamCodecs::CStreamedMatrixEncoderDesc, OVP_ClassId_Algorithm_SpectrumEncoderDesc) +}; +} // namespace StreamCodecs +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/stream-codecs/src/algorithms/encoders/ovpCStimulationEncoder.h b/plugins/processing/stream-codecs/src/algorithms/encoders/ovpCStimulationEncoder.h index 893143123a4b7dd88c2f4a069f001f76b62a7828..d03f960099e1e0579b9a13162558424a9016db03 100644 --- a/plugins/processing/stream-codecs/src/algorithms/encoders/ovpCStimulationEncoder.h +++ b/plugins/processing/stream-codecs/src/algorithms/encoders/ovpCStimulationEncoder.h @@ -3,56 +3,50 @@ #include "../../ovp_defines.h" #include "ovpCEBMLBaseEncoder.h" -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace StreamCodecs { +class CStimulationEncoder final : public CEBMLBaseEncoder { - namespace Plugins +public: + void release() override { delete this; } + bool initialize() override; + bool uninitialize() override; + bool processBuffer() override; + + _IsDerivedFromClass_Final_(StreamCodecs::CEBMLBaseEncoder, OVP_ClassId_Algorithm_StimulationEncoder) + +protected: + + Kernel::TParameterHandler<IStimulationSet*> ip_stimSet; +}; + +class CStimulationEncoderDesc final : public CEBMLBaseEncoderDesc +{ +public: + void release() override { } + CString getName() const override { return CString("Stimulation stream encoder"); } + CString getAuthorName() const override { return CString("Yann Renard"); } + CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } + CString getShortDescription() const override { return CString(""); } + CString getDetailedDescription() const override { return CString(""); } + CString getCategory() const override { return CString("Stream codecs/Encoders"); } + CString getVersion() const override { return CString("1.0"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_Algorithm_StimulationEncoder; } + IPluginObject* create() override { return new CStimulationEncoder(); } + + bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override { - namespace StreamCodecs - { - class CStimulationEncoder final : public CEBMLBaseEncoder - { - public: - void release() override { delete this; } - bool initialize() override; - bool uninitialize() override; - bool processBuffer() override; - - _IsDerivedFromClass_Final_(StreamCodecs::CEBMLBaseEncoder, OVP_ClassId_Algorithm_StimulationEncoder) - - protected: - - Kernel::TParameterHandler<IStimulationSet*> ip_stimSet; - }; - - class CStimulationEncoderDesc final : public CEBMLBaseEncoderDesc - { - public: - void release() override { } - CString getName() const override { return CString("Stimulation stream encoder"); } - CString getAuthorName() const override { return CString("Yann Renard"); } - CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } - CString getShortDescription() const override { return CString(""); } - CString getDetailedDescription() const override { return CString(""); } - CString getCategory() const override { return CString("Stream codecs/Encoders"); } - CString getVersion() const override { return CString("1.0"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_Algorithm_StimulationEncoder; } - IPluginObject* create() override { return new CStimulationEncoder(); } - - bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override - { - CEBMLBaseEncoderDesc::getAlgorithmPrototype(prototype); - - prototype.addInputParameter( - OVP_Algorithm_StimulationEncoder_InputParameterId_StimulationSet, "Stimulation set", Kernel::ParameterType_StimulationSet); - - return true; - } - - _IsDerivedFromClass_Final_(StreamCodecs::CEBMLBaseEncoderDesc, OVP_ClassId_Algorithm_StimulationEncoderDesc) - }; - } // namespace StreamCodecs - } // namespace Plugins + CEBMLBaseEncoderDesc::getAlgorithmPrototype(prototype); + prototype.addInputParameter(OVP_Algorithm_StimulationEncoder_InputParameterId_StimulationSet, "Stimulation set", Kernel::ParameterType_StimulationSet); + return true; + } + + _IsDerivedFromClass_Final_(StreamCodecs::CEBMLBaseEncoderDesc, OVP_ClassId_Algorithm_StimulationEncoderDesc) +}; +} // namespace StreamCodecs +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/stream-codecs/src/algorithms/encoders/ovpCStreamedMatrixEncoder.h b/plugins/processing/stream-codecs/src/algorithms/encoders/ovpCStreamedMatrixEncoder.h index 1d5da6e74e7f66f26c5f4e46429bcb0a63e2411b..f3e41a5c33bd1bf6f6bf77d8441cb35e2d356889 100644 --- a/plugins/processing/stream-codecs/src/algorithms/encoders/ovpCStreamedMatrixEncoder.h +++ b/plugins/processing/stream-codecs/src/algorithms/encoders/ovpCStreamedMatrixEncoder.h @@ -3,61 +3,55 @@ #include "../../ovp_defines.h" #include "ovpCEBMLBaseEncoder.h" -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace StreamCodecs { +class CStreamedMatrixEncoder : public CEBMLBaseEncoder { - namespace Plugins +public: + void release() override { delete this; } + bool initialize() override; + bool uninitialize() override; + bool processHeader() override; + bool processBuffer() override; + + _IsDerivedFromClass_Final_(StreamCodecs::CEBMLBaseEncoder, OVP_ClassId_Algorithm_StreamedMatrixEncoder) + +protected: + + Kernel::TParameterHandler<IMatrix*> ip_pMatrix; + +private: + + size_t m_size = 0; +}; + +class CStreamedMatrixEncoderDesc : public CEBMLBaseEncoderDesc +{ +public: + void release() override { } + CString getName() const override { return CString("Streamed matrix stream encoder"); } + CString getAuthorName() const override { return CString("Yann Renard"); } + CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } + CString getShortDescription() const override { return CString(""); } + CString getDetailedDescription() const override { return CString(""); } + CString getCategory() const override { return CString("Stream codecs/Encoders"); } + CString getVersion() const override { return CString("1.0"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_Algorithm_StreamedMatrixEncoder; } + IPluginObject* create() override { return new CStreamedMatrixEncoder(); } + + bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override { - namespace StreamCodecs - { - class CStreamedMatrixEncoder : public CEBMLBaseEncoder - { - public: - void release() override { delete this; } - bool initialize() override; - bool uninitialize() override; - bool processHeader() override; - bool processBuffer() override; - - _IsDerivedFromClass_Final_(StreamCodecs::CEBMLBaseEncoder, OVP_ClassId_Algorithm_StreamedMatrixEncoder) - - protected: - - Kernel::TParameterHandler<IMatrix*> ip_pMatrix; - - private: - - size_t m_size = 0; - }; - - class CStreamedMatrixEncoderDesc : public CEBMLBaseEncoderDesc - { - public: - void release() override { } - CString getName() const override { return CString("Streamed matrix stream encoder"); } - CString getAuthorName() const override { return CString("Yann Renard"); } - CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } - CString getShortDescription() const override { return CString(""); } - CString getDetailedDescription() const override { return CString(""); } - CString getCategory() const override { return CString("Stream codecs/Encoders"); } - CString getVersion() const override { return CString("1.0"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_Algorithm_StreamedMatrixEncoder; } - IPluginObject* create() override { return new CStreamedMatrixEncoder(); } - - bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override - { - CEBMLBaseEncoderDesc::getAlgorithmPrototype(prototype); - - prototype.addInputParameter( - OVP_Algorithm_StreamedMatrixEncoder_InputParameterId_Matrix, "Matrix", Kernel::ParameterType_Matrix); - - return true; - } - - _IsDerivedFromClass_Final_(StreamCodecs::CEBMLBaseEncoderDesc, OVP_ClassId_Algorithm_StreamedMatrixEncoderDesc) - }; - } // namespace StreamCodecs - } // namespace Plugins + CEBMLBaseEncoderDesc::getAlgorithmPrototype(prototype); + prototype.addInputParameter(OVP_Algorithm_StreamedMatrixEncoder_InputParameterId_Matrix, "Matrix", Kernel::ParameterType_Matrix); + return true; + } + + _IsDerivedFromClass_Final_(StreamCodecs::CEBMLBaseEncoderDesc, OVP_ClassId_Algorithm_StreamedMatrixEncoderDesc) +}; +} // namespace StreamCodecs +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/stream-codecs/src/box-algorithms/ovpCDecoderAlgorithmTest.h b/plugins/processing/stream-codecs/src/box-algorithms/ovpCDecoderAlgorithmTest.h index 5bf5374decaf8a1d4bf1d8fc183aec29d1f0ad59..3be261eb2a17d08fa71b5b75e3177b08b8fc5e66 100644 --- a/plugins/processing/stream-codecs/src/box-algorithms/ovpCDecoderAlgorithmTest.h +++ b/plugins/processing/stream-codecs/src/box-algorithms/ovpCDecoderAlgorithmTest.h @@ -4,69 +4,63 @@ #include <toolkit/ovtk_all.h> #include <array> -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace StreamCodecs { +class CDecoderAlgorithmTest final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm> { - namespace Plugins - { - namespace StreamCodecs - { - class CDecoderAlgorithmTest final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm> - { - public: +public: - CDecoderAlgorithmTest() { } - ~CDecoderAlgorithmTest() override { } - void release() override { delete this; } - bool initialize() override; - bool uninitialize() override; - bool processInput(const size_t index) override; - bool process() override; + CDecoderAlgorithmTest() { } + ~CDecoderAlgorithmTest() override { } + void release() override { delete this; } + bool initialize() override; + bool uninitialize() override; + bool processInput(const size_t index) override; + bool process() override; - _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_DecoderAlgorithmTest) + _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_DecoderAlgorithmTest) - protected: +protected: - std::array<Kernel::IAlgorithmProxy*, 7> m_decoder; - std::array<Kernel::TParameterHandler<const IMemoryBuffer*>, 7> ip_buffer; - }; + std::array<Kernel::IAlgorithmProxy*, 7> m_decoder; + std::array<Kernel::TParameterHandler<const IMemoryBuffer*>, 7> ip_buffer; +}; - class CDecoderAlgorithmTestDesc final : public IBoxAlgorithmDesc - { - public: - void release() override { } - CString getName() const override { return CString("Decoder algorithm test"); } - CString getAuthorName() const override { return CString("Yann Renard"); } - CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } +class CDecoderAlgorithmTestDesc final : public IBoxAlgorithmDesc +{ +public: + void release() override { } + CString getName() const override { return CString("Decoder algorithm test"); } + CString getAuthorName() const override { return CString("Yann Renard"); } + CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } - CString getShortDescription() const override - { - return CString("Decodes various types of streams and outputs some of the content parameters the log"); - } + CString getShortDescription() const override { return CString("Decodes various types of streams and outputs some of the content parameters the log"); } - CString getDetailedDescription() const override - { - return CString("Note: Warnings are normal as the algorithm polls the decoders for structures they may not contain."); - } + CString getDetailedDescription() const override + { + return CString("Note: Warnings are normal as the algorithm polls the decoders for structures they may not contain."); + } - CString getCategory() const override { return CString("Tests/Algorithms"); } - CString getVersion() const override { return CString("1.0"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_DecoderAlgorithmTest; } - IPluginObject* create() override { return new CDecoderAlgorithmTest(); } + CString getCategory() const override { return CString("Tests/Algorithms"); } + CString getVersion() const override { return CString("1.0"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_DecoderAlgorithmTest; } + IPluginObject* create() override { return new CDecoderAlgorithmTest(); } - bool getBoxPrototype(Kernel::IBoxProto& prototype) const override - { - prototype.addInput("Experiment information", OV_TypeId_ExperimentInfo); - prototype.addInput("Feature vector", OV_TypeId_FeatureVector); - prototype.addInput("Signal", OV_TypeId_Signal); - prototype.addInput("Spectrum", OV_TypeId_Spectrum); - prototype.addInput("Stimulation", OV_TypeId_Stimulations); - prototype.addInput("Streamed matrix", OV_TypeId_StreamedMatrix); - prototype.addInput("Channel localisation", OV_TypeId_ChannelLocalisation); - return true; - } + bool getBoxPrototype(Kernel::IBoxProto& prototype) const override + { + prototype.addInput("Experiment information", OV_TypeId_ExperimentInfo); + prototype.addInput("Feature vector", OV_TypeId_FeatureVector); + prototype.addInput("Signal", OV_TypeId_Signal); + prototype.addInput("Spectrum", OV_TypeId_Spectrum); + prototype.addInput("Stimulation", OV_TypeId_Stimulations); + prototype.addInput("Streamed matrix", OV_TypeId_StreamedMatrix); + prototype.addInput("Channel localisation", OV_TypeId_ChannelLocalisation); + return true; + } - _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_DecoderAlgorithmTestDesc) - }; - } // namespace StreamCodecs - } // namespace Plugins + _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_DecoderAlgorithmTestDesc) +}; +} // namespace StreamCodecs +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/stream-codecs/src/box-algorithms/ovpCEncoderAlgorithmTest.cpp b/plugins/processing/stream-codecs/src/box-algorithms/ovpCEncoderAlgorithmTest.cpp index 0cd48a0d70775b2883da120e6d3f674ab686b8cb..dc2569a7e20b1dead24f958339240c4e3e129699 100755 --- a/plugins/processing/stream-codecs/src/box-algorithms/ovpCEncoderAlgorithmTest.cpp +++ b/plugins/processing/stream-codecs/src/box-algorithms/ovpCEncoderAlgorithmTest.cpp @@ -90,7 +90,7 @@ bool CEncoderAlgorithmTest::uninitialize() return true; } -bool CEncoderAlgorithmTest::processClock(IMessageClock& /*messageClock*/) +bool CEncoderAlgorithmTest::processClock(Kernel::CMessageClock& /*msg*/) { getBoxAlgorithmContext()->markAlgorithmAsReadyToProcess(); return true; diff --git a/plugins/processing/stream-codecs/src/box-algorithms/ovpCEncoderAlgorithmTest.h b/plugins/processing/stream-codecs/src/box-algorithms/ovpCEncoderAlgorithmTest.h index 1e304dbeecb4b4acb4f0a925e8b84871a9127a0c..60d6e8f91b0c673928c6912981d159acbc66e564 100644 --- a/plugins/processing/stream-codecs/src/box-algorithms/ovpCEncoderAlgorithmTest.h +++ b/plugins/processing/stream-codecs/src/box-algorithms/ovpCEncoderAlgorithmTest.h @@ -4,68 +4,65 @@ #include <toolkit/ovtk_all.h> #include <array> -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace StreamCodecs { +class CEncoderAlgorithmTest : public Toolkit::TBoxAlgorithm<IBoxAlgorithm> { - namespace Plugins - { - namespace StreamCodecs - { - class CEncoderAlgorithmTest : public Toolkit::TBoxAlgorithm<IBoxAlgorithm> - { - public: - void release() override { delete this; } - uint64_t getClockFrequency() override { return 1LL << 32; } - bool initialize() override; - bool uninitialize() override; - bool processClock(Kernel::IMessageClock& messageClock) override; - bool process() override; +public: + void release() override { delete this; } + uint64_t getClockFrequency() override { return 1LL << 32; } + bool initialize() override; + bool uninitialize() override; + bool processClock(Kernel::CMessageClock& msg) override; + bool process() override; - _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_EncoderAlgorithmTest) + _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_EncoderAlgorithmTest) - protected: +protected: - std::array<Kernel::IAlgorithmProxy*, 7> m_encoders; - std::array<Kernel::TParameterHandler<IMemoryBuffer*>, 7> op_buffer; + std::array<Kernel::IAlgorithmProxy*, 7> m_encoders; + std::array<Kernel::TParameterHandler<IMemoryBuffer*>, 7> op_buffer; - bool m_hasSentHeader = false; - uint64_t m_startTime = 0; - uint64_t m_endTime = 0; + bool m_hasSentHeader = false; + uint64_t m_startTime = 0; + uint64_t m_endTime = 0; - CMatrix* m_matrix1 = nullptr; - CMatrix* m_matrix2 = nullptr; - CMatrix* m_matrix3 = nullptr; - CStimulationSet* m_stimSet = nullptr; - }; + CMatrix* m_matrix1 = nullptr; + CMatrix* m_matrix2 = nullptr; + CMatrix* m_matrix3 = nullptr; + CStimulationSet* m_stimSet = nullptr; +}; - class CEncoderAlgorithmTestDesc final : public IBoxAlgorithmDesc - { - public: - void release() override { } - CString getName() const override { return CString("Encoder algorithm test"); } - CString getAuthorName() const override { return CString("Yann Renard"); } - CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } - CString getShortDescription() const override { return CString("Setups various streams and outputs them"); } - CString getDetailedDescription() const override { return CString("Note: Data sent in the streams does not change over time"); } - CString getCategory() const override { return CString("Tests/Algorithms"); } - CString getVersion() const override { return CString("1.0"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_EncoderAlgorithmTest; } - IPluginObject* create() override { return new CEncoderAlgorithmTest(); } +class CEncoderAlgorithmTestDesc final : public IBoxAlgorithmDesc +{ +public: + void release() override { } + CString getName() const override { return CString("Encoder algorithm test"); } + CString getAuthorName() const override { return CString("Yann Renard"); } + CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } + CString getShortDescription() const override { return CString("Setups various streams and outputs them"); } + CString getDetailedDescription() const override { return CString("Note: Data sent in the streams does not change over time"); } + CString getCategory() const override { return CString("Tests/Algorithms"); } + CString getVersion() const override { return CString("1.0"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_EncoderAlgorithmTest; } + IPluginObject* create() override { return new CEncoderAlgorithmTest(); } - bool getBoxPrototype(Kernel::IBoxProto& prototype) const override - { - prototype.addOutput("Experiment information", OV_TypeId_ExperimentInfo); - prototype.addOutput("Feature vector", OV_TypeId_FeatureVector); - prototype.addOutput("Signal", OV_TypeId_Signal); - prototype.addOutput("Spectrum", OV_TypeId_Spectrum); - prototype.addOutput("Stimulation", OV_TypeId_Stimulations); - prototype.addOutput("Streamed matrix", OV_TypeId_StreamedMatrix); - prototype.addOutput("Channel localisation", OV_TypeId_ChannelLocalisation); + bool getBoxPrototype(Kernel::IBoxProto& prototype) const override + { + prototype.addOutput("Experiment information", OV_TypeId_ExperimentInfo); + prototype.addOutput("Feature vector", OV_TypeId_FeatureVector); + prototype.addOutput("Signal", OV_TypeId_Signal); + prototype.addOutput("Spectrum", OV_TypeId_Spectrum); + prototype.addOutput("Stimulation", OV_TypeId_Stimulations); + prototype.addOutput("Streamed matrix", OV_TypeId_StreamedMatrix); + prototype.addOutput("Channel localisation", OV_TypeId_ChannelLocalisation); - return true; - } + return true; + } - _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_EncoderAlgorithmTestDesc) - }; - } // namespace StreamCodecs - } // namespace Plugins + _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_EncoderAlgorithmTestDesc) +}; +} // namespace StreamCodecs +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/streaming/CMakeLists.txt b/plugins/processing/streaming/CMakeLists.txt index 6ad46d40d0c341e42d36d91edf00fdc56d81d55d..e7cafbe6c1538c1df0d9b40f15cc1bdacf588c0c 100644 --- a/plugins/processing/streaming/CMakeLists.txt +++ b/plugins/processing/streaming/CMakeLists.txt @@ -11,6 +11,7 @@ ADD_LIBRARY(${PROJECT_NAME} SHARED ${SRC_FILES}) SET_TARGET_PROPERTIES(${PROJECT_NAME} PROPERTIES VERSION ${PROJECT_VERSION} SOVERSION ${PROJECT_VERSION_MAJOR} + FOLDER ${PLUGINS_FOLDER} COMPILE_FLAGS "-DOVP_Exports -DOVP_Shared") # --------------------------------- @@ -20,9 +21,7 @@ INCLUDE("FindOpenViBEToolkit") # --------------------------------- # Target macros -# Defines target operating system -# Defines target architecture -# Defines target compiler +# Defines target operating system, architecture and compiler # --------------------------------- SET_BUILD_PLATFORM() diff --git a/plugins/processing/streaming/src/box-algorithms/ovpCBoxAlgorithmSignalMerger.cpp b/plugins/processing/streaming/src/box-algorithms/ovpCBoxAlgorithmSignalMerger.cpp index 83654eb15b1ce95ff253f04a2d855bd4926a0e57..942c11df1f94ca3aa7c45724926871c90923fe29 100644 --- a/plugins/processing/streaming/src/box-algorithms/ovpCBoxAlgorithmSignalMerger.cpp +++ b/plugins/processing/streaming/src/box-algorithms/ovpCBoxAlgorithmSignalMerger.cpp @@ -8,11 +8,8 @@ using namespace /*OpenViBE::Plugins::*/Streaming; bool CBoxAlgorithmSignalMerger::initialize() { const size_t nInput = this->getStaticBoxContext().getInputCount(); - for (size_t i = 0; i < nInput; ++i) { m_decoders.push_back(new Toolkit::TSignalDecoder<CBoxAlgorithmSignalMerger>(*this, i)); } - m_encoder = new Toolkit::TSignalEncoder<CBoxAlgorithmSignalMerger>(*this, 0); - return true; } @@ -122,14 +119,9 @@ bool CBoxAlgorithmSignalMerger::process() if (m_decoders[i]->isEndReceived()) { nEnd++; } } - OV_ERROR_UNLESS_KRF(!nHeader || nHeader == nInput, - "Received [" << nHeader << "] headers for [" << nInput << "] declared inputs", ErrorType::BadInput); - - OV_ERROR_UNLESS_KRF(!nBuffer || nBuffer == nInput, - "Received [" << nBuffer << "] buffers for [" << nInput << "] declared inputs", ErrorType::BadInput); - - OV_ERROR_UNLESS_KRF(!nEnd || nEnd == nInput, - "Received [" << nEnd << "] ends for [" << nInput << "] declared inputs", ErrorType::BadInput); + OV_ERROR_UNLESS_KRF(!nHeader || nHeader == nInput, "Received [" << nHeader << "] headers for [" << nInput << "] declared inputs", ErrorType::BadInput); + OV_ERROR_UNLESS_KRF(!nBuffer || nBuffer == nInput, "Received [" << nBuffer << "] buffers for [" << nInput << "] declared inputs", ErrorType::BadInput); + OV_ERROR_UNLESS_KRF(!nEnd || nEnd == nInput, "Received [" << nEnd << "] ends for [" << nInput << "] declared inputs", ErrorType::BadInput); if (nHeader) { diff --git a/plugins/processing/streaming/src/box-algorithms/ovpCBoxAlgorithmSignalMerger.h b/plugins/processing/streaming/src/box-algorithms/ovpCBoxAlgorithmSignalMerger.h index 4ab93fdb0622fc443fd6c52f6dfa7c1f0ee1f573..169055c27d46ba9fb1d015595685379aa9431989 100644 --- a/plugins/processing/streaming/src/box-algorithms/ovpCBoxAlgorithmSignalMerger.h +++ b/plugins/processing/streaming/src/box-algorithms/ovpCBoxAlgorithmSignalMerger.h @@ -5,73 +5,70 @@ #include <toolkit/ovtk_all.h> #include <vector> -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace Streaming { +class CBoxAlgorithmSignalMerger final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm> { - namespace Plugins - { - namespace Streaming - { - class CBoxAlgorithmSignalMerger final : public Toolkit::TBoxAlgorithm<IBoxAlgorithm> - { - public: - void release() override { delete this; } - bool initialize() override; - bool uninitialize() override; - bool processInput(const size_t index) override; - bool process() override; +public: + void release() override { delete this; } + bool initialize() override; + bool uninitialize() override; + bool processInput(const size_t index) override; + bool process() override; - _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_SignalMerger) + _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_SignalMerger) - protected: +protected: - std::vector<Toolkit::TSignalDecoder<CBoxAlgorithmSignalMerger>*> m_decoders; - Toolkit::TSignalEncoder<CBoxAlgorithmSignalMerger>* m_encoder = nullptr; - }; + std::vector<Toolkit::TSignalDecoder<CBoxAlgorithmSignalMerger>*> m_decoders; + Toolkit::TSignalEncoder<CBoxAlgorithmSignalMerger>* m_encoder = nullptr; +}; - class CBoxAlgorithmSignalMergerListener final : public Toolkit::TBoxListener<IBoxListener> - { - public: - bool onInputAdded(Kernel::IBox& box, const size_t index) override - { - box.setInputName(index, ("Input " + std::to_string(index + 1)).c_str()); - box.setInputType(index, OV_TypeId_Signal); - return true; - } +class CBoxAlgorithmSignalMergerListener final : public Toolkit::TBoxListener<IBoxListener> +{ +public: + bool onInputAdded(Kernel::IBox& box, const size_t index) override + { + box.setInputName(index, ("Input " + std::to_string(index + 1)).c_str()); + box.setInputType(index, OV_TypeId_Signal); + return true; + } - _IsDerivedFromClass_Final_(Toolkit::TBoxListener<IBoxListener>, OV_UndefinedIdentifier) - }; + _IsDerivedFromClass_Final_(Toolkit::TBoxListener<IBoxListener>, OV_UndefinedIdentifier) +}; - class CBoxAlgorithmSignalMergerDesc final : public IBoxAlgorithmDesc - { - public: - void release() override { } - CString getName() const override { return CString("Signal Merger"); } - CString getAuthorName() const override { return CString("Yann Renard"); } - CString getAuthorCompanyName() const override { return CString("INRIA"); } - CString getShortDescription() const override { return CString("Merges several input streams into a single output stream"); } - CString getDetailedDescription() const override { return CString(""); } - CString getCategory() const override { return CString("Streaming"); } - CString getVersion() const override { return CString("1.0"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_SignalMerger; } - IPluginObject* create() override { return new CBoxAlgorithmSignalMerger; } - IBoxListener* createBoxListener() const override { return new CBoxAlgorithmSignalMergerListener; } - void releaseBoxListener(IBoxListener* listener) const override { delete listener; } +class CBoxAlgorithmSignalMergerDesc final : public IBoxAlgorithmDesc +{ +public: + void release() override { } + CString getName() const override { return CString("Signal Merger"); } + CString getAuthorName() const override { return CString("Yann Renard"); } + CString getAuthorCompanyName() const override { return CString("INRIA"); } + CString getShortDescription() const override { return CString("Merges several input streams into a single output stream"); } + CString getDetailedDescription() const override { return CString(""); } + CString getCategory() const override { return CString("Streaming"); } + CString getVersion() const override { return CString("1.0"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_SignalMerger; } + IPluginObject* create() override { return new CBoxAlgorithmSignalMerger; } + IBoxListener* createBoxListener() const override { return new CBoxAlgorithmSignalMergerListener; } + void releaseBoxListener(IBoxListener* listener) const override { delete listener; } - bool getBoxPrototype(Kernel::IBoxProto& prototype) const override - { - prototype.addInput("Input 1", OV_TypeId_Signal); - prototype.addInput("Input 2", OV_TypeId_Signal); - prototype.addOutput("Merged", OV_TypeId_Signal); - prototype.addFlag(Kernel::BoxFlag_CanAddInput); + bool getBoxPrototype(Kernel::IBoxProto& prototype) const override + { + prototype.addInput("Input 1", OV_TypeId_Signal); + prototype.addInput("Input 2", OV_TypeId_Signal); + prototype.addOutput("Merged", OV_TypeId_Signal); + prototype.addFlag(Kernel::BoxFlag_CanAddInput); - return true; - } + return true; + } - _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_SignalMergerDesc) - }; - } // namespace Streaming - } // namespace Plugins + _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_SignalMergerDesc) +}; +} // namespace Streaming +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/streaming/src/box-algorithms/ovpCBoxAlgorithmStreamedMatrixMultiplexer.h b/plugins/processing/streaming/src/box-algorithms/ovpCBoxAlgorithmStreamedMatrixMultiplexer.h index 80f2e42d96e0e22ccca779c25f30051acf9cc3a9..9449777d5eb40238c042d534b48526d1352e887d 100644 --- a/plugins/processing/streaming/src/box-algorithms/ovpCBoxAlgorithmStreamedMatrixMultiplexer.h +++ b/plugins/processing/streaming/src/box-algorithms/ovpCBoxAlgorithmStreamedMatrixMultiplexer.h @@ -4,138 +4,135 @@ #include <openvibe/ov_all.h> #include <toolkit/ovtk_all.h> -namespace OpenViBE +namespace OpenViBE { +namespace Plugins { +namespace Streaming { +class CBoxAlgorithmStreamedMatrixMultiplexer final : virtual public Toolkit::TBoxAlgorithm<IBoxAlgorithm> { - namespace Plugins +public: + void release() override { delete this; } + bool initialize() override; + bool uninitialize() override; + bool processInput(const size_t index) override; + bool process() override; + + _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_StreamedMatrixMultiplexer) + +protected: + + uint64_t m_lastStartTime = 0; + uint64_t m_lastEndTime = 0; + bool m_headerSent = false; +}; + +class CBoxAlgorithmStreamedMatrixMultiplexerListener final : public Toolkit::TBoxListener<IBoxListener> +{ +public: + + bool check(Kernel::IBox& box) const + { + for (size_t i = 0; i < box.getInputCount(); ++i) { box.setInputName(i, ("Input stream " + std::to_string(i + 1)).c_str()); } + return true; + } + + bool onInputAdded(Kernel::IBox& box, const size_t index) override + { + CIdentifier typeID = OV_UndefinedIdentifier; + box.getOutputType(0, typeID); + box.setInputType(index, typeID); + return this->check(box); + } + + bool onInputRemoved(Kernel::IBox& box, const size_t /*index*/) override + { + CIdentifier typeID = OV_UndefinedIdentifier; + box.getOutputType(0, typeID); + + while (box.getInputCount() < 2) { box.addInput("", typeID); } + + return this->check(box); + } + + bool onInputTypeChanged(Kernel::IBox& box, const size_t index) override { - namespace Streaming + CIdentifier typeID = OV_UndefinedIdentifier; + box.getInputType(index, typeID); + + if (this->getTypeManager().isDerivedFromStream(typeID, OV_TypeId_StreamedMatrix)) + { + for (size_t i = 0; i < box.getInputCount(); ++i) { box.setInputType(i, typeID); } + + box.setOutputType(0, typeID); + } + else + { + box.getOutputType(0, typeID); + box.setInputType(index, typeID); + } + + return true; + } + + bool onOutputTypeChanged(Kernel::IBox& box, const size_t /*index*/) override + { + CIdentifier typeID = OV_UndefinedIdentifier; + box.getOutputType(0, typeID); + + if (this->getTypeManager().isDerivedFromStream(typeID, OV_TypeId_StreamedMatrix)) + { + for (size_t i = 0; i < box.getInputCount(); ++i) { box.setInputType(i, typeID); } + } + else { - class CBoxAlgorithmStreamedMatrixMultiplexer final : virtual public Toolkit::TBoxAlgorithm<IBoxAlgorithm> - { - public: - void release() override { delete this; } - bool initialize() override; - bool uninitialize() override; - bool processInput(const size_t index) override; - bool process() override; - - _IsDerivedFromClass_Final_(Toolkit::TBoxAlgorithm<IBoxAlgorithm>, OVP_ClassId_BoxAlgorithm_StreamedMatrixMultiplexer) - - protected: - - uint64_t m_lastStartTime = 0; - uint64_t m_lastEndTime = 0; - bool m_headerSent = false; - }; - - class CBoxAlgorithmStreamedMatrixMultiplexerListener final : public Toolkit::TBoxListener<IBoxListener> - { - public: - - bool check(Kernel::IBox& box) const - { - for (size_t i = 0; i < box.getInputCount(); ++i) { box.setInputName(i, ("Input stream " + std::to_string(i + 1)).c_str()); } - return true; - } - - bool onInputAdded(Kernel::IBox& box, const size_t index) override - { - CIdentifier typeID = OV_UndefinedIdentifier; - box.getOutputType(0, typeID); - box.setInputType(index, typeID); - return this->check(box); - } - - bool onInputRemoved(Kernel::IBox& box, const size_t /*index*/) override - { - CIdentifier typeID = OV_UndefinedIdentifier; - box.getOutputType(0, typeID); - - while (box.getInputCount() < 2) { box.addInput("", typeID); } - - return this->check(box); - } - - bool onInputTypeChanged(Kernel::IBox& box, const size_t index) override - { - CIdentifier typeID = OV_UndefinedIdentifier; - box.getInputType(index, typeID); - - if (this->getTypeManager().isDerivedFromStream(typeID, OV_TypeId_StreamedMatrix)) - { - for (size_t i = 0; i < box.getInputCount(); ++i) { box.setInputType(i, typeID); } - - box.setOutputType(0, typeID); - } - else - { - box.getOutputType(0, typeID); - box.setInputType(index, typeID); - } - - return true; - } - - bool onOutputTypeChanged(Kernel::IBox& box, const size_t /*index*/) override - { - CIdentifier typeID = OV_UndefinedIdentifier; - box.getOutputType(0, typeID); - - if (this->getTypeManager().isDerivedFromStream(typeID, OV_TypeId_StreamedMatrix)) - { - for (size_t i = 0; i < box.getInputCount(); ++i) { box.setInputType(i, typeID); } - } - else - { - box.getInputType(0, typeID); - box.setOutputType(0, typeID); - } - - return true; - } - - _IsDerivedFromClass_Final_(Toolkit::TBoxListener<IBoxListener>, OV_UndefinedIdentifier) - }; - - class CBoxAlgorithmStreamedMatrixMultiplexerDesc final : virtual public IBoxAlgorithmDesc - { - public: - void release() override { } - CString getName() const override { return CString("Streamed matrix multiplexer"); } - CString getAuthorName() const override { return CString("Yann Renard"); } - CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } - CString getShortDescription() const override { return CString("Multiplexes streamed matrix buffers in a new stream"); } - CString getDetailedDescription() const override { return CString(""); } - CString getCategory() const override { return CString("Streaming"); } - CString getVersion() const override { return CString("1.0"); } - CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } - CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } - CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } - CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_StreamedMatrixMultiplexer; } - IPluginObject* create() override { return new CBoxAlgorithmStreamedMatrixMultiplexer; } - IBoxListener* createBoxListener() const override { return new CBoxAlgorithmStreamedMatrixMultiplexerListener; } - void releaseBoxListener(IBoxListener* listener) const override { delete listener; } - - bool getBoxPrototype(Kernel::IBoxProto& prototype) const override - { - prototype.addInput("Input stream 1", OV_TypeId_StreamedMatrix); - prototype.addInput("Input stream 2", OV_TypeId_StreamedMatrix); - prototype.addOutput("Multiplexed streamed matrix", OV_TypeId_StreamedMatrix); - prototype.addFlag(Kernel::BoxFlag_CanAddInput); - prototype.addFlag(Kernel::BoxFlag_CanModifyInput); - prototype.addFlag(Kernel::BoxFlag_CanModifyOutput); - - prototype.addInputSupport(OV_TypeId_StreamedMatrix); - prototype.addInputSupport(OV_TypeId_ChannelLocalisation); - prototype.addInputSupport(OV_TypeId_FeatureVector); - prototype.addInputSupport(OV_TypeId_Signal); - prototype.addInputSupport(OV_TypeId_Spectrum); - - return true; - } - - _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_StreamedMatrixMultiplexerDesc) - }; - } // namespace Streaming - } // namespace Plugins + box.getInputType(0, typeID); + box.setOutputType(0, typeID); + } + + return true; + } + + _IsDerivedFromClass_Final_(Toolkit::TBoxListener<IBoxListener>, OV_UndefinedIdentifier) +}; + +class CBoxAlgorithmStreamedMatrixMultiplexerDesc final : virtual public IBoxAlgorithmDesc +{ +public: + void release() override { } + CString getName() const override { return CString("Streamed matrix multiplexer"); } + CString getAuthorName() const override { return CString("Yann Renard"); } + CString getAuthorCompanyName() const override { return CString("INRIA/IRISA"); } + CString getShortDescription() const override { return CString("Multiplexes streamed matrix buffers in a new stream"); } + CString getDetailedDescription() const override { return CString(""); } + CString getCategory() const override { return CString("Streaming"); } + CString getVersion() const override { return CString("1.0"); } + CString getSoftwareComponent() const override { return CString("openvibe-sdk"); } + CString getAddedSoftwareVersion() const override { return CString("0.0.0"); } + CString getUpdatedSoftwareVersion() const override { return CString("0.0.0"); } + CIdentifier getCreatedClass() const override { return OVP_ClassId_BoxAlgorithm_StreamedMatrixMultiplexer; } + IPluginObject* create() override { return new CBoxAlgorithmStreamedMatrixMultiplexer; } + IBoxListener* createBoxListener() const override { return new CBoxAlgorithmStreamedMatrixMultiplexerListener; } + void releaseBoxListener(IBoxListener* listener) const override { delete listener; } + + bool getBoxPrototype(Kernel::IBoxProto& prototype) const override + { + prototype.addInput("Input stream 1", OV_TypeId_StreamedMatrix); + prototype.addInput("Input stream 2", OV_TypeId_StreamedMatrix); + prototype.addOutput("Multiplexed streamed matrix", OV_TypeId_StreamedMatrix); + prototype.addFlag(Kernel::BoxFlag_CanAddInput); + prototype.addFlag(Kernel::BoxFlag_CanModifyInput); + prototype.addFlag(Kernel::BoxFlag_CanModifyOutput); + + prototype.addInputSupport(OV_TypeId_StreamedMatrix); + prototype.addInputSupport(OV_TypeId_ChannelLocalisation); + prototype.addInputSupport(OV_TypeId_FeatureVector); + prototype.addInputSupport(OV_TypeId_Signal); + prototype.addInputSupport(OV_TypeId_Spectrum); + + return true; + } + + _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_StreamedMatrixMultiplexerDesc) +}; +} // namespace Streaming +} // namespace Plugins } // namespace OpenViBE diff --git a/plugins/processing/tools/CMakeLists.txt b/plugins/processing/tools/CMakeLists.txt index 54d5c0c222197b8649f15a46b53691fbc891d923..57b8db1afbb0749522c675757777c08ca1bd5e03 100644 --- a/plugins/processing/tools/CMakeLists.txt +++ b/plugins/processing/tools/CMakeLists.txt @@ -11,6 +11,7 @@ ADD_LIBRARY(${PROJECT_NAME} SHARED ${SRC_FILES}) SET_TARGET_PROPERTIES(${PROJECT_NAME} PROPERTIES VERSION ${PROJECT_VERSION} SOVERSION ${PROJECT_VERSION_MAJOR} + FOLDER ${PLUGINS_FOLDER} COMPILE_FLAGS "-DOVP_Exports -DOVP_Shared") INCLUDE("FindOpenViBE") @@ -24,13 +25,10 @@ INCLUDE("FindOpenViBEModuleCommunication") # --------------------------------- # Target macros -# Defines target operating system -# Defines target architecture -# Defines target compiler +# Defines target operating system, architecture and compiler # --------------------------------- SET_BUILD_PLATFORM() - # ----------------------------- # Install files # ----------------------------- diff --git a/plugins/processing/tools/src/box-algorithms/ovpCBoxAlgorithmEBMLStreamSpy.cpp b/plugins/processing/tools/src/box-algorithms/ovpCBoxAlgorithmEBMLStreamSpy.cpp index 3fca483160e72713050be21f2aa0c2db6c373c26..eaa6cc5e4624c9f8701541fab1aafc27c3e9f96b 100644 --- a/plugins/processing/tools/src/box-algorithms/ovpCBoxAlgorithmEBMLStreamSpy.cpp +++ b/plugins/processing/tools/src/box-algorithms/ovpCBoxAlgorithmEBMLStreamSpy.cpp @@ -239,6 +239,6 @@ bool CBoxAlgorithmEBMLStreamSpy::process() return true; } -} // namespace Tools -} // namespace Plugins -} // namespace OpenViBE +} // namespace Tools +} // namespace Plugins +} // namespace OpenViBE diff --git a/plugins/processing/tools/src/box-algorithms/ovpCBoxAlgorithmEBMLStreamSpy.h b/plugins/processing/tools/src/box-algorithms/ovpCBoxAlgorithmEBMLStreamSpy.h index 6ae20cb670f1d29b690691a3bf2597dcefd917b9..42360f479081299363f0e450b3a1a01f2f2298a6 100644 --- a/plugins/processing/tools/src/box-algorithms/ovpCBoxAlgorithmEBMLStreamSpy.h +++ b/plugins/processing/tools/src/box-algorithms/ovpCBoxAlgorithmEBMLStreamSpy.h @@ -102,6 +102,6 @@ public: _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_EBMLStreamSpyDesc) }; -} // namespace Tools -} // namespace Plugins -} // namespace OpenViBE +} // namespace Tools +} // namespace Plugins +} // namespace OpenViBE diff --git a/plugins/processing/tools/src/box-algorithms/ovpCBoxAlgorithmExternalProcessing.cpp b/plugins/processing/tools/src/box-algorithms/ovpCBoxAlgorithmExternalProcessing.cpp index 6e3b5eb4a10f228018488a0f9ae0af0219d6aaa4..b64061527b97fc3122390fa653b6bb8998bbac55 100644 --- a/plugins/processing/tools/src/box-algorithms/ovpCBoxAlgorithmExternalProcessing.cpp +++ b/plugins/processing/tools/src/box-algorithms/ovpCBoxAlgorithmExternalProcessing.cpp @@ -254,7 +254,7 @@ bool CBoxAlgorithmExternalProcessing::uninitialize() return true; } -bool CBoxAlgorithmExternalProcessing::processClock(CMessageClock& /*messageClock*/) { return this->getBoxAlgorithmContext()->markAlgorithmAsReadyToProcess(); } +bool CBoxAlgorithmExternalProcessing::processClock(Kernel::CMessageClock& /*msg*/) { return this->getBoxAlgorithmContext()->markAlgorithmAsReadyToProcess(); } bool CBoxAlgorithmExternalProcessing::processInput(const size_t /*index*/) { @@ -605,6 +605,6 @@ void CBoxAlgorithmExternalProcessing::log() } } -} // namespace Tools -} // namespace Plugins -} // namespace OpenViBE +} // namespace Tools +} // namespace Plugins +} // namespace OpenViBE diff --git a/plugins/processing/tools/src/box-algorithms/ovpCBoxAlgorithmExternalProcessing.h b/plugins/processing/tools/src/box-algorithms/ovpCBoxAlgorithmExternalProcessing.h index 23d439b71407eb92db6f24e90353c4a336e54c18..4f90d68b397e99cd7e3a7eabd12376da2970a700 100644 --- a/plugins/processing/tools/src/box-algorithms/ovpCBoxAlgorithmExternalProcessing.h +++ b/plugins/processing/tools/src/box-algorithms/ovpCBoxAlgorithmExternalProcessing.h @@ -22,7 +22,7 @@ public: uint64_t getClockFrequency() override; bool initialize() override; bool uninitialize() override; - bool processClock(CMessageClock& messageClock) override; + bool processClock(Kernel::CMessageClock& msg) override; bool processInput(const size_t index) override; bool process() override; @@ -138,6 +138,6 @@ public: _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_ExternalProcessingDesc) }; -} // namespace Tools -} // namespace Plugins -} // namespace OpenViBE +} // namespace Tools +} // namespace Plugins +} // namespace OpenViBE diff --git a/plugins/processing/tools/src/box-algorithms/ovpCBoxAlgorithmMatrixValidityChecker.cpp b/plugins/processing/tools/src/box-algorithms/ovpCBoxAlgorithmMatrixValidityChecker.cpp index c6d054831a297bf416fa5e92b211583061d818dd..61406d601483e62b9743190e4b92a22d551cff23 100644 --- a/plugins/processing/tools/src/box-algorithms/ovpCBoxAlgorithmMatrixValidityChecker.cpp +++ b/plugins/processing/tools/src/box-algorithms/ovpCBoxAlgorithmMatrixValidityChecker.cpp @@ -65,9 +65,9 @@ bool CBoxAlgorithmMatrixValidityChecker::processInput(const size_t /*index*/) bool CBoxAlgorithmMatrixValidityChecker::process() { - Kernel::IBoxIO& boxCtx = this->getDynamicBoxContext(); - const size_t nInput = this->getStaticBoxContext().getInputCount(); - const size_t nSetting = this->getStaticBoxContext().getSettingCount(); + Kernel::IBoxIO& boxCtx = this->getDynamicBoxContext(); + const size_t nInput = this->getStaticBoxContext().getInputCount(); + const size_t nSetting = this->getStaticBoxContext().getSettingCount(); for (size_t i = 0; i < nInput; ++i) { @@ -169,6 +169,6 @@ bool CBoxAlgorithmMatrixValidityChecker::process() return true; } -} // namespace Tools -} // namespace Plugins -} // namespace OpenViBE +} // namespace Tools +} // namespace Plugins +} // namespace OpenViBE diff --git a/plugins/processing/tools/src/box-algorithms/ovpCBoxAlgorithmMatrixValidityChecker.h b/plugins/processing/tools/src/box-algorithms/ovpCBoxAlgorithmMatrixValidityChecker.h index d1932726aa2cd51ded51557dd51fad3ac5c990db..72b6bb05fb86ddc6c68cff974d495e17776349ee 100644 --- a/plugins/processing/tools/src/box-algorithms/ovpCBoxAlgorithmMatrixValidityChecker.h +++ b/plugins/processing/tools/src/box-algorithms/ovpCBoxAlgorithmMatrixValidityChecker.h @@ -95,7 +95,8 @@ public: CString getDetailedDescription() const override { - return "This box is for debugging purposes and allows an author to check the validity of a streamed matrix and derived stream. This box can log a message, stop the player or interpolate data."; + return + "This box is for debugging purposes and allows an author to check the validity of a streamed matrix and derived stream. This box can log a message, stop the player or interpolate data."; } CString getCategory() const override { return "Tools"; } @@ -122,6 +123,6 @@ public: _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_MatrixValidityCheckerDesc) }; -} // namespace Tools -} // namespace Plugins -} // namespace OpenViBE +} // namespace Tools +} // namespace Plugins +} // namespace OpenViBE diff --git a/plugins/processing/tools/src/box-algorithms/ovpCBoxAlgorithmStimulationListener.cpp b/plugins/processing/tools/src/box-algorithms/ovpCBoxAlgorithmStimulationListener.cpp index 978462abaa66385b9be0f62bd474f15052770e83..c60a44b8f1794471b8cf18d0cb071b7edc706b34 100644 --- a/plugins/processing/tools/src/box-algorithms/ovpCBoxAlgorithmStimulationListener.cpp +++ b/plugins/processing/tools/src/box-algorithms/ovpCBoxAlgorithmStimulationListener.cpp @@ -53,7 +53,7 @@ bool CBoxAlgorithmStimulationListener::process() staticboxCtx.getInputName(i, inputName); for (size_t k = 0; k < stimSet->getStimulationCount(); ++k) { - this->getLogManager() << m_logLevel + this->getLogManager() << m_logLevel << "For input " << i << " with name " << inputName << " got stimulation " << stimSet->getStimulationIdentifier(k) << "[" << getTypeManager().getEnumerationEntryNameFromValue(OV_TypeId_Stimulation, stimSet->getStimulationIdentifier(k)) << "]" @@ -75,6 +75,6 @@ bool CBoxAlgorithmStimulationListener::process() return true; } -} // namespace Tools -} // namespace Plugins -} // namespace OpenViBE +} // namespace Tools +} // namespace Plugins +} // namespace OpenViBE diff --git a/plugins/processing/tools/src/box-algorithms/ovpCBoxAlgorithmStimulationListener.h b/plugins/processing/tools/src/box-algorithms/ovpCBoxAlgorithmStimulationListener.h index b02a9ff601d31c090f2bdd7fb2ecdc680988544b..7606ec567ec39ce8d3a04e0889f88109a02dff2c 100644 --- a/plugins/processing/tools/src/box-algorithms/ovpCBoxAlgorithmStimulationListener.h +++ b/plugins/processing/tools/src/box-algorithms/ovpCBoxAlgorithmStimulationListener.h @@ -56,10 +56,7 @@ public: CString getAuthorCompanyName() const override { return "INRIA/IRISA"; } CString getShortDescription() const override { return "Prints stimulation codes in the log manager"; } - CString getDetailedDescription() const override - { - return "Prints each received stimulationto the log using the log level specified in the box config."; - } + CString getDetailedDescription() const override { return "Prints each received stimulationto the log using the log level specified in the box config."; } CString getCategory() const override { return "Tools"; } CString getVersion() const override { return "1.0"; } @@ -82,6 +79,6 @@ public: _IsDerivedFromClass_Final_(IBoxAlgorithmDesc, OVP_ClassId_BoxAlgorithm_StimulationListenerDesc) }; -} // namespace Tools -} // namespace Plugins -} // namespace OpenViBE +} // namespace Tools +} // namespace Plugins +} // namespace OpenViBE diff --git a/plugins/processing/tools/src/ovp_main.cpp b/plugins/processing/tools/src/ovp_main.cpp index a8dfd1f218c51200414aa99f9d18bb415ef62b9c..753d917b211d5a763df66a598f354d283b30aae6 100644 --- a/plugins/processing/tools/src/ovp_main.cpp +++ b/plugins/processing/tools/src/ovp_main.cpp @@ -20,9 +20,8 @@ OVP_Declare_Begin() OVP_Declare_New(CBoxAlgorithmEBMLStreamSpyDesc); OVP_Declare_New(CBoxAlgorithmMatrixValidityCheckerDesc); OVP_Declare_New(CBoxAlgorithmExternalProcessingDesc); - OVP_Declare_End() -} // namespace Tools -} // namespace Plugins -} // namespace OpenViBE +} // namespace Tools +} // namespace Plugins +} // namespace OpenViBE diff --git a/scripts/linux-dependencies-fedora.txt b/scripts/linux-dependencies-fedora.txt new file mode 100644 index 0000000000000000000000000000000000000000..31f0dba13edffc0ad791c831271d321b28330ab0 --- /dev/null +++ b/scripts/linux-dependencies-fedora.txt @@ -0,0 +1,11 @@ +doxygen +make +gcc +gcc-c++ +expat-devel +openssl-devel +boost-devel +ninja-build +zziplib-devel +xerces-c-devel +gtest-devel diff --git a/scripts/linux-dependencies-ubuntu16_plus.txt b/scripts/linux-dependencies-ubuntu16_plus.txt index 82ae1c56c02320ee4c2d1512da68ce38a1e278ab..6d269ce130a2ae61b309420b6b915befcfd1ee6e 100644 --- a/scripts/linux-dependencies-ubuntu16_plus.txt +++ b/scripts/linux-dependencies-ubuntu16_plus.txt @@ -2,6 +2,7 @@ doxygen make gcc g++ +libssl-dev libexpat1-dev libncurses5-dev libboost-dev diff --git a/scripts/linux-install_dependencies.pl b/scripts/linux-install_dependencies.pl index fad559bdb6a99c6c8979f20c277b2ab54d4d81cf..c891d0b8d4bf01e426cbd759c524205afc625d56 100755 --- a/scripts/linux-install_dependencies.pl +++ b/scripts/linux-install_dependencies.pl @@ -83,8 +83,10 @@ my $update_packages_command = ''; my $package_install_command = ''; my $add_repository_command = ''; -my $lsb_distributor = `lsb_release --id --short`; -my $lsb_release = `lsb_release --release --short`; +my $os_release = `cat /etc/os-release`; +# Check for NAME= and VERSION_ID= +# Take into account distros placing quotes around values +my ($lsb_distributor, $lsb_release) = ($os_release =~ m/NAME=["'\`]*([a-zA-Z]+).*VERSION_ID=["'\`]*([0-9.]+)/s); if ($lsb_distributor =~ 'Ubuntu') { if (!$no_install) { @@ -104,17 +106,25 @@ if ($lsb_distributor =~ 'Ubuntu') { || $lsb_release =~ '19.10') { $distribution = 'Ubuntu ' . $lsb_release; } +} elsif ($lsb_distributor =~ 'Fedora') { + if (!$no_install) { + if ($assume_yes) { + $package_install_command = 'sudo dnf -y install'; + } else { + $package_install_command = 'sudo dnf install'; + } + } + $distribution = 'Fedora'; } $distribution eq $unsupported_distribution and die('This distribution is unsupported'); print "Installing dependencies for: $distribution\n"; - +print "Install command: $package_install_command\n"; # Perform steps before installing packages opendir(my $dir_handle, $helper_script_dir) or die("unable to open $helper_script_dir"); while(my $filename = readdir($dir_handle)) { if($filename =~ /^linux-preinstall.*pl/) { - print "Running $helper_script_dir/$filename ...\n"; open(my $pl_file_handle, '<', "$helper_script_dir/$filename") or die "Unable to open file, $helper_script_dir/$filename"; undef $/; @@ -130,8 +140,10 @@ my $pkg_file = ""; if ($distribution eq 'Ubuntu 14.04') { $pkg_file = "$manifest_dir/linux-dependencies-ubuntu1404.txt"; -} else { +} elsif ($distribution =~ 'Ubuntu') { $pkg_file = "$manifest_dir/linux-dependencies-ubuntu16_plus.txt"; +} elsif ($distribution eq 'Fedora') { + $pkg_file = "$manifest_dir/linux-dependencies-fedora.txt"; } # Install actual packages @@ -152,11 +164,15 @@ close($pkg_file_handle) or warn "Unable to close $pkg_file"; if (!$no_install) { # Update package list - print "Updating package database...\n"; - system($add_repository_command); - ($CHILD_ERROR != 0) and die('Failed to add additional repositories'); - system($update_packages_command); - ($CHILD_ERROR != 0) and die('Failed to update the package databases'); + if ($add_repository_command) { + print "Updating package database...\n"; + system($add_repository_command); + ($CHILD_ERROR != 0) and die('Failed to add additional repositories'); + } + if ($update_packages_command) { + system($update_packages_command); + ($CHILD_ERROR != 0) and die('Failed to update the package databases'); + } # Install the packages print "Will install following packages:\n"; diff --git a/scripts/unix-build b/scripts/unix-build index e0ec378c434596ea1e86e62708e79541e0177381..3f27263be1321a94721cc3b1515e9bdd65bc7efd 100755 --- a/scripts/unix-build +++ b/scripts/unix-build @@ -119,13 +119,6 @@ while [[ $# -gt 0 ]]; do shift # past argument or value done -if [[ ! -z ${dependencies_dir} ]] -then - ./unix-init-env.sh --dependencies-dir ${dependencies_dir} -else - echo "dependencies_dir not set: not initialisaing environment" -fi - # Check parameters validity if [[ ${ov_build_type} != "Debug" ]] \ && [[ ${ov_build_type} != "Release" ]] \ diff --git a/toolkit/CMakeLists.txt b/toolkit/CMakeLists.txt index 6a92d4b8f2cded91a30ed7d8217058c57c72a99f..b6f7540b3ddb17cdf290c795247c28e8e91d56bf 100644 --- a/toolkit/CMakeLists.txt +++ b/toolkit/CMakeLists.txt @@ -50,6 +50,7 @@ ADD_DEPENDENCIES(${PROJECT_NAME} openvibe-generate-stimulation-file) SET_TARGET_PROPERTIES(${PROJECT_NAME} PROPERTIES VERSION ${PROJECT_VERSION} SOVERSION ${PROJECT_VERSION_MAJOR} + FOLDER ${KERNEL_FOLDER} COMPILE_FLAGS "-DOVTK_Exports -DOVTK_Shared") # --------------------------------- @@ -62,9 +63,7 @@ INCLUDE("FindThirdPartyBoost_FileSystem") # --------------------------------- # Target macros -# Defines target operating system -# Defines target architecture -# Defines target compiler +# Defines target operating system, architecture and compiler # --------------------------------- SET_BUILD_PLATFORM() diff --git a/toolkit/include/toolkit/algorithms/classification/ovtkCAlgorithmClassifier.h b/toolkit/include/toolkit/algorithms/classification/ovtkCAlgorithmClassifier.h index b96ef667edbe9c23a0dd18d478e8bcb75d27f463..029154213e5b95ac728a6294c1db7410ab325712 100644 --- a/toolkit/include/toolkit/algorithms/classification/ovtkCAlgorithmClassifier.h +++ b/toolkit/include/toolkit/algorithms/classification/ovtkCAlgorithmClassifier.h @@ -32,81 +32,77 @@ #define OVTK_Algorithm_Classifier_OutputTriggerId_Failed OpenViBE::CIdentifier(0x6E72B255, 0x317FAA04) -namespace OpenViBE +namespace OpenViBE { +namespace Toolkit { +class OVTK_API CAlgorithmClassifier : public TAlgorithm<Plugins::IAlgorithm> { - namespace Toolkit +public: + bool initialize() override; + bool uninitialize() override; + void release() override { delete this; } + bool process() override; + + virtual bool train(const IFeatureVectorSet& featureVectorSet) = 0; + virtual bool classify(const IFeatureVector& featureVector, double& estimatedClass, IVector& distanceValue, IVector& probabilityValue) = 0; + + virtual XML::IXMLNode* saveConfig() = 0; + virtual bool loadConfig(XML::IXMLNode* configurationRoot) = 0; + + virtual size_t getNProbabilities() = 0; + virtual size_t getNDistances() = 0; + + _IsDerivedFromClass_(TAlgorithm<Plugins::IAlgorithm>, OVTK_ClassId_Algorithm_Classifier) + +protected: + bool initializeExtraParameterMechanism(); + bool uninitializeExtraParameterMechanism(); + + uint64_t getUInt64Parameter(const CIdentifier& parameterID); + int64_t getInt64Parameter(const CIdentifier& parameterID); + double getDoubleParameter(const CIdentifier& parameterID); + bool getBooleanParameter(const CIdentifier& parameterID); + CString* getCStringParameter(const CIdentifier& parameterID); + uint64_t getEnumerationParameter(const CIdentifier& parameterID, const CIdentifier& enumerationIdentifier); + +private: + CString& getParameterValue(const CIdentifier& parameterID) const; + static void setMatrixOutputDimension(Kernel::TParameterHandler<IMatrix*>& matrix, size_t length); + + Kernel::IAlgorithmProxy* m_AlgorithmProxy = nullptr; + void* m_ExtraParametersMap = nullptr; +}; + +class OVTK_API CAlgorithmClassifierDesc : public Plugins::IAlgorithmDesc +{ +public: + bool getAlgorithmPrototype(Kernel::IAlgorithmProto& algorithmPrototype) const override { - class OVTK_API CAlgorithmClassifier : public TAlgorithm<Plugins::IAlgorithm> - { - public: - bool initialize() override; - bool uninitialize() override; - void release() override { delete this; } - bool process() override; - - virtual bool train(const IFeatureVectorSet& featureVectorSet) = 0; - virtual bool classify(const IFeatureVector& featureVector, double& estimatedClass, IVector& distanceValue, IVector& probabilityValue) = 0; - - virtual XML::IXMLNode* saveConfig() = 0; - virtual bool loadConfig(XML::IXMLNode* configurationRoot) = 0; - - virtual size_t getNProbabilities() = 0; - virtual size_t getNDistances() = 0; - - _IsDerivedFromClass_(TAlgorithm<Plugins::IAlgorithm>, OVTK_ClassId_Algorithm_Classifier) - - protected: - bool initializeExtraParameterMechanism(); - bool uninitializeExtraParameterMechanism(); - - uint64_t getUInt64Parameter(const CIdentifier& parameterID); - int64_t getInt64Parameter(const CIdentifier& parameterID); - double getDoubleParameter(const CIdentifier& parameterID); - bool getBooleanParameter(const CIdentifier& parameterID); - CString* getCStringParameter(const CIdentifier& parameterID); - uint64_t getEnumerationParameter(const CIdentifier& parameterID, const CIdentifier& enumerationIdentifier); - - private: - CString& getParameterValue(const CIdentifier& parameterID) const; - static void setMatrixOutputDimension(Kernel::TParameterHandler<IMatrix*>& matrix, size_t length); - - Kernel::IAlgorithmProxy* m_AlgorithmProxy = nullptr; - void* m_ExtraParametersMap = nullptr; - }; - - class OVTK_API CAlgorithmClassifierDesc : public Plugins::IAlgorithmDesc - { - public: - bool getAlgorithmPrototype(Kernel::IAlgorithmProto& algorithmPrototype) const override - { - algorithmPrototype.addInputParameter(OVTK_Algorithm_Classifier_InputParameterId_FeatureVector, "Feature vector", Kernel::ParameterType_Matrix); - algorithmPrototype.addInputParameter( - OVTK_Algorithm_Classifier_InputParameterId_FeatureVectorSet, "Feature vector set", Kernel::ParameterType_Matrix); - algorithmPrototype.addInputParameter(OVTK_Algorithm_Classifier_InputParameterId_Config, "Configuration", Kernel::ParameterType_Pointer); - algorithmPrototype.addInputParameter(OVTK_Algorithm_Classifier_InputParameterId_NClasses, "Number of classes", Kernel::ParameterType_UInteger); - algorithmPrototype.addInputParameter( - OVTK_Algorithm_Classifier_InputParameterId_ExtraParameter, "Extra parameter", Kernel::ParameterType_Pointer); - - algorithmPrototype.addOutputParameter(OVTK_Algorithm_Classifier_OutputParameterId_Class, "Class", Kernel::ParameterType_Float); - algorithmPrototype.addOutputParameter( - OVTK_Algorithm_Classifier_OutputParameterId_ClassificationValues, "Hyperplane distance", Kernel::ParameterType_Matrix); - algorithmPrototype.addOutputParameter( - OVTK_Algorithm_Classifier_OutputParameterId_ProbabilityValues, "Probability values", Kernel::ParameterType_Matrix); - algorithmPrototype.addOutputParameter(OVTK_Algorithm_Classifier_OutputParameterId_Config, "Configuration", Kernel::ParameterType_Pointer); - - algorithmPrototype.addInputTrigger(OVTK_Algorithm_Classifier_InputTriggerId_Train, "Train"); - algorithmPrototype.addInputTrigger(OVTK_Algorithm_Classifier_InputTriggerId_Classify, "Classify"); - algorithmPrototype.addInputTrigger(OVTK_Algorithm_Classifier_InputTriggerId_LoadConfig, "Load configuration"); - algorithmPrototype.addInputTrigger(OVTK_Algorithm_Classifier_InputTriggerId_SaveConfig, "Save configuration"); - - algorithmPrototype.addOutputTrigger(OVTK_Algorithm_Classifier_OutputTriggerId_Success, "Success"); - algorithmPrototype.addOutputTrigger(OVTK_Algorithm_Classifier_OutputTriggerId_Failed, "Failed"); - - - return true; - } - - _IsDerivedFromClass_(Plugins::IAlgorithmDesc, OVTK_ClassId_Algorithm_ClassifierDesc) - }; - } // namespace Toolkit + algorithmPrototype.addInputParameter(OVTK_Algorithm_Classifier_InputParameterId_FeatureVector, "Feature vector", Kernel::ParameterType_Matrix); + algorithmPrototype.addInputParameter(OVTK_Algorithm_Classifier_InputParameterId_FeatureVectorSet, "Feature vector set", Kernel::ParameterType_Matrix); + algorithmPrototype.addInputParameter(OVTK_Algorithm_Classifier_InputParameterId_Config, "Configuration", Kernel::ParameterType_Pointer); + algorithmPrototype.addInputParameter(OVTK_Algorithm_Classifier_InputParameterId_NClasses, "Number of classes", Kernel::ParameterType_UInteger); + algorithmPrototype.addInputParameter(OVTK_Algorithm_Classifier_InputParameterId_ExtraParameter, "Extra parameter", Kernel::ParameterType_Pointer); + + algorithmPrototype.addOutputParameter(OVTK_Algorithm_Classifier_OutputParameterId_Class, "Class", Kernel::ParameterType_Float); + algorithmPrototype.addOutputParameter(OVTK_Algorithm_Classifier_OutputParameterId_ClassificationValues, "Hyperplane distance", + Kernel::ParameterType_Matrix); + algorithmPrototype.addOutputParameter(OVTK_Algorithm_Classifier_OutputParameterId_ProbabilityValues, "Probability values", + Kernel::ParameterType_Matrix); + algorithmPrototype.addOutputParameter(OVTK_Algorithm_Classifier_OutputParameterId_Config, "Configuration", Kernel::ParameterType_Pointer); + + algorithmPrototype.addInputTrigger(OVTK_Algorithm_Classifier_InputTriggerId_Train, "Train"); + algorithmPrototype.addInputTrigger(OVTK_Algorithm_Classifier_InputTriggerId_Classify, "Classify"); + algorithmPrototype.addInputTrigger(OVTK_Algorithm_Classifier_InputTriggerId_LoadConfig, "Load configuration"); + algorithmPrototype.addInputTrigger(OVTK_Algorithm_Classifier_InputTriggerId_SaveConfig, "Save configuration"); + + algorithmPrototype.addOutputTrigger(OVTK_Algorithm_Classifier_OutputTriggerId_Success, "Success"); + algorithmPrototype.addOutputTrigger(OVTK_Algorithm_Classifier_OutputTriggerId_Failed, "Failed"); + + + return true; + } + + _IsDerivedFromClass_(Plugins::IAlgorithmDesc, OVTK_ClassId_Algorithm_ClassifierDesc) +}; +} // namespace Toolkit } // namespace OpenViBE diff --git a/toolkit/include/toolkit/algorithms/classification/ovtkCAlgorithmClassifierTrainer.h b/toolkit/include/toolkit/algorithms/classification/ovtkCAlgorithmClassifierTrainer.h index 870c428cbc2d814a13f771ccef99c31c7ca4a70e..557e88c6901577976318655140995d559745c685 100644 --- a/toolkit/include/toolkit/algorithms/classification/ovtkCAlgorithmClassifierTrainer.h +++ b/toolkit/include/toolkit/algorithms/classification/ovtkCAlgorithmClassifierTrainer.h @@ -12,37 +12,34 @@ #define OVTK_Algorithm_ClassifierTrainer_OutputTriggerId_Success OpenViBE::CIdentifier(0x7B8C0EFF, 0x26224D6B) #define OVTK_Algorithm_ClassifierTrainer_OutputTriggerId_Failed OpenViBE::CIdentifier(0x31B97C83, 0x59015D0E) -namespace OpenViBE +namespace OpenViBE { +namespace Toolkit { +class OVTK_API CAlgorithmClassifierTrainer : public TAlgorithm<Plugins::IAlgorithm> { - namespace Toolkit - { - class OVTK_API CAlgorithmClassifierTrainer : public TAlgorithm<Plugins::IAlgorithm> - { - public: - void release() override { delete this; } - bool process() override; - virtual bool train(const IFeatureVectorSet& dataset) = 0; - virtual bool saveConfig(IMemoryBuffer& buffer) = 0; +public: + void release() override { delete this; } + bool process() override; + virtual bool train(const IFeatureVectorSet& dataset) = 0; + virtual bool saveConfig(IMemoryBuffer& buffer) = 0; - _IsDerivedFromClass_(TAlgorithm < Plugins::IAlgorithm >, OVTK_ClassId_Algorithm_ClassifierTrainer) - }; + _IsDerivedFromClass_(TAlgorithm < Plugins::IAlgorithm >, OVTK_ClassId_Algorithm_ClassifierTrainer) +}; - class OVTK_API CAlgorithmClassifierTrainerDesc : public Plugins::IAlgorithmDesc - { - public: - bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override - { - prototype.addInputParameter( - OVTK_Algorithm_ClassifierTrainer_InputParameterId_FeatureVectorSet, "Feature vector set", Kernel::ParameterType_Matrix); - prototype.addOutputParameter(OVTK_Algorithm_ClassifierTrainer_OutputParameterId_Config, "Configuration", Kernel::ParameterType_MemoryBuffer); - prototype.addInputTrigger(OVTK_Algorithm_ClassifierTrainer_InputTriggerId_Train, "Train"); - prototype.addInputTrigger(OVTK_Algorithm_ClassifierTrainer_InputTriggerId_SaveConfig, "Save configuration"); - prototype.addOutputTrigger(OVTK_Algorithm_ClassifierTrainer_OutputTriggerId_Success, "Success"); - prototype.addOutputTrigger(OVTK_Algorithm_ClassifierTrainer_OutputTriggerId_Failed, "Failed"); - return true; - } +class OVTK_API CAlgorithmClassifierTrainerDesc : public Plugins::IAlgorithmDesc +{ +public: + bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override + { + prototype.addInputParameter(OVTK_Algorithm_ClassifierTrainer_InputParameterId_FeatureVectorSet, "Feature vector set", Kernel::ParameterType_Matrix); + prototype.addOutputParameter(OVTK_Algorithm_ClassifierTrainer_OutputParameterId_Config, "Configuration", Kernel::ParameterType_MemoryBuffer); + prototype.addInputTrigger(OVTK_Algorithm_ClassifierTrainer_InputTriggerId_Train, "Train"); + prototype.addInputTrigger(OVTK_Algorithm_ClassifierTrainer_InputTriggerId_SaveConfig, "Save configuration"); + prototype.addOutputTrigger(OVTK_Algorithm_ClassifierTrainer_OutputTriggerId_Success, "Success"); + prototype.addOutputTrigger(OVTK_Algorithm_ClassifierTrainer_OutputTriggerId_Failed, "Failed"); + return true; + } - _IsDerivedFromClass_(Plugins::IAlgorithmDesc, OVTK_ClassId_Algorithm_ClassifierTrainerDesc) - }; - } // namespace Toolkit + _IsDerivedFromClass_(Plugins::IAlgorithmDesc, OVTK_ClassId_Algorithm_ClassifierTrainerDesc) +}; +} // namespace Toolkit } // namespace OpenViBE diff --git a/toolkit/include/toolkit/algorithms/classification/ovtkCAlgorithmPairingStrategy.h b/toolkit/include/toolkit/algorithms/classification/ovtkCAlgorithmPairingStrategy.h index e8c410f4357254dd3b82555f406b2f95b4529ec9..6dd6273039c7e2fafd664038c2b39cc916ff620b 100644 --- a/toolkit/include/toolkit/algorithms/classification/ovtkCAlgorithmPairingStrategy.h +++ b/toolkit/include/toolkit/algorithms/classification/ovtkCAlgorithmPairingStrategy.h @@ -14,49 +14,47 @@ typedef int (*fClassifierComparison)(OpenViBE::IMatrix&, OpenViBE::IMatrix&); -namespace OpenViBE +namespace OpenViBE { +namespace Toolkit { +extern OVTK_API void registerClassificationComparisonFunction(const CIdentifier& classID, fClassifierComparison comparision); +extern OVTK_API fClassifierComparison getClassificationComparisonFunction(const CIdentifier& classID); + + +class OVTK_API CAlgorithmPairingStrategy : public CAlgorithmClassifier +{ +public: + bool process() override; + void release() override { delete this; } + + virtual bool designArchitecture(const CIdentifier& id, const size_t nClass) = 0; + bool train(const IFeatureVectorSet& rFeatureVectorSet) override = 0; + bool classify(const IFeatureVector& rFeatureVector, double& classId, IVector& distance, IVector& probability) override = 0; + XML::IXMLNode* saveConfig() override = 0; + bool loadConfig(XML::IXMLNode* pConfiguratioNode) override = 0; + _IsDerivedFromClass_(CAlgorithmClassifier, OVTK_ClassId_Algorithm_PairingStrategy) + size_t getNProbabilities() override = 0; + size_t getNDistances() override = 0; + + +protected: + // std::vector <double> m_classes; + //The vector will be use when the user will be able to specify class label + CIdentifier m_subClassifierAlgorithmID = OV_UndefinedIdentifier; +}; + +class OVTK_API CAlgorithmPairingStrategyDesc : public CAlgorithmClassifierDesc { - namespace Toolkit +public: + bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override { - extern OVTK_API void registerClassificationComparisonFunction(const CIdentifier& classID, fClassifierComparison comparision); - extern OVTK_API fClassifierComparison getClassificationComparisonFunction(const CIdentifier& classID); - - - class OVTK_API CAlgorithmPairingStrategy : public CAlgorithmClassifier - { - public: - bool process() override; - void release() override { delete this; } - - virtual bool designArchitecture(const CIdentifier& id, const size_t nClass) = 0; - bool train(const IFeatureVectorSet& rFeatureVectorSet) override = 0; - bool classify(const IFeatureVector& rFeatureVector, double& classId, IVector& distance, IVector& probability) override = 0; - XML::IXMLNode* saveConfig() override = 0; - bool loadConfig(XML::IXMLNode* pConfiguratioNode) override = 0; - _IsDerivedFromClass_(CAlgorithmClassifier, OVTK_ClassId_Algorithm_PairingStrategy) - size_t getNProbabilities() override = 0; - size_t getNDistances() override = 0; - - - protected: - // std::vector <double> m_classes; - //The vector will be use when the user will be able to specify class label - CIdentifier m_subClassifierAlgorithmID = OV_UndefinedIdentifier; - }; - - class OVTK_API CAlgorithmPairingStrategyDesc : public CAlgorithmClassifierDesc - { - public: - bool getAlgorithmPrototype(Kernel::IAlgorithmProto& prototype) const override - { - CAlgorithmClassifierDesc::getAlgorithmPrototype(prototype); - prototype.addInputParameter( - OVTK_Algorithm_PairingStrategy_InputParameterId_SubClassifierAlgorithm, "Algorithm Identifier", Kernel::ParameterType_Identifier); - prototype.addInputTrigger(OVTK_Algorithm_PairingStrategy_InputTriggerId_DesignArchitecture, "Design Architecture"); - return true; - } - - _IsDerivedFromClass_(CAlgorithmClassifierDesc, OVTK_ClassId_Algorithm_PairingStrategyDesc) - }; - } // namespace Toolkit + CAlgorithmClassifierDesc::getAlgorithmPrototype(prototype); + prototype.addInputParameter( + OVTK_Algorithm_PairingStrategy_InputParameterId_SubClassifierAlgorithm, "Algorithm Identifier", Kernel::ParameterType_Identifier); + prototype.addInputTrigger(OVTK_Algorithm_PairingStrategy_InputTriggerId_DesignArchitecture, "Design Architecture"); + return true; + } + + _IsDerivedFromClass_(CAlgorithmClassifierDesc, OVTK_ClassId_Algorithm_PairingStrategyDesc) +}; +} // namespace Toolkit } // namespace OpenViBE diff --git a/toolkit/include/toolkit/algorithms/ovtkTAlgorithm.h b/toolkit/include/toolkit/algorithms/ovtkTAlgorithm.h index b2118982561c8eb33c631cffb0d3a06ad1a93bb1..9bd5b10f2fbc9806f9ed7fc2f65e7b5f2204e1c2 100644 --- a/toolkit/include/toolkit/algorithms/ovtkTAlgorithm.h +++ b/toolkit/include/toolkit/algorithms/ovtkTAlgorithm.h @@ -2,120 +2,96 @@ #include "../ovtk_base.h" -namespace OpenViBE +namespace OpenViBE { +namespace Toolkit { +template <class TAlgorithmParentClass> +class TAlgorithm : public TAlgorithmParentClass { - namespace Toolkit - { - template <class TAlgorithmParentClass> - class TAlgorithm : public TAlgorithmParentClass - { - public: - - TAlgorithm() { } - - bool initialize(Kernel::IAlgorithmContext& algorithmCtx) override - { - CScopedAlgorithm scopedAlgorithm(m_algorithmCtx, &algorithmCtx); - return initialize(); - } - - bool uninitialize(Kernel::IAlgorithmContext& algorithmCtx) override - { - CScopedAlgorithm scopedAlgorithm(m_algorithmCtx, &algorithmCtx); - return uninitialize(); - } +public: - bool process(Kernel::IAlgorithmContext& algorithmCtx) override - { - CScopedAlgorithm scopedAlgorithm(m_algorithmCtx, &algorithmCtx); - return process(); - } + TAlgorithm() { } - // ==================================================================================================================================== - - virtual bool initialize() { return true; } - virtual bool uninitialize() { return true; } - virtual bool process() = 0; + bool initialize(Kernel::IAlgorithmContext& algorithmCtx) override + { + CScopedAlgorithm scopedAlgorithm(m_algorithmCtx, &algorithmCtx); + return initialize(); + } - // ==================================================================================================================================== + bool uninitialize(Kernel::IAlgorithmContext& algorithmCtx) override + { + CScopedAlgorithm scopedAlgorithm(m_algorithmCtx, &algorithmCtx); + return uninitialize(); + } - virtual Kernel::IAlgorithmContext& getAlgorithmContext() - { - return *m_algorithmCtx; // should never be null - } + bool process(Kernel::IAlgorithmContext& algorithmCtx) override + { + CScopedAlgorithm scopedAlgorithm(m_algorithmCtx, &algorithmCtx); + return process(); + } - protected: + // ==================================================================================================================================== - virtual Kernel::IConfigurationManager& getConfigurationManager() - { - return m_algorithmCtx->getConfigurationManager(); // should never be null - } + virtual bool initialize() { return true; } + virtual bool uninitialize() { return true; } + virtual bool process() = 0; - virtual Kernel::IAlgorithmManager& getAlgorithmManager() - { - return m_algorithmCtx->getAlgorithmManager(); // should never be null - } + // ==================================================================================================================================== - virtual Kernel::ILogManager& getLogManager() - { - return m_algorithmCtx->getLogManager(); // should never be null - } + virtual Kernel::IAlgorithmContext& getAlgorithmContext() + { + return *m_algorithmCtx; // should never be null + } - virtual Kernel::IErrorManager& getErrorManager() - { - return m_algorithmCtx->getErrorManager(); // should never be null - } +protected: - virtual Kernel::ITypeManager& getTypeManager() - { - return m_algorithmCtx->getTypeManager(); // should never be null - } + virtual Kernel::IConfigurationManager& getConfigurationManager() { return m_algorithmCtx->getConfigurationManager(); } // should never be null + virtual Kernel::IAlgorithmManager& getAlgorithmManager() { return m_algorithmCtx->getAlgorithmManager(); } // should never be null + virtual Kernel::ILogManager& getLogManager() { return m_algorithmCtx->getLogManager(); } // should never be null + virtual Kernel::IErrorManager& getErrorManager() { return m_algorithmCtx->getErrorManager(); } // should never be null + virtual Kernel::ITypeManager& getTypeManager() { return m_algorithmCtx->getTypeManager(); } // should never be null - virtual CIdentifier getNextInputParameterIdentifier(const CIdentifier& rPreviousInputParameterIdentifier) const - { - return m_algorithmCtx->getNextInputParameterIdentifier(rPreviousInputParameterIdentifier); - } + virtual CIdentifier getNextInputParameterIdentifier(const CIdentifier& rPreviousInputParameterIdentifier) const + { + return m_algorithmCtx->getNextInputParameterIdentifier(rPreviousInputParameterIdentifier); + } - virtual Kernel::IParameter* getInputParameter(const CIdentifier& InputParameterID) { return m_algorithmCtx->getInputParameter(InputParameterID); } + virtual Kernel::IParameter* getInputParameter(const CIdentifier& InputParameterID) { return m_algorithmCtx->getInputParameter(InputParameterID); } - virtual CIdentifier getNextOutputParameterIdentifier(const CIdentifier& rPreviousOutputParameterIdentifier) const - { - return m_algorithmCtx->getNextOutputParameterIdentifier(rPreviousOutputParameterIdentifier); - } + virtual CIdentifier getNextOutputParameterIdentifier(const CIdentifier& rPreviousOutputParameterIdentifier) const + { + return m_algorithmCtx->getNextOutputParameterIdentifier(rPreviousOutputParameterIdentifier); + } - virtual Kernel::IParameter* getOutputParameter(const CIdentifier& outputParameterID) - { - return m_algorithmCtx->getOutputParameter(outputParameterID); - } + virtual Kernel::IParameter* getOutputParameter(const CIdentifier& outputParameterID) { return m_algorithmCtx->getOutputParameter(outputParameterID); } - virtual bool isInputTriggerActive(const CIdentifier& inputTriggerID) const { return m_algorithmCtx->isInputTriggerActive(inputTriggerID); } + virtual bool isInputTriggerActive(const CIdentifier& inputTriggerID) const { return m_algorithmCtx->isInputTriggerActive(inputTriggerID); } - virtual bool activateOutputTrigger(const CIdentifier& outputTriggerID, const bool bTriggerState) - { - return m_algorithmCtx->activateOutputTrigger(outputTriggerID, bTriggerState); - } + virtual bool activateOutputTrigger(const CIdentifier& outputTriggerID, const bool bTriggerState) + { + return m_algorithmCtx->activateOutputTrigger(outputTriggerID, bTriggerState); + } - // ==================================================================================================================================== + // ==================================================================================================================================== - _IsDerivedFromClass_(TAlgorithmParentClass, OVTK_ClassId_) + _IsDerivedFromClass_(TAlgorithmParentClass, OVTK_ClassId_) - private: +private: - class CScopedAlgorithm final - { - public: + class CScopedAlgorithm final + { + public: - CScopedAlgorithm(Kernel::IAlgorithmContext*& algorithmCtxRef, Kernel::IAlgorithmContext* algorithmCtx) - : m_algorithmCtx(algorithmCtxRef) { m_algorithmCtx = algorithmCtx; } + CScopedAlgorithm(Kernel::IAlgorithmContext*& algorithmCtxRef, Kernel::IAlgorithmContext* algorithmCtx) + : m_algorithmCtx(algorithmCtxRef) { m_algorithmCtx = algorithmCtx; } - ~CScopedAlgorithm() { m_algorithmCtx = nullptr; } + ~CScopedAlgorithm() { m_algorithmCtx = nullptr; } - protected: + protected: - Kernel::IAlgorithmContext*& m_algorithmCtx; - }; + Kernel::IAlgorithmContext*& m_algorithmCtx; + }; - Kernel::IAlgorithmContext* m_algorithmCtx = nullptr; - }; - } // namespace Toolkit + Kernel::IAlgorithmContext* m_algorithmCtx = nullptr; +}; +} // namespace Toolkit } // namespace OpenViBE diff --git a/toolkit/include/toolkit/algorithms/scenario-io/ovtkCAlgorithmScenarioExporter.h b/toolkit/include/toolkit/algorithms/scenario-io/ovtkCAlgorithmScenarioExporter.h index 63598cb193f37b657e3c8fb6abdd9fdaf9b49da9..a7c9c1d514fbf441aa6d838f5913350427850872 100644 --- a/toolkit/include/toolkit/algorithms/scenario-io/ovtkCAlgorithmScenarioExporter.h +++ b/toolkit/include/toolkit/algorithms/scenario-io/ovtkCAlgorithmScenarioExporter.h @@ -8,24 +8,22 @@ #define OVTK_ClassId_Algorithm_ScenarioExporter OpenViBE::CIdentifier(0x7C281FEA, 0x40B66277) #define OVTK_ClassId_Algorithm_ScenarioExporterDesc OpenViBE::CIdentifier(0x49A9778E, 0x7BB377F9) -namespace OpenViBE +namespace OpenViBE { +namespace Toolkit { +class OVTK_API CAlgorithmScenarioExporter : public TAlgorithm<Plugins::IAlgorithmScenarioExporter> { - namespace Toolkit - { - class OVTK_API CAlgorithmScenarioExporter : public TAlgorithm<Plugins::IAlgorithmScenarioExporter> - { - public: - void release() override { delete this; } - bool process() override; +public: + void release() override { delete this; } + bool process() override; - _IsDerivedFromClass_Final_(TAlgorithm<Plugins::IAlgorithmScenarioExporter>, OVTK_ClassId_Algorithm_ScenarioExporter) - }; + _IsDerivedFromClass_Final_(TAlgorithm<Plugins::IAlgorithmScenarioExporter>, OVTK_ClassId_Algorithm_ScenarioExporter) +}; - class OVTK_API CAlgorithmScenarioExporterDesc : public Plugins::IAlgorithmScenarioExporterDesc - { - public: +class OVTK_API CAlgorithmScenarioExporterDesc : public Plugins::IAlgorithmScenarioExporterDesc +{ +public: - _IsDerivedFromClass_(Plugins::IAlgorithmScenarioExporterDesc, OVTK_ClassId_Algorithm_ScenarioExporterDesc) - }; - } // namespace Toolkit + _IsDerivedFromClass_(Plugins::IAlgorithmScenarioExporterDesc, OVTK_ClassId_Algorithm_ScenarioExporterDesc) +}; +} // namespace Toolkit } // namespace OpenViBE diff --git a/toolkit/include/toolkit/algorithms/scenario-io/ovtkCAlgorithmScenarioImporter.h b/toolkit/include/toolkit/algorithms/scenario-io/ovtkCAlgorithmScenarioImporter.h index f11b3244b4c4ad764c9a96773e293b2974060f13..f44862571bfbea301585a374ce25ec5baafe1908 100644 --- a/toolkit/include/toolkit/algorithms/scenario-io/ovtkCAlgorithmScenarioImporter.h +++ b/toolkit/include/toolkit/algorithms/scenario-io/ovtkCAlgorithmScenarioImporter.h @@ -7,24 +7,22 @@ #define OVP_ClassId_Algorithm_ScenarioImporter OpenViBE::CIdentifier(0x1EE72169, 0x2BF146C1) #define OVP_ClassId_Algorithm_ScenarioImporterDesc OpenViBE::CIdentifier(0x503C0DDE, 0x5D4C6CB2) -namespace OpenViBE +namespace OpenViBE { +namespace Toolkit { +class OVTK_API CAlgorithmScenarioImporter : public TAlgorithm<Plugins::IAlgorithmScenarioImporter> { - namespace Toolkit - { - class OVTK_API CAlgorithmScenarioImporter : public TAlgorithm<Plugins::IAlgorithmScenarioImporter> - { - public: - void release() override { delete this; } - bool process() override; +public: + void release() override { delete this; } + bool process() override; - _IsDerivedFromClass_(TAlgorithm<Plugins::IAlgorithmScenarioImporter>, OVP_ClassId_Algorithm_ScenarioImporter) - }; + _IsDerivedFromClass_(TAlgorithm<Plugins::IAlgorithmScenarioImporter>, OVP_ClassId_Algorithm_ScenarioImporter) +}; - class OVTK_API CAlgorithmScenarioImporterDesc : public Plugins::IAlgorithmScenarioImporterDesc - { - public: +class OVTK_API CAlgorithmScenarioImporterDesc : public Plugins::IAlgorithmScenarioImporterDesc +{ +public: - _IsDerivedFromClass_(Plugins::IAlgorithmScenarioImporterDesc, OVP_ClassId_Algorithm_ScenarioImporterDesc) - }; - } // namespace Toolkit + _IsDerivedFromClass_(Plugins::IAlgorithmScenarioImporterDesc, OVP_ClassId_Algorithm_ScenarioImporterDesc) +}; +} // namespace Toolkit } // namespace OpenViBE diff --git a/toolkit/include/toolkit/box-algorithms/ovtkTBoxAlgorithm.h b/toolkit/include/toolkit/box-algorithms/ovtkTBoxAlgorithm.h index a0d4761219e2840daaaf0a3f5637228796eefb0d..7197c7690bf26cdf170a88d02098c86fcff3ea83 100755 --- a/toolkit/include/toolkit/box-algorithms/ovtkTBoxAlgorithm.h +++ b/toolkit/include/toolkit/box-algorithms/ovtkTBoxAlgorithm.h @@ -3,381 +3,361 @@ #include "../ovtk_base.h" #include <limits> -namespace OpenViBE +namespace OpenViBE { +namespace Toolkit { +template <class TBoxAlgorithmParentClass> +class TBoxAlgorithm : public TBoxAlgorithmParentClass { - namespace Toolkit +public: + + TBoxAlgorithm() { } + + // ==================================================================================================================================== + +private: + + virtual uint64_t getClockFrequency(Kernel::IBoxAlgorithmContext& ctx) { - template <class TBoxAlgorithmParentClass> - class TBoxAlgorithm : public TBoxAlgorithmParentClass - { - public: + CScopedBoxAlgorithm scopedBoxAlgorithm(m_boxAlgorithmCtx, &ctx); + return getClockFrequency(); + } - TBoxAlgorithm() { } + virtual bool initialize(Kernel::IBoxAlgorithmContext& ctx) + { + CScopedBoxAlgorithm scopedBoxAlgorithm(m_boxAlgorithmCtx, &ctx); + return initialize(); + } - // ==================================================================================================================================== + virtual bool uninitialize(Kernel::IBoxAlgorithmContext& ctx) + { + CScopedBoxAlgorithm scopedBoxAlgorithm(m_boxAlgorithmCtx, &ctx); + return uninitialize(); + } - private: + virtual bool processClock(Kernel::IBoxAlgorithmContext& ctx, Kernel::CMessageClock& msg) + { + CScopedBoxAlgorithm scopedBoxAlgorithm(m_boxAlgorithmCtx, &ctx); + return processClock(msg); + } - virtual uint64_t getClockFrequency(Kernel::IBoxAlgorithmContext& ctx) - { - CScopedBoxAlgorithm scopedBoxAlgorithm(m_boxAlgorithmCtx, &ctx); - return getClockFrequency(); - } + virtual bool processInput(Kernel::IBoxAlgorithmContext& ctx, const size_t index) + { + CScopedBoxAlgorithm scopedBoxAlgorithm(m_boxAlgorithmCtx, &ctx); + return processInput(index); + } - virtual bool initialize(Kernel::IBoxAlgorithmContext& ctx) - { - CScopedBoxAlgorithm scopedBoxAlgorithm(m_boxAlgorithmCtx, &ctx); - return initialize(); - } + virtual bool process(Kernel::IBoxAlgorithmContext& ctx) + { + CScopedBoxAlgorithm oScopedBoxAlgorithm(m_boxAlgorithmCtx, &ctx); + return process(); + } - virtual bool uninitialize(Kernel::IBoxAlgorithmContext& ctx) - { - CScopedBoxAlgorithm scopedBoxAlgorithm(m_boxAlgorithmCtx, &ctx); - return uninitialize(); - } + // ==================================================================================================================================== - virtual bool processEvent(Kernel::IBoxAlgorithmContext& ctx, CMessageEvent& messageEvent) - { - CScopedBoxAlgorithm scopedBoxAlgorithm(m_boxAlgorithmCtx, &ctx); - return processEvent(messageEvent); - } +public: - virtual bool processSignal(Kernel::IBoxAlgorithmContext& ctx, CMessageSignal& messageSignal) - { - CScopedBoxAlgorithm scopedBoxAlgorithm(m_boxAlgorithmCtx, &ctx); - return processSignal(messageSignal); - } + virtual uint64_t getClockFrequency() { return 0; } + virtual bool initialize() { return true; } + virtual bool uninitialize() { return true; } + virtual bool processClock(Kernel::CMessageClock& /*msg*/) { return false; } + virtual bool processInput(const size_t /*index*/) { return false; } + virtual bool process() = 0; - virtual bool processClock(Kernel::IBoxAlgorithmContext& ctx, CMessageClock& messageClock) - { - CScopedBoxAlgorithm scopedBoxAlgorithm(m_boxAlgorithmCtx, &ctx); - return processClock(messageClock); - } + // ==================================================================================================================================== - virtual bool processInput(Kernel::IBoxAlgorithmContext& ctx, const size_t index) - { - CScopedBoxAlgorithm scopedBoxAlgorithm(m_boxAlgorithmCtx, &ctx); - return processInput(index); - } + virtual Kernel::IBoxAlgorithmContext* getBoxAlgorithmContext() { return m_boxAlgorithmCtx; } + // virtual Kernel::IBoxAlgorithmContext& getBoxAlgorithmContext() { return *m_boxAlgorithmCtx; } this one should replace ! + virtual const Kernel::IBox& getStaticBoxContext() { return *m_boxAlgorithmCtx->getStaticBoxContext(); } + virtual Kernel::IBoxIO& getDynamicBoxContext() { return *m_boxAlgorithmCtx->getDynamicBoxContext(); } + virtual Kernel::IPlayerContext& getPlayerContext() { return *m_boxAlgorithmCtx->getPlayerContext(); } - virtual bool process(Kernel::IBoxAlgorithmContext& ctx) - { - CScopedBoxAlgorithm oScopedBoxAlgorithm(m_boxAlgorithmCtx, &ctx); - return process(); - } + virtual Kernel::IAlgorithmManager& getAlgorithmManager() { return getPlayerContext().getAlgorithmManager(); } + virtual Kernel::IConfigurationManager& getConfigurationManager() { return getPlayerContext().getConfigurationManager(); } + virtual Kernel::ILogManager& getLogManager() { return getPlayerContext().getLogManager(); } + virtual Kernel::IErrorManager& getErrorManager() { return getPlayerContext().getErrorManager(); } + virtual Kernel::IScenarioManager& getScenarioManager() { return getPlayerContext().getScenarioManager(); } + virtual Kernel::ITypeManager& getTypeManager() { return getPlayerContext().getTypeManager(); } + + virtual bool canCreatePluginObject(const CIdentifier& pluginID) { return getPlayerContext().canCreatePluginObject(pluginID); } - // ==================================================================================================================================== + virtual Plugins::IPluginObject* createPluginObject(const CIdentifier& pluginID) { return getPlayerContext().createPluginObject(pluginID); } - public: + virtual bool releasePluginObject(Plugins::IPluginObject* pluginObject) { return getPlayerContext().releasePluginObject(pluginObject); } - virtual uint64_t getClockFrequency() { return 0; } - virtual bool initialize() { return true; } - virtual bool uninitialize() { return true; } - virtual bool processEvent(CMessageEvent& /*messageEvent*/) { return false; } - virtual bool processSignal(CMessageSignal& /*messageSignal*/) { return false; } - virtual bool processClock(CMessageClock& /*messageClock*/) { return false; } - virtual bool processInput(const size_t /*index*/) { return false; } - virtual bool process() = 0; + // ==================================================================================================================================== + + virtual void appendOutputChunkData(const size_t outputIdx, const void* buffer, const size_t size) + { + Kernel::IBoxAlgorithmContext* context = this->getBoxAlgorithmContext(); + if (context) + { + Kernel::IBoxIO* boxContext = context->getDynamicBoxContext(); + if (boxContext) { boxContext->appendOutputChunkData(outputIdx, static_cast<const uint8_t*>(buffer), size); } + } + } - // ==================================================================================================================================== + template <size_t TOutputIdx> + void appendOutputChunkData(const void* buffer, const size_t size) { appendOutputChunkData(TOutputIdx, buffer, size); } - virtual Kernel::IBoxAlgorithmContext* getBoxAlgorithmContext() { return m_boxAlgorithmCtx; } - // virtual Kernel::IBoxAlgorithmContext& getBoxAlgorithmContext() { return *m_boxAlgorithmCtx; } this one should replace ! - virtual const Kernel::IBox& getStaticBoxContext() { return *m_boxAlgorithmCtx->getStaticBoxContext(); } - virtual Kernel::IBoxIO& getDynamicBoxContext() { return *m_boxAlgorithmCtx->getDynamicBoxContext(); } - virtual Kernel::IPlayerContext& getPlayerContext() { return *m_boxAlgorithmCtx->getPlayerContext(); } + _IsDerivedFromClass_(TBoxAlgorithmParentClass, OVTK_ClassId_) - virtual Kernel::IAlgorithmManager& getAlgorithmManager() { return getPlayerContext().getAlgorithmManager(); } - virtual Kernel::IConfigurationManager& getConfigurationManager() { return getPlayerContext().getConfigurationManager(); } - virtual Kernel::ILogManager& getLogManager() { return getPlayerContext().getLogManager(); } - virtual Kernel::IErrorManager& getErrorManager() { return getPlayerContext().getErrorManager(); } - virtual Kernel::IScenarioManager& getScenarioManager() { return getPlayerContext().getScenarioManager(); } - virtual Kernel::ITypeManager& getTypeManager() { return getPlayerContext().getTypeManager(); } +protected: - virtual bool canCreatePluginObject(const CIdentifier& pluginID) { return getPlayerContext().canCreatePluginObject(pluginID); } + class FSettingValueAutoCast + { + public: + FSettingValueAutoCast(Kernel::IBoxAlgorithmContext& ctx, const size_t index) + : m_logManager(ctx.getPlayerContext()->getLogManager()), + m_errorManager(ctx.getPlayerContext()->getErrorManager()), + m_typeManager(ctx.getPlayerContext()->getTypeManager()), + m_configManager(ctx.getPlayerContext()->getConfigurationManager()) + { + ctx.getStaticBoxContext()->getSettingValue(index, m_settingValue); + ctx.getStaticBoxContext()->getSettingType(index, m_settingType); + } + + FSettingValueAutoCast(Kernel::IBoxAlgorithmContext& ctx, const CString& name) + : m_logManager(ctx.getPlayerContext()->getLogManager()), + m_errorManager(ctx.getPlayerContext()->getErrorManager()), + m_typeManager(ctx.getPlayerContext()->getTypeManager()), + m_configManager(ctx.getPlayerContext()->getConfigurationManager()) + { + ctx.getStaticBoxContext()->getSettingValue(name, m_settingValue); + ctx.getStaticBoxContext()->getInterfacorType(Kernel::EBoxInterfacorType::Setting, name, m_settingType); + } + + FSettingValueAutoCast(Kernel::IBoxAlgorithmContext& ctx, const CIdentifier& identifier) + : m_logManager(ctx.getPlayerContext()->getLogManager()), + m_errorManager(ctx.getPlayerContext()->getErrorManager()), + m_typeManager(ctx.getPlayerContext()->getTypeManager()), + m_configManager(ctx.getPlayerContext()->getConfigurationManager()) + { + ctx.getStaticBoxContext()->getSettingValue(identifier, m_settingValue); + ctx.getStaticBoxContext()->getInterfacorType(Kernel::EBoxInterfacorType::Setting, identifier, m_settingType); + } - virtual Plugins::IPluginObject* createPluginObject(const CIdentifier& pluginID) { return getPlayerContext().createPluginObject(pluginID); } + operator uint32_t() const + { + double result; + const CString value = m_configManager.expand(m_settingValue); - virtual bool releasePluginObject(Plugins::IPluginObject* pluginObject) { return getPlayerContext().releasePluginObject(pluginObject); } + OV_ERROR_UNLESS(m_typeManager.evaluateSettingValue(value, result), + "Could not expand numeric expression [" << m_settingValue << "] to unsigned integer 32bits.", + Kernel::ErrorType::BadParsing, std::numeric_limits<uint32_t>::max(), m_errorManager, m_logManager); - // ==================================================================================================================================== + return uint32_t(result); + } - virtual void appendOutputChunkData(const size_t outputIdx, const void* buffer, const size_t size) + operator uint64_t() const + { + uint64_t stimId = std::numeric_limits<uint64_t>::max(); + const CString value = m_configManager.expand(m_settingValue); + double result; + if (m_typeManager.isEnumeration(m_settingType)) { - Kernel::IBoxAlgorithmContext* context = this->getBoxAlgorithmContext(); - if (context) - { - Kernel::IBoxIO* boxContext = context->getDynamicBoxContext(); - if (boxContext) { boxContext->appendOutputChunkData(outputIdx, static_cast<const uint8_t*>(buffer), size); } - } + stimId = m_typeManager.getEnumerationEntryValueFromName(m_settingType, value); + + OV_ERROR_UNLESS(stimId != std::numeric_limits<uint64_t>::max(), + "Did not find an enumeration value for [" << m_typeManager.getTypeName(m_settingType) << "] = [" << m_settingValue << + "]", + Kernel::ErrorType::BadParsing, std::numeric_limits<uint64_t>::max(), m_errorManager, m_logManager); } + else if (m_typeManager.evaluateSettingValue(value, result)) { return uint64_t(result); } - template <size_t TOutputIdx> - void appendOutputChunkData(const void* buffer, const size_t size) { appendOutputChunkData(TOutputIdx, buffer, size); } + // Seems like currently some plugins use FSettingValueAutoCast without knowing then setting type. + // In this case, to avoid to pollute the console with useless messages, throw a message only if the + // setting should be an integer. + OV_ERROR_UNLESS(stimId != std::numeric_limits<uint64_t>::max() || m_settingType != OV_TypeId_Integer, + "Could not expand numeric expression [" << m_settingValue << "] to unsigned integer 64bits.", + Kernel::ErrorType::BadParsing, std::numeric_limits<uint64_t>::max(), m_errorManager, m_logManager); - _IsDerivedFromClass_(TBoxAlgorithmParentClass, OVTK_ClassId_) + return stimId; + } - protected: + operator int() const + { + double res; + const CString value = m_configManager.expand(m_settingValue); - class FSettingValueAutoCast - { - public: - FSettingValueAutoCast(Kernel::IBoxAlgorithmContext& ctx, const size_t index) - : m_logManager(ctx.getPlayerContext()->getLogManager()), - m_errorManager(ctx.getPlayerContext()->getErrorManager()), - m_typeManager(ctx.getPlayerContext()->getTypeManager()), - m_configManager(ctx.getPlayerContext()->getConfigurationManager()) - { - ctx.getStaticBoxContext()->getSettingValue(index, m_settingValue); - ctx.getStaticBoxContext()->getSettingType(index, m_settingType); - } - - FSettingValueAutoCast(Kernel::IBoxAlgorithmContext& ctx, const CString& name) - : m_logManager(ctx.getPlayerContext()->getLogManager()), - m_errorManager(ctx.getPlayerContext()->getErrorManager()), - m_typeManager(ctx.getPlayerContext()->getTypeManager()), - m_configManager(ctx.getPlayerContext()->getConfigurationManager()) - { - ctx.getStaticBoxContext()->getSettingValue(name, m_settingValue); - ctx.getStaticBoxContext()->getInterfacorType(Kernel::EBoxInterfacorType::Setting, name, m_settingType); - } - - FSettingValueAutoCast(Kernel::IBoxAlgorithmContext& ctx, const CIdentifier& identifier) - : m_logManager(ctx.getPlayerContext()->getLogManager()), - m_errorManager(ctx.getPlayerContext()->getErrorManager()), - m_typeManager(ctx.getPlayerContext()->getTypeManager()), - m_configManager(ctx.getPlayerContext()->getConfigurationManager()) - { - ctx.getStaticBoxContext()->getSettingValue(identifier, m_settingValue); - ctx.getStaticBoxContext()->getInterfacorType(Kernel::EBoxInterfacorType::Setting, identifier, m_settingType); - } - - operator uint32_t() const - { - double result; - const CString value = m_configManager.expand(m_settingValue); - - OV_ERROR_UNLESS(m_typeManager.evaluateSettingValue(value, result), - "Could not expand numeric expression [" << m_settingValue << "] to unsigned integer 32bits.", - Kernel::ErrorType::BadParsing, std::numeric_limits<uint32_t>::max(), m_errorManager, m_logManager); - - return uint32_t(result); - } - - operator uint64_t() const - { - uint64_t stimId = std::numeric_limits<uint64_t>::max(); - const CString value = m_configManager.expand(m_settingValue); - double result; - if (m_typeManager.isEnumeration(m_settingType)) - { - stimId = m_typeManager.getEnumerationEntryValueFromName(m_settingType, value); - - OV_ERROR_UNLESS(stimId != std::numeric_limits<uint64_t>::max(), - "Did not find an enumeration value for [" << m_typeManager.getTypeName(m_settingType) << "] = [" << m_settingValue << - "]", - Kernel::ErrorType::BadParsing, std::numeric_limits<uint64_t>::max(), m_errorManager, m_logManager); - } - else if (m_typeManager.evaluateSettingValue(value, result)) { return uint64_t(result); } - - // Seems like currently some plugins use FSettingValueAutoCast without knowing then setting type. - // In this case, to avoid to pollute the console with useless messages, throw a message only if the - // setting should be an integer. - OV_ERROR_UNLESS(stimId != std::numeric_limits<uint64_t>::max() || m_settingType != OV_TypeId_Integer, - "Could not expand numeric expression [" << m_settingValue << "] to unsigned integer 64bits.", - Kernel::ErrorType::BadParsing, std::numeric_limits<uint64_t>::max(), m_errorManager, m_logManager); - - return stimId; - } - - operator int() const - { - double res; - const CString value = m_configManager.expand(m_settingValue); - - OV_ERROR_UNLESS(m_typeManager.evaluateSettingValue(value, res), - "Could not expand numeric expression [" << m_settingValue << "] to integer 32bits.", - Kernel::ErrorType::BadParsing, std::numeric_limits<int>::max(), m_errorManager, m_logManager); - - return int(res); - } - - operator int64_t() const - { - double res; - const CString value = m_configManager.expand(m_settingValue); - - OV_ERROR_UNLESS(m_typeManager.evaluateSettingValue(value, res), - "Could not expand numeric expression [" << m_settingValue << "] to integer 64bits.", - Kernel::ErrorType::BadParsing, std::numeric_limits<int64_t>::max(), m_errorManager, m_logManager); - - return int64_t(res); - } - - operator double() const - { - double res; - const CString value = m_configManager.expand(m_settingValue); - - OV_ERROR_UNLESS(m_typeManager.evaluateSettingValue(value, res), - "Could not expand numeric expression [" << m_settingValue << "] to double.", - Kernel::ErrorType::BadParsing, std::numeric_limits<double>::max(), m_errorManager, m_logManager); - - return double(res); - } - - operator bool() const { return m_configManager.expandAsBoolean(m_settingValue); } - - operator CString() const { return m_configManager.expand(m_settingValue); } - - private: - Kernel::ILogManager& m_logManager; - Kernel::IErrorManager& m_errorManager; - Kernel::ITypeManager& m_typeManager; - Kernel::IConfigurationManager& m_configManager; - CString m_settingValue; - CIdentifier m_settingType = OV_UndefinedIdentifier; - }; - - private: - - class CScopedBoxAlgorithm final - { - public: - CScopedBoxAlgorithm(Kernel::IBoxAlgorithmContext*& ctxRef, Kernel::IBoxAlgorithmContext* ctx) - : m_boxAlgorithmCtx(ctxRef) { m_boxAlgorithmCtx = ctx; } + OV_ERROR_UNLESS(m_typeManager.evaluateSettingValue(value, res), + "Could not expand numeric expression [" << m_settingValue << "] to integer 32bits.", + Kernel::ErrorType::BadParsing, std::numeric_limits<int>::max(), m_errorManager, m_logManager); - ~CScopedBoxAlgorithm() { m_boxAlgorithmCtx = nullptr; } + return int(res); + } + + operator int64_t() const + { + double res; + const CString value = m_configManager.expand(m_settingValue); - protected: - Kernel::IBoxAlgorithmContext*& m_boxAlgorithmCtx; - }; + OV_ERROR_UNLESS(m_typeManager.evaluateSettingValue(value, res), + "Could not expand numeric expression [" << m_settingValue << "] to integer 64bits.", + Kernel::ErrorType::BadParsing, std::numeric_limits<int64_t>::max(), m_errorManager, m_logManager); - Kernel::IBoxAlgorithmContext* m_boxAlgorithmCtx = nullptr; - }; + return int64_t(res); + } - template <class TBoxListenerParentClass> - class TBoxListener : public TBoxListenerParentClass + operator double() const { - public: + double res; + const CString value = m_configManager.expand(m_settingValue); - TBoxListener() { } + OV_ERROR_UNLESS(m_typeManager.evaluateSettingValue(value, res), + "Could not expand numeric expression [" << m_settingValue << "] to double.", + Kernel::ErrorType::BadParsing, std::numeric_limits<double>::max(), m_errorManager, m_logManager); - private: + return double(res); + } - virtual bool initialize(Kernel::IBoxListenerContext& ctx) - { - CScopedBoxListener scopedBoxListener(m_boxListenerCtx, &ctx); - return initialize(); - } + operator bool() const { return m_configManager.expandAsBoolean(m_settingValue); } - virtual bool uninitialize(Kernel::IBoxListenerContext& ctx) - { - CScopedBoxListener scopedBoxListener(m_boxListenerCtx, &ctx); - return uninitialize(); - } + operator CString() const { return m_configManager.expand(m_settingValue); } - virtual bool process(Kernel::IBoxListenerContext& ctx, const Kernel::EBoxModification eBoxModificationType) - { - CScopedBoxListener scopedBoxListener(m_boxListenerCtx, &ctx); - switch (eBoxModificationType) - { - case Kernel::EBoxModification::Initialized: return this->onInitialized(m_boxListenerCtx->getBox()); - case Kernel::EBoxModification::DefaultInitialized: return this->onDefaultInitialized(m_boxListenerCtx->getBox()); - case Kernel::EBoxModification::NameChanged: return this->onNameChanged(m_boxListenerCtx->getBox()); - case Kernel::EBoxModification::IdentifierChanged: return this->onIdentifierChanged(m_boxListenerCtx->getBox()); - case Kernel::EBoxModification::AlgorithmClassIdentifierChanged: return this->onAlgorithmClassIdentifierChanged(m_boxListenerCtx->getBox()); - case Kernel::EBoxModification::InputConnected: return this->onInputConnected(m_boxListenerCtx->getBox(), m_boxListenerCtx->getIndex()); - case Kernel::EBoxModification::InputDisconnected: return this->onInputDisconnected(m_boxListenerCtx->getBox(), m_boxListenerCtx->getIndex()); - case Kernel::EBoxModification::InputAdded: return this->onInputAdded(m_boxListenerCtx->getBox(), m_boxListenerCtx->getIndex()); - case Kernel::EBoxModification::InputRemoved: return this->onInputRemoved(m_boxListenerCtx->getBox(), m_boxListenerCtx->getIndex()); - case Kernel::EBoxModification::InputTypeChanged: return this->onInputTypeChanged(m_boxListenerCtx->getBox(), m_boxListenerCtx->getIndex()); - case Kernel::EBoxModification::InputNameChanged: return this->onInputNameChanged(m_boxListenerCtx->getBox(), m_boxListenerCtx->getIndex()); - case Kernel::EBoxModification::OutputConnected: return this->onOutputConnected(m_boxListenerCtx->getBox(), m_boxListenerCtx->getIndex()); - case Kernel::EBoxModification::OutputDisconnected: return this-> - onOutputDisconnected(m_boxListenerCtx->getBox(), m_boxListenerCtx->getIndex()); - case Kernel::EBoxModification::OutputAdded: return this->onOutputAdded(m_boxListenerCtx->getBox(), m_boxListenerCtx->getIndex()); - case Kernel::EBoxModification::OutputRemoved: return this->onOutputRemoved(m_boxListenerCtx->getBox(), m_boxListenerCtx->getIndex()); - case Kernel::EBoxModification::OutputTypeChanged: return this->onOutputTypeChanged(m_boxListenerCtx->getBox(), m_boxListenerCtx->getIndex()); - case Kernel::EBoxModification::OutputNameChanged: return this->onOutputNameChanged(m_boxListenerCtx->getBox(), m_boxListenerCtx->getIndex()); - case Kernel::EBoxModification::SettingAdded: return this->onSettingAdded(m_boxListenerCtx->getBox(), m_boxListenerCtx->getIndex()); - case Kernel::EBoxModification::SettingRemoved: return this->onSettingRemoved(m_boxListenerCtx->getBox(), m_boxListenerCtx->getIndex()); - case Kernel::EBoxModification::SettingTypeChanged: return this-> - onSettingTypeChanged(m_boxListenerCtx->getBox(), m_boxListenerCtx->getIndex()); - case Kernel::EBoxModification::SettingNameChanged: return this-> - onSettingNameChanged(m_boxListenerCtx->getBox(), m_boxListenerCtx->getIndex()); - case Kernel::EBoxModification::SettingDefaultValueChanged: return this->onSettingDefaultValueChanged( - m_boxListenerCtx->getBox(), m_boxListenerCtx->getIndex()); - case Kernel::EBoxModification::SettingValueChanged: return this->onSettingValueChanged( - m_boxListenerCtx->getBox(), m_boxListenerCtx->getIndex()); - default: OV_ERROR_KRF("Unhandled box modification type " << size_t(eBoxModificationType), Kernel::ErrorType::BadArgument); - } - //return false; - } + private: + Kernel::ILogManager& m_logManager; + Kernel::IErrorManager& m_errorManager; + Kernel::ITypeManager& m_typeManager; + Kernel::IConfigurationManager& m_configManager; + CString m_settingValue; + CIdentifier m_settingType = OV_UndefinedIdentifier; + }; - // ==================================================================================================================================== - - public: - - virtual bool initialize() { return true; } - virtual bool uninitialize() { return true; } - virtual bool onInitialized(Kernel::IBox& /*box*/) { return true; } - virtual bool onDefaultInitialized(Kernel::IBox& /*box*/) { return true; } - virtual bool onNameChanged(Kernel::IBox& /*box*/) { return true; } - virtual bool onIdentifierChanged(Kernel::IBox& /*box*/) { return true; } - virtual bool onAlgorithmClassIdentifierChanged(Kernel::IBox& /*box*/) { return true; } - virtual bool onInputConnected(Kernel::IBox& /*box*/, const size_t /*index*/) { return true; } - virtual bool onInputDisconnected(Kernel::IBox& /*box*/, const size_t /*index*/) { return true; } - virtual bool onInputAdded(Kernel::IBox& /*box*/, const size_t /*index*/) { return true; } - virtual bool onInputRemoved(Kernel::IBox& /*box*/, const size_t /*index*/) { return true; } - virtual bool onInputTypeChanged(Kernel::IBox& /*box*/, const size_t /*index*/) { return true; } - virtual bool onInputNameChanged(Kernel::IBox& /*box*/, const size_t /*index*/) { return true; } - virtual bool onOutputConnected(Kernel::IBox& /*box*/, const size_t /*index*/) { return true; } - virtual bool onOutputDisconnected(Kernel::IBox& /*box*/, const size_t /*index*/) { return true; } - virtual bool onOutputAdded(Kernel::IBox& /*box*/, const size_t /*index*/) { return true; } - virtual bool onOutputRemoved(Kernel::IBox& /*box*/, const size_t /*index*/) { return true; } - virtual bool onOutputTypeChanged(Kernel::IBox& /*box*/, const size_t /*index*/) { return true; } - virtual bool onOutputNameChanged(Kernel::IBox& /*box*/, const size_t /*index*/) { return true; } - virtual bool onSettingAdded(Kernel::IBox& /*box*/, const size_t /*index*/) { return true; } - virtual bool onSettingRemoved(Kernel::IBox& /*box*/, const size_t /*index*/) { return true; } - virtual bool onSettingTypeChanged(Kernel::IBox& /*box*/, const size_t /*index*/) { return true; } - virtual bool onSettingNameChanged(Kernel::IBox& /*box*/, const size_t /*index*/) { return true; } - virtual bool onSettingDefaultValueChanged(Kernel::IBox& /*box*/, const size_t /*index*/) { return true; } - virtual bool onSettingValueChanged(Kernel::IBox& /*box*/, const size_t /*index*/) { return true; } - - // ==================================================================================================================================== - - virtual Kernel::IAlgorithmManager& getAlgorithmManager() const { return m_boxListenerCtx->getAlgorithmManager(); } - virtual Kernel::IPlayerManager& getPlayerManager() const { return m_boxListenerCtx->getPlayerManager(); } - virtual Kernel::IPluginManager& getPluginManager() const { return m_boxListenerCtx->getPluginManager(); } - virtual Kernel::IMetaboxManager& getMetaboxManager() const { return m_boxListenerCtx->getMetaboxManager(); } - virtual Kernel::IScenarioManager& getScenarioManager() const { return m_boxListenerCtx->getScenarioManager(); } - virtual Kernel::ITypeManager& getTypeManager() const { return m_boxListenerCtx->getTypeManager(); } - virtual Kernel::ILogManager& getLogManager() const { return m_boxListenerCtx->getLogManager(); } - virtual Kernel::IErrorManager& getErrorManager() const { return m_boxListenerCtx->getErrorManager(); } - virtual Kernel::IConfigurationManager& getConfigurationManager() const { return m_boxListenerCtx->getConfigurationManager(); } - - virtual Kernel::IScenario& getScenario() const { return m_boxListenerCtx->getScenario(); } - - // ==================================================================================================================================== - - _IsDerivedFromClass_(TBoxListenerParentClass, OVTK_ClassId_) - - private: - - class CScopedBoxListener final - { - public: - CScopedBoxListener(Kernel::IBoxListenerContext*& ctxRef, Kernel::IBoxListenerContext* ctx) - : m_boxListenerCtx(ctxRef) { m_boxListenerCtx = ctx; } +private: + + class CScopedBoxAlgorithm final + { + public: + CScopedBoxAlgorithm(Kernel::IBoxAlgorithmContext*& ctxRef, Kernel::IBoxAlgorithmContext* ctx) + : m_boxAlgorithmCtx(ctxRef) { m_boxAlgorithmCtx = ctx; } + + ~CScopedBoxAlgorithm() { m_boxAlgorithmCtx = nullptr; } + + protected: + Kernel::IBoxAlgorithmContext*& m_boxAlgorithmCtx; + }; + + Kernel::IBoxAlgorithmContext* m_boxAlgorithmCtx = nullptr; +}; + +template <class TBoxListenerParentClass> +class TBoxListener : public TBoxListenerParentClass +{ +public: + + TBoxListener() { } + +private: + + virtual bool initialize(Kernel::IBoxListenerContext& ctx) + { + CScopedBoxListener scopedBoxListener(m_boxListenerCtx, &ctx); + return initialize(); + } + + virtual bool uninitialize(Kernel::IBoxListenerContext& ctx) + { + CScopedBoxListener scopedBoxListener(m_boxListenerCtx, &ctx); + return uninitialize(); + } + + virtual bool process(Kernel::IBoxListenerContext& ctx, const Kernel::EBoxModification eBoxModificationType) + { + CScopedBoxListener scopedBoxListener(m_boxListenerCtx, &ctx); + switch (eBoxModificationType) + { + case Kernel::EBoxModification::Initialized: return this->onInitialized(m_boxListenerCtx->getBox()); + case Kernel::EBoxModification::DefaultInitialized: return this->onDefaultInitialized(m_boxListenerCtx->getBox()); + case Kernel::EBoxModification::NameChanged: return this->onNameChanged(m_boxListenerCtx->getBox()); + case Kernel::EBoxModification::IdentifierChanged: return this->onIdentifierChanged(m_boxListenerCtx->getBox()); + case Kernel::EBoxModification::AlgorithmClassIdentifierChanged: return this->onAlgorithmClassIdentifierChanged(m_boxListenerCtx->getBox()); + case Kernel::EBoxModification::InputConnected: return this->onInputConnected(m_boxListenerCtx->getBox(), m_boxListenerCtx->getIndex()); + case Kernel::EBoxModification::InputDisconnected: return this->onInputDisconnected(m_boxListenerCtx->getBox(), m_boxListenerCtx->getIndex()); + case Kernel::EBoxModification::InputAdded: return this->onInputAdded(m_boxListenerCtx->getBox(), m_boxListenerCtx->getIndex()); + case Kernel::EBoxModification::InputRemoved: return this->onInputRemoved(m_boxListenerCtx->getBox(), m_boxListenerCtx->getIndex()); + case Kernel::EBoxModification::InputTypeChanged: return this->onInputTypeChanged(m_boxListenerCtx->getBox(), m_boxListenerCtx->getIndex()); + case Kernel::EBoxModification::InputNameChanged: return this->onInputNameChanged(m_boxListenerCtx->getBox(), m_boxListenerCtx->getIndex()); + case Kernel::EBoxModification::OutputConnected: return this->onOutputConnected(m_boxListenerCtx->getBox(), m_boxListenerCtx->getIndex()); + case Kernel::EBoxModification::OutputDisconnected: return this->onOutputDisconnected(m_boxListenerCtx->getBox(), m_boxListenerCtx->getIndex()); + case Kernel::EBoxModification::OutputAdded: return this->onOutputAdded(m_boxListenerCtx->getBox(), m_boxListenerCtx->getIndex()); + case Kernel::EBoxModification::OutputRemoved: return this->onOutputRemoved(m_boxListenerCtx->getBox(), m_boxListenerCtx->getIndex()); + case Kernel::EBoxModification::OutputTypeChanged: return this->onOutputTypeChanged(m_boxListenerCtx->getBox(), m_boxListenerCtx->getIndex()); + case Kernel::EBoxModification::OutputNameChanged: return this->onOutputNameChanged(m_boxListenerCtx->getBox(), m_boxListenerCtx->getIndex()); + case Kernel::EBoxModification::SettingAdded: return this->onSettingAdded(m_boxListenerCtx->getBox(), m_boxListenerCtx->getIndex()); + case Kernel::EBoxModification::SettingRemoved: return this->onSettingRemoved(m_boxListenerCtx->getBox(), m_boxListenerCtx->getIndex()); + case Kernel::EBoxModification::SettingTypeChanged: return this->onSettingTypeChanged(m_boxListenerCtx->getBox(), m_boxListenerCtx->getIndex()); + case Kernel::EBoxModification::SettingNameChanged: return this->onSettingNameChanged(m_boxListenerCtx->getBox(), m_boxListenerCtx->getIndex()); + case Kernel::EBoxModification::SettingDefaultValueChanged: return this->onSettingDefaultValueChanged( + m_boxListenerCtx->getBox(), m_boxListenerCtx->getIndex()); + case Kernel::EBoxModification::SettingValueChanged: return this->onSettingValueChanged(m_boxListenerCtx->getBox(), m_boxListenerCtx->getIndex()); + default: OV_ERROR_KRF("Unhandled box modification type " << size_t(eBoxModificationType), Kernel::ErrorType::BadArgument); + } + //return false; + } + + // ==================================================================================================================================== + +public: + + virtual bool initialize() { return true; } + virtual bool uninitialize() { return true; } + virtual bool onInitialized(Kernel::IBox& /*box*/) { return true; } + virtual bool onDefaultInitialized(Kernel::IBox& /*box*/) { return true; } + virtual bool onNameChanged(Kernel::IBox& /*box*/) { return true; } + virtual bool onIdentifierChanged(Kernel::IBox& /*box*/) { return true; } + virtual bool onAlgorithmClassIdentifierChanged(Kernel::IBox& /*box*/) { return true; } + virtual bool onInputConnected(Kernel::IBox& /*box*/, const size_t /*index*/) { return true; } + virtual bool onInputDisconnected(Kernel::IBox& /*box*/, const size_t /*index*/) { return true; } + virtual bool onInputAdded(Kernel::IBox& /*box*/, const size_t /*index*/) { return true; } + virtual bool onInputRemoved(Kernel::IBox& /*box*/, const size_t /*index*/) { return true; } + virtual bool onInputTypeChanged(Kernel::IBox& /*box*/, const size_t /*index*/) { return true; } + virtual bool onInputNameChanged(Kernel::IBox& /*box*/, const size_t /*index*/) { return true; } + virtual bool onOutputConnected(Kernel::IBox& /*box*/, const size_t /*index*/) { return true; } + virtual bool onOutputDisconnected(Kernel::IBox& /*box*/, const size_t /*index*/) { return true; } + virtual bool onOutputAdded(Kernel::IBox& /*box*/, const size_t /*index*/) { return true; } + virtual bool onOutputRemoved(Kernel::IBox& /*box*/, const size_t /*index*/) { return true; } + virtual bool onOutputTypeChanged(Kernel::IBox& /*box*/, const size_t /*index*/) { return true; } + virtual bool onOutputNameChanged(Kernel::IBox& /*box*/, const size_t /*index*/) { return true; } + virtual bool onSettingAdded(Kernel::IBox& /*box*/, const size_t /*index*/) { return true; } + virtual bool onSettingRemoved(Kernel::IBox& /*box*/, const size_t /*index*/) { return true; } + virtual bool onSettingTypeChanged(Kernel::IBox& /*box*/, const size_t /*index*/) { return true; } + virtual bool onSettingNameChanged(Kernel::IBox& /*box*/, const size_t /*index*/) { return true; } + virtual bool onSettingDefaultValueChanged(Kernel::IBox& /*box*/, const size_t /*index*/) { return true; } + virtual bool onSettingValueChanged(Kernel::IBox& /*box*/, const size_t /*index*/) { return true; } + + // ==================================================================================================================================== + + virtual Kernel::IAlgorithmManager& getAlgorithmManager() const { return m_boxListenerCtx->getAlgorithmManager(); } + virtual Kernel::IPlayerManager& getPlayerManager() const { return m_boxListenerCtx->getPlayerManager(); } + virtual Kernel::IPluginManager& getPluginManager() const { return m_boxListenerCtx->getPluginManager(); } + virtual Kernel::IMetaboxManager& getMetaboxManager() const { return m_boxListenerCtx->getMetaboxManager(); } + virtual Kernel::IScenarioManager& getScenarioManager() const { return m_boxListenerCtx->getScenarioManager(); } + virtual Kernel::ITypeManager& getTypeManager() const { return m_boxListenerCtx->getTypeManager(); } + virtual Kernel::ILogManager& getLogManager() const { return m_boxListenerCtx->getLogManager(); } + virtual Kernel::IErrorManager& getErrorManager() const { return m_boxListenerCtx->getErrorManager(); } + virtual Kernel::IConfigurationManager& getConfigurationManager() const { return m_boxListenerCtx->getConfigurationManager(); } + + virtual Kernel::IScenario& getScenario() const { return m_boxListenerCtx->getScenario(); } + + // ==================================================================================================================================== + + _IsDerivedFromClass_(TBoxListenerParentClass, OVTK_ClassId_) + +private: + + class CScopedBoxListener final + { + public: + CScopedBoxListener(Kernel::IBoxListenerContext*& ctxRef, Kernel::IBoxListenerContext* ctx) + : m_boxListenerCtx(ctxRef) { m_boxListenerCtx = ctx; } - ~CScopedBoxListener() { m_boxListenerCtx = nullptr; } + ~CScopedBoxListener() { m_boxListenerCtx = nullptr; } - protected: - Kernel::IBoxListenerContext*& m_boxListenerCtx; - }; + protected: + Kernel::IBoxListenerContext*& m_boxListenerCtx; + }; - Kernel::IBoxListenerContext* m_boxListenerCtx = nullptr; - }; - } // namespace Toolkit + Kernel::IBoxListenerContext* m_boxListenerCtx = nullptr; +}; +} // namespace Toolkit } // namespace OpenViBE diff --git a/toolkit/include/toolkit/codecs/decoders/ovtkTAcquisitionDecoder.h b/toolkit/include/toolkit/codecs/decoders/ovtkTAcquisitionDecoder.h index c57e1601412f6ca37c78a9f4ab6524ee6c669290..f72c59e2bb5491b4406e985e1751194208f87d05 100644 --- a/toolkit/include/toolkit/codecs/decoders/ovtkTAcquisitionDecoder.h +++ b/toolkit/include/toolkit/codecs/decoders/ovtkTAcquisitionDecoder.h @@ -6,99 +6,96 @@ #include "ovtkTStreamedMatrixDecoder.h" -namespace OpenViBE +namespace OpenViBE { +namespace Toolkit { +template <class T> +class TAcquisitionDecoderLocal : public T { - namespace Toolkit +protected: + + Kernel::TParameterHandler<uint64_t> op_bufferDuration; + Kernel::TParameterHandler<IMemoryBuffer*> op_experimentInfoStream; + Kernel::TParameterHandler<IMemoryBuffer*> op_signalStream; + Kernel::TParameterHandler<IMemoryBuffer*> op_stimulationStream; + Kernel::TParameterHandler<IMemoryBuffer*> op_channelLocalisationStream; + Kernel::TParameterHandler<IMemoryBuffer*> op_channelUnitsStream; + + using T::m_codec; + using T::m_boxAlgorithm; + using T::m_iBuffer; + + bool initializeImpl() + { + m_codec = &m_boxAlgorithm->getAlgorithmManager().getAlgorithm( + m_boxAlgorithm->getAlgorithmManager().createAlgorithm(OVP_GD_ClassId_Algorithm_AcquisitionDecoder)); + m_codec->initialize(); + + m_iBuffer.initialize(m_codec->getInputParameter(OVP_GD_Algorithm_AcquisitionDecoder_InputParameterId_MemoryBufferToDecode)); + + op_bufferDuration.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_AcquisitionDecoder_OutputParameterId_BufferDuration)); + op_experimentInfoStream.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_AcquisitionDecoder_OutputParameterId_ExperimentInfoStream)); + op_signalStream.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_AcquisitionDecoder_OutputParameterId_SignalStream)); + op_stimulationStream.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_AcquisitionDecoder_OutputParameterId_StimulationStream)); + op_channelLocalisationStream.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_AcquisitionDecoder_OutputParameterId_ChannelLocalisationStream)); + op_channelUnitsStream.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_AcquisitionDecoder_OutputParameterId_ChannelUnitsStream)); + + return true; + } + +public: + + using T::initialize; + + bool uninitialize() + { + if (m_boxAlgorithm == nullptr || m_codec == nullptr) { return false; } + + op_channelUnitsStream.uninitialize(); + op_channelLocalisationStream.uninitialize(); + op_stimulationStream.uninitialize(); + op_signalStream.uninitialize(); + op_experimentInfoStream.uninitialize(); + op_bufferDuration.uninitialize(); + + m_iBuffer.uninitialize(); + m_codec->uninitialize(); + m_boxAlgorithm->getAlgorithmManager().releaseAlgorithm(*m_codec); + m_boxAlgorithm = NULL; + + return true; + } + + Kernel::TParameterHandler<uint64_t>& getBufferDuration() { return op_bufferDuration; } + Kernel::TParameterHandler<IMemoryBuffer*>& getExperimentInfoStream() { return op_experimentInfoStream; } + Kernel::TParameterHandler<IMemoryBuffer*>& getSignalStream() { return op_signalStream; } + Kernel::TParameterHandler<IMemoryBuffer*>& getStimulationStream() { return op_stimulationStream; } + Kernel::TParameterHandler<IMemoryBuffer*>& getChannelLocalisationStream() { return op_channelLocalisationStream; } + Kernel::TParameterHandler<IMemoryBuffer*>& getChannelUnitsStream() { return op_channelUnitsStream; } + + virtual bool isHeaderReceived() { return m_codec->isOutputTriggerActive(OVP_GD_Algorithm_AcquisitionDecoder_OutputTriggerId_ReceivedHeader); } + virtual bool isBufferReceived() { return m_codec->isOutputTriggerActive(OVP_GD_Algorithm_AcquisitionDecoder_OutputTriggerId_ReceivedBuffer); } + virtual bool isEndReceived() { return m_codec->isOutputTriggerActive(OVP_GD_Algorithm_AcquisitionDecoder_OutputTriggerId_ReceivedEnd); } +}; + +template <class T> +class TAcquisitionDecoder : public TAcquisitionDecoderLocal<TStreamedMatrixDecoderLocal<TDecoder<T>>> +{ + using TAcquisitionDecoderLocal<TStreamedMatrixDecoderLocal<TDecoder<T>>>::m_boxAlgorithm; + +public: + using TAcquisitionDecoderLocal<TStreamedMatrixDecoderLocal<TDecoder<T>>>::uninitialize; + + TAcquisitionDecoder() { } + + explicit TAcquisitionDecoder(T& boxAlgorithm) { - template <class T> - class TAcquisitionDecoderLocal : public T - { - protected: - - Kernel::TParameterHandler<uint64_t> op_bufferDuration; - Kernel::TParameterHandler<IMemoryBuffer*> op_experimentInfoStream; - Kernel::TParameterHandler<IMemoryBuffer*> op_signalStream; - Kernel::TParameterHandler<IMemoryBuffer*> op_stimulationStream; - Kernel::TParameterHandler<IMemoryBuffer*> op_channelLocalisationStream; - Kernel::TParameterHandler<IMemoryBuffer*> op_channelUnitsStream; - - using T::m_codec; - using T::m_boxAlgorithm; - using T::m_iBuffer; - - bool initializeImpl() - { - m_codec = &m_boxAlgorithm->getAlgorithmManager().getAlgorithm( - m_boxAlgorithm->getAlgorithmManager().createAlgorithm(OVP_GD_ClassId_Algorithm_AcquisitionDecoder)); - m_codec->initialize(); - - m_iBuffer.initialize(m_codec->getInputParameter(OVP_GD_Algorithm_AcquisitionDecoder_InputParameterId_MemoryBufferToDecode)); - - op_bufferDuration.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_AcquisitionDecoder_OutputParameterId_BufferDuration)); - op_experimentInfoStream.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_AcquisitionDecoder_OutputParameterId_ExperimentInfoStream)); - op_signalStream.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_AcquisitionDecoder_OutputParameterId_SignalStream)); - op_stimulationStream.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_AcquisitionDecoder_OutputParameterId_StimulationStream)); - op_channelLocalisationStream.initialize( - m_codec->getOutputParameter(OVP_GD_Algorithm_AcquisitionDecoder_OutputParameterId_ChannelLocalisationStream)); - op_channelUnitsStream.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_AcquisitionDecoder_OutputParameterId_ChannelUnitsStream)); - - return true; - } - - public: - - using T::initialize; - - bool uninitialize() - { - if (m_boxAlgorithm == nullptr || m_codec == nullptr) { return false; } - - op_channelUnitsStream.uninitialize(); - op_channelLocalisationStream.uninitialize(); - op_stimulationStream.uninitialize(); - op_signalStream.uninitialize(); - op_experimentInfoStream.uninitialize(); - op_bufferDuration.uninitialize(); - - m_iBuffer.uninitialize(); - m_codec->uninitialize(); - m_boxAlgorithm->getAlgorithmManager().releaseAlgorithm(*m_codec); - m_boxAlgorithm = NULL; - - return true; - } - - Kernel::TParameterHandler<uint64_t>& getBufferDuration() { return op_bufferDuration; } - Kernel::TParameterHandler<IMemoryBuffer*>& getExperimentInfoStream() { return op_experimentInfoStream; } - Kernel::TParameterHandler<IMemoryBuffer*>& getSignalStream() { return op_signalStream; } - Kernel::TParameterHandler<IMemoryBuffer*>& getStimulationStream() { return op_stimulationStream; } - Kernel::TParameterHandler<IMemoryBuffer*>& getChannelLocalisationStream() { return op_channelLocalisationStream; } - Kernel::TParameterHandler<IMemoryBuffer*>& getChannelUnitsStream() { return op_channelUnitsStream; } - - virtual bool isHeaderReceived() { return m_codec->isOutputTriggerActive(OVP_GD_Algorithm_AcquisitionDecoder_OutputTriggerId_ReceivedHeader); } - virtual bool isBufferReceived() { return m_codec->isOutputTriggerActive(OVP_GD_Algorithm_AcquisitionDecoder_OutputTriggerId_ReceivedBuffer); } - virtual bool isEndReceived() { return m_codec->isOutputTriggerActive(OVP_GD_Algorithm_AcquisitionDecoder_OutputTriggerId_ReceivedEnd); } - }; - - template <class T> - class TAcquisitionDecoder : public TAcquisitionDecoderLocal<TStreamedMatrixDecoderLocal<TDecoder<T>>> - { - using TAcquisitionDecoderLocal<TStreamedMatrixDecoderLocal<TDecoder<T>>>::m_boxAlgorithm; - - public: - using TAcquisitionDecoderLocal<TStreamedMatrixDecoderLocal<TDecoder<T>>>::uninitialize; - - TAcquisitionDecoder() { } - - explicit TAcquisitionDecoder(T& boxAlgorithm) - { - m_boxAlgorithm = NULL; - this->initialize(boxAlgorithm); - } - - virtual ~TAcquisitionDecoder() { this->uninitialize(); } - }; - } // namespace Toolkit + m_boxAlgorithm = NULL; + this->initialize(boxAlgorithm); + } + + virtual ~TAcquisitionDecoder() { this->uninitialize(); } +}; +} // namespace Toolkit } // namespace OpenViBE #endif // TARGET_HAS_ThirdPartyOpenViBEPluginsGlobalDefines diff --git a/toolkit/include/toolkit/codecs/decoders/ovtkTChannelLocalisationDecoder.h b/toolkit/include/toolkit/codecs/decoders/ovtkTChannelLocalisationDecoder.h index 3738c180d7a82b0d8f0a12764cb9588780e1d6db..9732978dd2accb0fdbe7113c96681000f8ad64e3 100644 --- a/toolkit/include/toolkit/codecs/decoders/ovtkTChannelLocalisationDecoder.h +++ b/toolkit/include/toolkit/codecs/decoders/ovtkTChannelLocalisationDecoder.h @@ -4,84 +4,74 @@ #include "ovtkTStreamedMatrixDecoder.h" -namespace OpenViBE +namespace OpenViBE { +namespace Toolkit { +template <class T> +class TChannelLocalisationDecoderLocal : public T { - namespace Toolkit +protected: + + Kernel::TParameterHandler<bool> m_oDynamic; + + using T::m_codec; + using T::m_boxAlgorithm; + using T::m_iBuffer; + using T::m_oMatrix; + + bool initializeImpl() { - template <class T> - class TChannelLocalisationDecoderLocal : public T - { - protected: - - Kernel::TParameterHandler<bool> m_oDynamic; - - using T::m_codec; - using T::m_boxAlgorithm; - using T::m_iBuffer; - using T::m_oMatrix; - - bool initializeImpl() - { - m_codec = &m_boxAlgorithm->getAlgorithmManager().getAlgorithm( - m_boxAlgorithm->getAlgorithmManager().createAlgorithm(OVP_GD_ClassId_Algorithm_ChannelLocalisationDecoder)); - m_codec->initialize(); - m_iBuffer.initialize(m_codec->getInputParameter(OVP_GD_Algorithm_ChannelLocalisationDecoder_InputParameterId_MemoryBufferToDecode)); - m_oMatrix.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_ChannelLocalisationDecoder_OutputParameterId_Matrix)); - m_oDynamic.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_ChannelLocalisationDecoder_OutputParameterId_Dynamic)); - - return true; - } - - public: - using T::initialize; - - bool uninitialize() - { - if (m_boxAlgorithm == nullptr || m_codec == nullptr) { return false; } - - m_oDynamic.uninitialize(); - m_oMatrix.uninitialize(); - m_iBuffer.uninitialize(); - m_codec->uninitialize(); - m_boxAlgorithm->getAlgorithmManager().releaseAlgorithm(*m_codec); - m_boxAlgorithm = NULL; - - return true; - } - - Kernel::TParameterHandler<bool>& getOutputDynamic() { return m_oDynamic; } - - virtual bool isHeaderReceived() - { - return m_codec->isOutputTriggerActive(OVP_GD_Algorithm_ChannelLocalisationDecoder_OutputTriggerId_ReceivedHeader); - } - - virtual bool isBufferReceived() - { - return m_codec->isOutputTriggerActive(OVP_GD_Algorithm_ChannelLocalisationDecoder_OutputTriggerId_ReceivedBuffer); - } - - virtual bool isEndReceived() { return m_codec->isOutputTriggerActive(OVP_GD_Algorithm_ChannelLocalisationDecoder_OutputTriggerId_ReceivedEnd); } - }; - - template <class T> - class TChannelLocalisationDecoder : public TChannelLocalisationDecoderLocal<TStreamedMatrixDecoderLocal<TDecoder<T>>> - { - using TChannelLocalisationDecoderLocal<TStreamedMatrixDecoderLocal<TDecoder<T>>>::m_boxAlgorithm; - public: - using TChannelLocalisationDecoderLocal<TStreamedMatrixDecoderLocal<TDecoder<T>>>::uninitialize; - - TChannelLocalisationDecoder() { } - - TChannelLocalisationDecoder(T& boxAlgorithm, size_t index) - { - m_boxAlgorithm = NULL; - this->initialize(boxAlgorithm, index); - } - - virtual ~TChannelLocalisationDecoder() { this->uninitialize(); } - }; - } // namespace Toolkit + m_codec = &m_boxAlgorithm->getAlgorithmManager().getAlgorithm( + m_boxAlgorithm->getAlgorithmManager().createAlgorithm(OVP_GD_ClassId_Algorithm_ChannelLocalisationDecoder)); + m_codec->initialize(); + m_iBuffer.initialize(m_codec->getInputParameter(OVP_GD_Algorithm_ChannelLocalisationDecoder_InputParameterId_MemoryBufferToDecode)); + m_oMatrix.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_ChannelLocalisationDecoder_OutputParameterId_Matrix)); + m_oDynamic.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_ChannelLocalisationDecoder_OutputParameterId_Dynamic)); + + return true; + } + +public: + using T::initialize; + + bool uninitialize() + { + if (m_boxAlgorithm == nullptr || m_codec == nullptr) { return false; } + + m_oDynamic.uninitialize(); + m_oMatrix.uninitialize(); + m_iBuffer.uninitialize(); + m_codec->uninitialize(); + m_boxAlgorithm->getAlgorithmManager().releaseAlgorithm(*m_codec); + m_boxAlgorithm = NULL; + + return true; + } + + Kernel::TParameterHandler<bool>& getOutputDynamic() { return m_oDynamic; } + + virtual bool isHeaderReceived() { return m_codec->isOutputTriggerActive(OVP_GD_Algorithm_ChannelLocalisationDecoder_OutputTriggerId_ReceivedHeader); } + virtual bool isBufferReceived() { return m_codec->isOutputTriggerActive(OVP_GD_Algorithm_ChannelLocalisationDecoder_OutputTriggerId_ReceivedBuffer); } + virtual bool isEndReceived() { return m_codec->isOutputTriggerActive(OVP_GD_Algorithm_ChannelLocalisationDecoder_OutputTriggerId_ReceivedEnd); } +}; + +template <class T> +class TChannelLocalisationDecoder : public TChannelLocalisationDecoderLocal<TStreamedMatrixDecoderLocal<TDecoder<T>>> +{ + using TChannelLocalisationDecoderLocal<TStreamedMatrixDecoderLocal<TDecoder<T>>>::m_boxAlgorithm; +public: + using TChannelLocalisationDecoderLocal<TStreamedMatrixDecoderLocal<TDecoder<T>>>::uninitialize; + + TChannelLocalisationDecoder() { } + + TChannelLocalisationDecoder(T& boxAlgorithm, size_t index) + { + m_boxAlgorithm = NULL; + this->initialize(boxAlgorithm, index); + } + + virtual ~TChannelLocalisationDecoder() { this->uninitialize(); } +}; +} // namespace Toolkit } // namespace OpenViBE #endif // TARGET_HAS_ThirdPartyOpenViBEPluginsGlobalDefines diff --git a/toolkit/include/toolkit/codecs/decoders/ovtkTChannelUnitsDecoder.h b/toolkit/include/toolkit/codecs/decoders/ovtkTChannelUnitsDecoder.h index 6372025ad22fdd63d0194fd41734c6ce2e1552a5..2d78db7f7ab5ce7e252750eaa9b0ef83cff1130a 100644 --- a/toolkit/include/toolkit/codecs/decoders/ovtkTChannelUnitsDecoder.h +++ b/toolkit/include/toolkit/codecs/decoders/ovtkTChannelUnitsDecoder.h @@ -4,77 +4,75 @@ #include "ovtkTStreamedMatrixDecoder.h" -namespace OpenViBE +namespace OpenViBE { +namespace Toolkit { +template <class T> +class TChannelUnitsDecoderLocal : public T { - namespace Toolkit +protected: + + Kernel::TParameterHandler<bool> m_oDynamic; + + using T::m_codec; + using T::m_boxAlgorithm; + using T::m_iBuffer; + using T::m_oMatrix; + + bool initializeImpl() + { + m_codec = &m_boxAlgorithm->getAlgorithmManager().getAlgorithm( + m_boxAlgorithm->getAlgorithmManager().createAlgorithm(OVP_GD_ClassId_Algorithm_ChannelUnitsDecoder)); + m_codec->initialize(); + m_iBuffer.initialize(m_codec->getInputParameter(OVP_GD_Algorithm_ChannelUnitsDecoder_InputParameterId_MemoryBufferToDecode)); + m_oMatrix.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_ChannelUnitsDecoder_OutputParameterId_Matrix)); + m_oDynamic.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_ChannelUnitsDecoder_OutputParameterId_Dynamic)); + + return true; + } + +public: + using T::initialize; + + bool uninitialize() + { + if (m_boxAlgorithm == nullptr || m_codec == nullptr) { return false; } + + m_oDynamic.uninitialize(); + m_oMatrix.uninitialize(); + + m_iBuffer.uninitialize(); + m_codec->uninitialize(); + m_boxAlgorithm->getAlgorithmManager().releaseAlgorithm(*m_codec); + m_boxAlgorithm = NULL; + + return true; + } + + Kernel::TParameterHandler<bool>& getOutputDynamic() { return m_oDynamic; } + + virtual bool isHeaderReceived() { return m_codec->isOutputTriggerActive(OVP_GD_Algorithm_ChannelUnitsDecoder_OutputTriggerId_ReceivedHeader); } + virtual bool isBufferReceived() { return m_codec->isOutputTriggerActive(OVP_GD_Algorithm_ChannelUnitsDecoder_OutputTriggerId_ReceivedBuffer); } + virtual bool isEndReceived() { return m_codec->isOutputTriggerActive(OVP_GD_Algorithm_ChannelUnitsDecoder_OutputTriggerId_ReceivedEnd); } +}; + +template <class T> +class TChannelUnitsDecoder : public TChannelUnitsDecoderLocal<TStreamedMatrixDecoderLocal<TDecoder<T>>> +{ + using TChannelUnitsDecoderLocal<TStreamedMatrixDecoderLocal<TDecoder<T>>>::m_boxAlgorithm; +public: + using TChannelUnitsDecoderLocal<TStreamedMatrixDecoderLocal<TDecoder<T>>>::uninitialize; + + TChannelUnitsDecoder() { } + + TChannelUnitsDecoder(T& boxAlgorithm, size_t index) { - template <class T> - class TChannelUnitsDecoderLocal : public T - { - protected: - - Kernel::TParameterHandler<bool> m_oDynamic; - - using T::m_codec; - using T::m_boxAlgorithm; - using T::m_iBuffer; - using T::m_oMatrix; - - bool initializeImpl() - { - m_codec = &m_boxAlgorithm->getAlgorithmManager().getAlgorithm( - m_boxAlgorithm->getAlgorithmManager().createAlgorithm(OVP_GD_ClassId_Algorithm_ChannelUnitsDecoder)); - m_codec->initialize(); - m_iBuffer.initialize(m_codec->getInputParameter(OVP_GD_Algorithm_ChannelUnitsDecoder_InputParameterId_MemoryBufferToDecode)); - m_oMatrix.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_ChannelUnitsDecoder_OutputParameterId_Matrix)); - m_oDynamic.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_ChannelUnitsDecoder_OutputParameterId_Dynamic)); - - return true; - } - - public: - using T::initialize; - - bool uninitialize() - { - if (m_boxAlgorithm == nullptr || m_codec == nullptr) { return false; } - - m_oDynamic.uninitialize(); - m_oMatrix.uninitialize(); - - m_iBuffer.uninitialize(); - m_codec->uninitialize(); - m_boxAlgorithm->getAlgorithmManager().releaseAlgorithm(*m_codec); - m_boxAlgorithm = NULL; - - return true; - } - - Kernel::TParameterHandler<bool>& getOutputDynamic() { return m_oDynamic; } - - virtual bool isHeaderReceived() { return m_codec->isOutputTriggerActive(OVP_GD_Algorithm_ChannelUnitsDecoder_OutputTriggerId_ReceivedHeader); } - virtual bool isBufferReceived() { return m_codec->isOutputTriggerActive(OVP_GD_Algorithm_ChannelUnitsDecoder_OutputTriggerId_ReceivedBuffer); } - virtual bool isEndReceived() { return m_codec->isOutputTriggerActive(OVP_GD_Algorithm_ChannelUnitsDecoder_OutputTriggerId_ReceivedEnd); } - }; - - template <class T> - class TChannelUnitsDecoder : public TChannelUnitsDecoderLocal<TStreamedMatrixDecoderLocal<TDecoder<T>>> - { - using TChannelUnitsDecoderLocal<TStreamedMatrixDecoderLocal<TDecoder<T>>>::m_boxAlgorithm; - public: - using TChannelUnitsDecoderLocal<TStreamedMatrixDecoderLocal<TDecoder<T>>>::uninitialize; - - TChannelUnitsDecoder() { } - - TChannelUnitsDecoder(T& boxAlgorithm, size_t index) - { - m_boxAlgorithm = NULL; - this->initialize(boxAlgorithm, index); - } - - virtual ~TChannelUnitsDecoder() { this->uninitialize(); } - }; - } // namespace Toolkit + m_boxAlgorithm = NULL; + this->initialize(boxAlgorithm, index); + } + + virtual ~TChannelUnitsDecoder() { this->uninitialize(); } +}; +} // namespace Toolkit } // namespace OpenViBE #endif // TARGET_HAS_ThirdPartyOpenViBEPluginsGlobalDefines diff --git a/toolkit/include/toolkit/codecs/decoders/ovtkTDecoder.h b/toolkit/include/toolkit/codecs/decoders/ovtkTDecoder.h index 22e8964f6c41f1d1c83422b3fbae7fb813dec7f4..c82c8c6c5a46b2095f3b913c5d497b96ba67c977 100644 --- a/toolkit/include/toolkit/codecs/decoders/ovtkTDecoder.h +++ b/toolkit/include/toolkit/codecs/decoders/ovtkTDecoder.h @@ -6,78 +6,75 @@ #include "../ovtkTCodec.h" -namespace OpenViBE +namespace OpenViBE { +namespace Toolkit { +template <class T> +class TDecoderLocal : public T { - namespace Toolkit - { - template <class T> - class TDecoderLocal : public T - { - protected: - - Kernel::TParameterHandler<const IMemoryBuffer*> m_iBuffer; - +protected: - using T::m_codec; - using T::m_boxAlgorithm; - using T::m_connectorIdx; + Kernel::TParameterHandler<const IMemoryBuffer*> m_iBuffer; - virtual void setInputChunk(const IMemoryBuffer* pInputChunkMemoryBuffer) { m_iBuffer = pInputChunkMemoryBuffer; } - virtual Kernel::TParameterHandler<const IMemoryBuffer*>& getInputMemoryBuffer() { return m_iBuffer; } + using T::m_codec; + using T::m_boxAlgorithm; + using T::m_connectorIdx; - virtual bool isOutputTriggerActive(const CIdentifier oTrigger) { return m_codec->isOutputTriggerActive(oTrigger); } + virtual void setInputChunk(const IMemoryBuffer* pInputChunkMemoryBuffer) { m_iBuffer = pInputChunkMemoryBuffer; } - virtual bool process(const CIdentifier& oTrigger) { return m_codec->process(oTrigger); } + virtual Kernel::TParameterHandler<const IMemoryBuffer*>& getInputMemoryBuffer() { return m_iBuffer; } - virtual bool process() { return m_codec->process(); } + virtual bool isOutputTriggerActive(const CIdentifier oTrigger) { return m_codec->isOutputTriggerActive(oTrigger); } - public: - // We make visible the initialize methods of the superclass (should be TCodec), in the same scope (public) - using T::initialize; + virtual bool process(const CIdentifier& oTrigger) { return m_codec->process(oTrigger); } + virtual bool process() { return m_codec->process(); } - /* - This public function handles every aspects of the decoding process: - - fill the input memory buffer with a chunk - - decode it (specific for each decoder) - - mark input as deprecated - */ - virtual bool decode(const size_t chunkIdx, const bool markInputAsDeprecated = true) - { - this->setInputChunk(m_boxAlgorithm->getDynamicBoxContext().getInputChunk(m_connectorIdx, chunkIdx)); - if (! m_codec->process()) return false; - if (markInputAsDeprecated) m_boxAlgorithm->getDynamicBoxContext().markInputAsDeprecated(m_connectorIdx, chunkIdx); - return true; - } +public: + // We make visible the initialize methods of the superclass (should be TCodec), in the same scope (public) + using T::initialize; - // We explicitly delete the decode function taking two integers as parameters - // in order to raise errors in plugins using the older API + /* + This public function handles every aspects of the decoding process: + - fill the input memory buffer with a chunk + - decode it (specific for each decoder) + - mark input as deprecated + */ + virtual bool decode(const size_t chunkIdx, const bool markInputAsDeprecated = true) + { + this->setInputChunk(m_boxAlgorithm->getDynamicBoxContext().getInputChunk(m_connectorIdx, chunkIdx)); + if (! m_codec->process()) return false; + if (markInputAsDeprecated) m_boxAlgorithm->getDynamicBoxContext().markInputAsDeprecated(m_connectorIdx, chunkIdx); + return true; + } + + // We explicitly delete the decode function taking two integers as parameters + // in order to raise errors in plugins using the older API #ifndef TARGET_OS_MacOS // Current clang has a bug which fails to link these - virtual bool decode(int, int) = delete; - virtual bool decode(size_t, size_t) = delete; + virtual bool decode(int, int) = delete; + virtual bool decode(size_t, size_t) = delete; #endif - // The functions that need to be specified by the decoders (specific Trigger ID) - virtual bool isHeaderReceived() = 0; - virtual bool isBufferReceived() = 0; - virtual bool isEndReceived() = 0; - }; - - /* - This class provides an access to the superclass TDecoder. - Use case : iterating over a vector of TDecoder, calling decode() each time. - You don't need to know which type of decoder is in the vector. - */ - template <class T> - class TDecoder : public TDecoderLocal<TCodec<T>> - { - public: - virtual ~TDecoder() { } - protected: - // constructor is protected, ensuring we can't instanciate a TDecoder - TDecoder() { } - }; - } // namespace Toolkit + // The functions that need to be specified by the decoders (specific Trigger ID) + virtual bool isHeaderReceived() = 0; + virtual bool isBufferReceived() = 0; + virtual bool isEndReceived() = 0; +}; + +/* +This class provides an access to the superclass TDecoder. +Use case : iterating over a vector of TDecoder, calling decode() each time. +You don't need to know which type of decoder is in the vector. +*/ +template <class T> +class TDecoder : public TDecoderLocal<TCodec<T>> +{ +public: + virtual ~TDecoder() { } +protected: + // constructor is protected, ensuring we can't instanciate a TDecoder + TDecoder() { } +}; +} // namespace Toolkit } // namespace OpenViBE #endif // TARGET_HAS_ThirdPartyOpenViBEPluginsGlobalDefines diff --git a/toolkit/include/toolkit/codecs/decoders/ovtkTExperimentInfoDecoder.h b/toolkit/include/toolkit/codecs/decoders/ovtkTExperimentInfoDecoder.h index 9747b5860fec6a2ac73311c3d4474732821332ad..4b81b9e8c55e2474ce6311215ced8233baf293a9 100644 --- a/toolkit/include/toolkit/codecs/decoders/ovtkTExperimentInfoDecoder.h +++ b/toolkit/include/toolkit/codecs/decoders/ovtkTExperimentInfoDecoder.h @@ -6,117 +6,115 @@ #include "ovtkTDecoder.h" -namespace OpenViBE +namespace OpenViBE { +namespace Toolkit { +template <class T> +class TExperimentInfoDecoderLocal : public T { - namespace Toolkit +protected: + + Kernel::TParameterHandler<uint64_t> m_experimentID; + Kernel::TParameterHandler<CString*> m_experimentDate; + + Kernel::TParameterHandler<uint64_t> m_subjectID; + Kernel::TParameterHandler<CString*> m_subjectName; + Kernel::TParameterHandler<uint64_t> m_subjectAge; + Kernel::TParameterHandler<uint64_t> m_subjectGender; + + Kernel::TParameterHandler<uint64_t> m_laboratoryID; + Kernel::TParameterHandler<CString*> m_laboratoryName; + Kernel::TParameterHandler<uint64_t> m_technicianID; + Kernel::TParameterHandler<CString*> m_technicianName; + + using T::m_codec; + using T::m_boxAlgorithm; + using T::m_iBuffer; + + bool initializeImpl() { - template <class T> - class TExperimentInfoDecoderLocal : public T - { - protected: - - Kernel::TParameterHandler<uint64_t> m_experimentID; - Kernel::TParameterHandler<CString*> m_experimentDate; - - Kernel::TParameterHandler<uint64_t> m_subjectID; - Kernel::TParameterHandler<CString*> m_subjectName; - Kernel::TParameterHandler<uint64_t> m_subjectAge; - Kernel::TParameterHandler<uint64_t> m_subjectGender; - - Kernel::TParameterHandler<uint64_t> m_laboratoryID; - Kernel::TParameterHandler<CString*> m_laboratoryName; - Kernel::TParameterHandler<uint64_t> m_technicianID; - Kernel::TParameterHandler<CString*> m_technicianName; - - using T::m_codec; - using T::m_boxAlgorithm; - using T::m_iBuffer; - - bool initializeImpl() - { - m_codec = &m_boxAlgorithm->getAlgorithmManager().getAlgorithm( - m_boxAlgorithm->getAlgorithmManager().createAlgorithm(OVP_GD_ClassId_Algorithm_ExperimentInfoDecoder)); - m_codec->initialize(); - - m_iBuffer.initialize(m_codec->getInputParameter(OVP_GD_Algorithm_ExperimentInfoDecoder_InputParameterId_MemoryBufferToDecode)); - - m_experimentID.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_ExperimentInfoDecoder_OutputParameterId_ExperimentID)); - m_experimentDate.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_ExperimentInfoDecoder_OutputParameterId_ExperimentDate)); - - m_subjectID.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_ExperimentInfoDecoder_OutputParameterId_SubjectID)); - m_subjectName.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_ExperimentInfoDecoder_OutputParameterId_SubjectName)); - m_subjectAge.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_ExperimentInfoDecoder_OutputParameterId_SubjectAge)); - m_subjectGender.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_ExperimentInfoDecoder_OutputParameterId_SubjectGender)); - - m_laboratoryID.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_ExperimentInfoDecoder_OutputParameterId_LaboratoryID)); - m_laboratoryName.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_ExperimentInfoDecoder_OutputParameterId_LaboratoryName)); - m_technicianID.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_ExperimentInfoDecoder_OutputParameterId_TechnicianID)); - m_technicianName.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_ExperimentInfoDecoder_OutputParameterId_TechnicianName)); - - return true; - } - - public: - using T::initialize; - - bool uninitialize() - { - if (m_boxAlgorithm == nullptr || m_codec == nullptr) { return false; } - - m_experimentID.uninitialize(); - m_experimentDate.uninitialize(); - m_subjectID.uninitialize(); - m_subjectName.uninitialize(); - m_subjectAge.uninitialize(); - m_subjectGender.uninitialize(); - m_laboratoryID.uninitialize(); - m_laboratoryName.uninitialize(); - m_technicianID.uninitialize(); - m_technicianName.uninitialize(); - - m_iBuffer.uninitialize(); - m_codec->uninitialize(); - m_boxAlgorithm->getAlgorithmManager().releaseAlgorithm(*m_codec); - m_boxAlgorithm = NULL; - - return true; - } - - Kernel::TParameterHandler<uint64_t>& getOutputExperimentID() { return m_experimentID; } - Kernel::TParameterHandler<CString*>& getOutputExperimentDate() { return m_experimentDate; } - Kernel::TParameterHandler<uint64_t>& getOutputSubjectID() { return m_subjectID; } - Kernel::TParameterHandler<CString*>& getOutputSubjectName() { return m_subjectName; } - Kernel::TParameterHandler<uint64_t>& getOutputSubjectAge() { return m_subjectAge; } - Kernel::TParameterHandler<uint64_t>& getOutputSubjectGender() { return m_subjectGender; } - Kernel::TParameterHandler<uint64_t>& getOutputLaboratoryID() { return m_laboratoryID; } - Kernel::TParameterHandler<CString*>& getOutputLaboratoryName() { return m_laboratoryName; } - Kernel::TParameterHandler<uint64_t>& getOutputTechnicianID() { return m_technicianID; } - Kernel::TParameterHandler<CString*>& getOutputTechnicianName() { return m_technicianName; } - - virtual bool isHeaderReceived() { return m_codec->isOutputTriggerActive(OVP_GD_Algorithm_ExperimentInfoDecoder_OutputTriggerId_ReceivedHeader); } - virtual bool isBufferReceived() { return m_codec->isOutputTriggerActive(OVP_GD_Algorithm_ExperimentInfoDecoder_OutputTriggerId_ReceivedBuffer); } - virtual bool isEndReceived() { return m_codec->isOutputTriggerActive(OVP_GD_Algorithm_ExperimentInfoDecoder_OutputTriggerId_ReceivedEnd); } - }; - - template <class T> - class TExperimentInfoDecoder : public TExperimentInfoDecoderLocal<TDecoder<T>> - { - using TExperimentInfoDecoderLocal<TDecoder<T>>::m_boxAlgorithm; - - public: - using TExperimentInfoDecoderLocal<TDecoder<T>>::uninitialize; - - TExperimentInfoDecoder() { } - - TExperimentInfoDecoder(T& boxAlgorithm, size_t index) - { - m_boxAlgorithm = NULL; - this->initialize(boxAlgorithm, index); - } - - virtual ~TExperimentInfoDecoder() { this->uninitialize(); } - }; - } // namespace Toolkit + m_codec = &m_boxAlgorithm->getAlgorithmManager().getAlgorithm( + m_boxAlgorithm->getAlgorithmManager().createAlgorithm(OVP_GD_ClassId_Algorithm_ExperimentInfoDecoder)); + m_codec->initialize(); + + m_iBuffer.initialize(m_codec->getInputParameter(OVP_GD_Algorithm_ExperimentInfoDecoder_InputParameterId_MemoryBufferToDecode)); + + m_experimentID.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_ExperimentInfoDecoder_OutputParameterId_ExperimentID)); + m_experimentDate.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_ExperimentInfoDecoder_OutputParameterId_ExperimentDate)); + + m_subjectID.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_ExperimentInfoDecoder_OutputParameterId_SubjectID)); + m_subjectName.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_ExperimentInfoDecoder_OutputParameterId_SubjectName)); + m_subjectAge.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_ExperimentInfoDecoder_OutputParameterId_SubjectAge)); + m_subjectGender.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_ExperimentInfoDecoder_OutputParameterId_SubjectGender)); + + m_laboratoryID.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_ExperimentInfoDecoder_OutputParameterId_LaboratoryID)); + m_laboratoryName.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_ExperimentInfoDecoder_OutputParameterId_LaboratoryName)); + m_technicianID.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_ExperimentInfoDecoder_OutputParameterId_TechnicianID)); + m_technicianName.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_ExperimentInfoDecoder_OutputParameterId_TechnicianName)); + + return true; + } + +public: + using T::initialize; + + bool uninitialize() + { + if (m_boxAlgorithm == nullptr || m_codec == nullptr) { return false; } + + m_experimentID.uninitialize(); + m_experimentDate.uninitialize(); + m_subjectID.uninitialize(); + m_subjectName.uninitialize(); + m_subjectAge.uninitialize(); + m_subjectGender.uninitialize(); + m_laboratoryID.uninitialize(); + m_laboratoryName.uninitialize(); + m_technicianID.uninitialize(); + m_technicianName.uninitialize(); + + m_iBuffer.uninitialize(); + m_codec->uninitialize(); + m_boxAlgorithm->getAlgorithmManager().releaseAlgorithm(*m_codec); + m_boxAlgorithm = NULL; + + return true; + } + + Kernel::TParameterHandler<uint64_t>& getOutputExperimentID() { return m_experimentID; } + Kernel::TParameterHandler<CString*>& getOutputExperimentDate() { return m_experimentDate; } + Kernel::TParameterHandler<uint64_t>& getOutputSubjectID() { return m_subjectID; } + Kernel::TParameterHandler<CString*>& getOutputSubjectName() { return m_subjectName; } + Kernel::TParameterHandler<uint64_t>& getOutputSubjectAge() { return m_subjectAge; } + Kernel::TParameterHandler<uint64_t>& getOutputSubjectGender() { return m_subjectGender; } + Kernel::TParameterHandler<uint64_t>& getOutputLaboratoryID() { return m_laboratoryID; } + Kernel::TParameterHandler<CString*>& getOutputLaboratoryName() { return m_laboratoryName; } + Kernel::TParameterHandler<uint64_t>& getOutputTechnicianID() { return m_technicianID; } + Kernel::TParameterHandler<CString*>& getOutputTechnicianName() { return m_technicianName; } + + virtual bool isHeaderReceived() { return m_codec->isOutputTriggerActive(OVP_GD_Algorithm_ExperimentInfoDecoder_OutputTriggerId_ReceivedHeader); } + virtual bool isBufferReceived() { return m_codec->isOutputTriggerActive(OVP_GD_Algorithm_ExperimentInfoDecoder_OutputTriggerId_ReceivedBuffer); } + virtual bool isEndReceived() { return m_codec->isOutputTriggerActive(OVP_GD_Algorithm_ExperimentInfoDecoder_OutputTriggerId_ReceivedEnd); } +}; + +template <class T> +class TExperimentInfoDecoder : public TExperimentInfoDecoderLocal<TDecoder<T>> +{ + using TExperimentInfoDecoderLocal<TDecoder<T>>::m_boxAlgorithm; + +public: + using TExperimentInfoDecoderLocal<TDecoder<T>>::uninitialize; + + TExperimentInfoDecoder() { } + + TExperimentInfoDecoder(T& boxAlgorithm, size_t index) + { + m_boxAlgorithm = NULL; + this->initialize(boxAlgorithm, index); + } + + virtual ~TExperimentInfoDecoder() { this->uninitialize(); } +}; +} // namespace Toolkit } // namespace OpenViBE #endif // TARGET_HAS_ThirdPartyOpenViBEPluginsGlobalDefines diff --git a/toolkit/include/toolkit/codecs/decoders/ovtkTFeatureVectorDecoder.h b/toolkit/include/toolkit/codecs/decoders/ovtkTFeatureVectorDecoder.h index 81cf295e4c7b77732a539039d1a853e3e975dfb4..074b6abeb782747936e74ceef033eec2b1697d61 100644 --- a/toolkit/include/toolkit/codecs/decoders/ovtkTFeatureVectorDecoder.h +++ b/toolkit/include/toolkit/codecs/decoders/ovtkTFeatureVectorDecoder.h @@ -6,58 +6,56 @@ #include "ovtkTStreamedMatrixDecoder.h" -namespace OpenViBE +namespace OpenViBE { +namespace Toolkit { +template <class T> +class TFeatureVectorDecoderLocal : public T { - namespace Toolkit +protected: + + using T::m_codec; + using T::m_boxAlgorithm; + using T::m_iBuffer; + using T::m_oMatrix; + + bool initializeImpl() { - template <class T> - class TFeatureVectorDecoderLocal : public T - { - protected: - - using T::m_codec; - using T::m_boxAlgorithm; - using T::m_iBuffer; - using T::m_oMatrix; - - bool initializeImpl() - { - m_codec = &m_boxAlgorithm->getAlgorithmManager().getAlgorithm( - m_boxAlgorithm->getAlgorithmManager().createAlgorithm(OVP_GD_ClassId_Algorithm_FeatureVectorDecoder)); - m_codec->initialize(); - m_iBuffer.initialize(m_codec->getInputParameter(OVP_GD_Algorithm_FeatureVectorDecoder_InputParameterId_MemoryBufferToDecode)); - m_oMatrix.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_FeatureVectorDecoder_OutputParameterId_Matrix)); - - return true; - } - - public: - using T::initialize; - using T::uninitialize; - - virtual bool isHeaderReceived() { return m_codec->isOutputTriggerActive(OVP_GD_Algorithm_FeatureVectorDecoder_OutputTriggerId_ReceivedHeader); } - virtual bool isBufferReceived() { return m_codec->isOutputTriggerActive(OVP_GD_Algorithm_FeatureVectorDecoder_OutputTriggerId_ReceivedBuffer); } - virtual bool isEndReceived() { return m_codec->isOutputTriggerActive(OVP_GD_Algorithm_FeatureVectorDecoder_OutputTriggerId_ReceivedEnd); } - }; - - template <class T> - class TFeatureVectorDecoder : public TFeatureVectorDecoderLocal<TStreamedMatrixDecoderLocal<TDecoder<T>>> - { - using TFeatureVectorDecoderLocal<TStreamedMatrixDecoderLocal<TDecoder<T>>>::m_boxAlgorithm; - public: - using TFeatureVectorDecoderLocal<TStreamedMatrixDecoderLocal<TDecoder<T>>>::uninitialize; - - TFeatureVectorDecoder() { } - - TFeatureVectorDecoder(T& boxAlgorithm, size_t index) - { - m_boxAlgorithm = NULL; - this->initialize(boxAlgorithm, index); - } - - virtual ~TFeatureVectorDecoder() { this->uninitialize(); } - }; - } // namespace Toolkit + m_codec = &m_boxAlgorithm->getAlgorithmManager().getAlgorithm( + m_boxAlgorithm->getAlgorithmManager().createAlgorithm(OVP_GD_ClassId_Algorithm_FeatureVectorDecoder)); + m_codec->initialize(); + m_iBuffer.initialize(m_codec->getInputParameter(OVP_GD_Algorithm_FeatureVectorDecoder_InputParameterId_MemoryBufferToDecode)); + m_oMatrix.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_FeatureVectorDecoder_OutputParameterId_Matrix)); + + return true; + } + +public: + using T::initialize; + using T::uninitialize; + + virtual bool isHeaderReceived() { return m_codec->isOutputTriggerActive(OVP_GD_Algorithm_FeatureVectorDecoder_OutputTriggerId_ReceivedHeader); } + virtual bool isBufferReceived() { return m_codec->isOutputTriggerActive(OVP_GD_Algorithm_FeatureVectorDecoder_OutputTriggerId_ReceivedBuffer); } + virtual bool isEndReceived() { return m_codec->isOutputTriggerActive(OVP_GD_Algorithm_FeatureVectorDecoder_OutputTriggerId_ReceivedEnd); } +}; + +template <class T> +class TFeatureVectorDecoder : public TFeatureVectorDecoderLocal<TStreamedMatrixDecoderLocal<TDecoder<T>>> +{ + using TFeatureVectorDecoderLocal<TStreamedMatrixDecoderLocal<TDecoder<T>>>::m_boxAlgorithm; +public: + using TFeatureVectorDecoderLocal<TStreamedMatrixDecoderLocal<TDecoder<T>>>::uninitialize; + + TFeatureVectorDecoder() { } + + TFeatureVectorDecoder(T& boxAlgorithm, size_t index) + { + m_boxAlgorithm = NULL; + this->initialize(boxAlgorithm, index); + } + + virtual ~TFeatureVectorDecoder() { this->uninitialize(); } +}; +} // namespace Toolkit } // namespace OpenViBE #endif // TARGET_HAS_ThirdPartyOpenViBEPluginsGlobalDefines diff --git a/toolkit/include/toolkit/codecs/decoders/ovtkTSignalDecoder.h b/toolkit/include/toolkit/codecs/decoders/ovtkTSignalDecoder.h index fd91c1341d5caa8feba9ad0cce3da98288162b9c..3df5df8dc94ffafe999cd7519b5e22ba6996970f 100644 --- a/toolkit/include/toolkit/codecs/decoders/ovtkTSignalDecoder.h +++ b/toolkit/include/toolkit/codecs/decoders/ovtkTSignalDecoder.h @@ -6,76 +6,74 @@ #include "ovtkTStreamedMatrixDecoder.h" -namespace OpenViBE +namespace OpenViBE { +namespace Toolkit { +template <class T> +class TSignalDecoderLocal : public T { - namespace Toolkit +protected: + + Kernel::TParameterHandler<uint64_t> m_sampling; + + using T::m_codec; + using T::m_boxAlgorithm; + using T::m_iBuffer; + using T::m_oMatrix; + + bool initializeImpl() { - template <class T> - class TSignalDecoderLocal : public T - { - protected: - - Kernel::TParameterHandler<uint64_t> m_sampling; - - using T::m_codec; - using T::m_boxAlgorithm; - using T::m_iBuffer; - using T::m_oMatrix; - - bool initializeImpl() - { - m_codec = &m_boxAlgorithm->getAlgorithmManager().getAlgorithm( - m_boxAlgorithm->getAlgorithmManager().createAlgorithm(OVP_GD_ClassId_Algorithm_SignalDecoder)); - m_codec->initialize(); - m_sampling.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_SignalDecoder_OutputParameterId_Sampling)); - m_oMatrix.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_SignalDecoder_OutputParameterId_Matrix)); - m_iBuffer.initialize(m_codec->getInputParameter(OVP_GD_Algorithm_SignalDecoder_InputParameterId_MemoryBufferToDecode)); - - return true; - } - - public: - using T::initialize; - - bool uninitialize() - { - if (m_boxAlgorithm == nullptr || m_codec == nullptr) { return false; } - - m_sampling.uninitialize(); - m_oMatrix.uninitialize(); - m_iBuffer.uninitialize(); - m_codec->uninitialize(); - m_boxAlgorithm->getAlgorithmManager().releaseAlgorithm(*m_codec); - m_boxAlgorithm = NULL; - - return true; - } - - Kernel::TParameterHandler<uint64_t>& getOutputSamplingRate() { return m_sampling; } - - virtual bool isHeaderReceived() { return m_codec->isOutputTriggerActive(OVP_GD_Algorithm_SignalDecoder_OutputTriggerId_ReceivedHeader); } - virtual bool isBufferReceived() { return m_codec->isOutputTriggerActive(OVP_GD_Algorithm_SignalDecoder_OutputTriggerId_ReceivedBuffer); } - virtual bool isEndReceived() { return m_codec->isOutputTriggerActive(OVP_GD_Algorithm_SignalDecoder_OutputTriggerId_ReceivedEnd); } - }; - - template <class T> - class TSignalDecoder : public TSignalDecoderLocal<TStreamedMatrixDecoderLocal<TDecoder<T>>> - { - using TSignalDecoderLocal<TStreamedMatrixDecoderLocal<TDecoder<T>>>::m_boxAlgorithm; - public: - using TSignalDecoderLocal<TStreamedMatrixDecoderLocal<TDecoder<T>>>::uninitialize; - - TSignalDecoder() { } - - TSignalDecoder(T& boxAlgorithm, size_t index) - { - m_boxAlgorithm = NULL; - this->initialize(boxAlgorithm, index); - } - - virtual ~TSignalDecoder() { this->uninitialize(); } - }; - } // namespace Toolkit + m_codec = &m_boxAlgorithm->getAlgorithmManager().getAlgorithm( + m_boxAlgorithm->getAlgorithmManager().createAlgorithm(OVP_GD_ClassId_Algorithm_SignalDecoder)); + m_codec->initialize(); + m_sampling.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_SignalDecoder_OutputParameterId_Sampling)); + m_oMatrix.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_SignalDecoder_OutputParameterId_Matrix)); + m_iBuffer.initialize(m_codec->getInputParameter(OVP_GD_Algorithm_SignalDecoder_InputParameterId_MemoryBufferToDecode)); + + return true; + } + +public: + using T::initialize; + + bool uninitialize() + { + if (m_boxAlgorithm == nullptr || m_codec == nullptr) { return false; } + + m_sampling.uninitialize(); + m_oMatrix.uninitialize(); + m_iBuffer.uninitialize(); + m_codec->uninitialize(); + m_boxAlgorithm->getAlgorithmManager().releaseAlgorithm(*m_codec); + m_boxAlgorithm = NULL; + + return true; + } + + Kernel::TParameterHandler<uint64_t>& getOutputSamplingRate() { return m_sampling; } + + virtual bool isHeaderReceived() { return m_codec->isOutputTriggerActive(OVP_GD_Algorithm_SignalDecoder_OutputTriggerId_ReceivedHeader); } + virtual bool isBufferReceived() { return m_codec->isOutputTriggerActive(OVP_GD_Algorithm_SignalDecoder_OutputTriggerId_ReceivedBuffer); } + virtual bool isEndReceived() { return m_codec->isOutputTriggerActive(OVP_GD_Algorithm_SignalDecoder_OutputTriggerId_ReceivedEnd); } +}; + +template <class T> +class TSignalDecoder : public TSignalDecoderLocal<TStreamedMatrixDecoderLocal<TDecoder<T>>> +{ + using TSignalDecoderLocal<TStreamedMatrixDecoderLocal<TDecoder<T>>>::m_boxAlgorithm; +public: + using TSignalDecoderLocal<TStreamedMatrixDecoderLocal<TDecoder<T>>>::uninitialize; + + TSignalDecoder() { } + + TSignalDecoder(T& boxAlgorithm, size_t index) + { + m_boxAlgorithm = NULL; + this->initialize(boxAlgorithm, index); + } + + virtual ~TSignalDecoder() { this->uninitialize(); } +}; +} // namespace Toolkit } // namespace OpenViBE #endif // TARGET_HAS_ThirdPartyOpenViBEPluginsGlobalDefines diff --git a/toolkit/include/toolkit/codecs/decoders/ovtkTSpectrumDecoder.h b/toolkit/include/toolkit/codecs/decoders/ovtkTSpectrumDecoder.h index b8ab9ada45dd0088917ec697b657cea9048b7842..b9b1e87feefb36b64a4808a891fff359e20d2b7f 100755 --- a/toolkit/include/toolkit/codecs/decoders/ovtkTSpectrumDecoder.h +++ b/toolkit/include/toolkit/codecs/decoders/ovtkTSpectrumDecoder.h @@ -6,81 +6,79 @@ #include "ovtkTStreamedMatrixDecoder.h" -namespace OpenViBE +namespace OpenViBE { +namespace Toolkit { +template <class T> +class TSpectrumDecoderLocal : public T { - namespace Toolkit +protected: + + Kernel::TParameterHandler<IMatrix*> m_frequencyAbscissa; + Kernel::TParameterHandler<uint64_t> m_sampling; + + + using T::m_codec; + using T::m_boxAlgorithm; + using T::m_iBuffer; + using T::m_oMatrix; + + bool initializeImpl() + { + m_codec = &m_boxAlgorithm->getAlgorithmManager().getAlgorithm( + m_boxAlgorithm->getAlgorithmManager().createAlgorithm(OVP_GD_ClassId_Algorithm_SpectrumDecoder)); + m_codec->initialize(); + m_oMatrix.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_SpectrumDecoder_OutputParameterId_Matrix)); + m_frequencyAbscissa.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_SpectrumDecoder_OutputParameterId_FrequencyAbscissa)); + m_sampling.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_SpectrumDecoder_OutputParameterId_Sampling)); + m_iBuffer.initialize(m_codec->getInputParameter(OVP_GD_Algorithm_SpectrumDecoder_InputParameterId_MemoryBufferToDecode)); + + return true; + } + +public: + using T::initialize; + + bool uninitialize() + { + if (m_boxAlgorithm == nullptr || m_codec == nullptr) { return false; } + + m_oMatrix.uninitialize(); + m_frequencyAbscissa.uninitialize(); + m_sampling.uninitialize(); + m_iBuffer.uninitialize(); + m_codec->uninitialize(); + m_boxAlgorithm->getAlgorithmManager().releaseAlgorithm(*m_codec); + m_boxAlgorithm = NULL; + + return true; + } + + Kernel::TParameterHandler<uint64_t>& getOutputSamplingRate() { return m_sampling; } + Kernel::TParameterHandler<IMatrix*>& getOutputFrequencyAbscissa() { return m_frequencyAbscissa; } + + virtual bool isHeaderReceived() { return m_codec->isOutputTriggerActive(OVP_GD_Algorithm_SpectrumDecoder_OutputTriggerId_ReceivedHeader); } + virtual bool isBufferReceived() { return m_codec->isOutputTriggerActive(OVP_GD_Algorithm_SpectrumDecoder_OutputTriggerId_ReceivedBuffer); } + virtual bool isEndReceived() { return m_codec->isOutputTriggerActive(OVP_GD_Algorithm_SpectrumDecoder_OutputTriggerId_ReceivedEnd); } +}; + +template <class T> +class TSpectrumDecoder : public TSpectrumDecoderLocal<TStreamedMatrixDecoderLocal<TDecoder<T>>> +{ + using TSpectrumDecoderLocal<TStreamedMatrixDecoderLocal<TDecoder<T>>>::m_boxAlgorithm; +public: + using TSpectrumDecoderLocal<TStreamedMatrixDecoderLocal<TDecoder<T>>>::uninitialize; + + TSpectrumDecoder() { } + + TSpectrumDecoder(T& boxAlgorithm, size_t index) { - template <class T> - class TSpectrumDecoderLocal : public T - { - protected: - - Kernel::TParameterHandler<IMatrix*> m_frequencyAbscissa; - Kernel::TParameterHandler<uint64_t> m_sampling; - - - using T::m_codec; - using T::m_boxAlgorithm; - using T::m_iBuffer; - using T::m_oMatrix; - - bool initializeImpl() - { - m_codec = &m_boxAlgorithm->getAlgorithmManager().getAlgorithm( - m_boxAlgorithm->getAlgorithmManager().createAlgorithm(OVP_GD_ClassId_Algorithm_SpectrumDecoder)); - m_codec->initialize(); - m_oMatrix.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_SpectrumDecoder_OutputParameterId_Matrix)); - m_frequencyAbscissa.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_SpectrumDecoder_OutputParameterId_FrequencyAbscissa)); - m_sampling.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_SpectrumDecoder_OutputParameterId_Sampling)); - m_iBuffer.initialize(m_codec->getInputParameter(OVP_GD_Algorithm_SpectrumDecoder_InputParameterId_MemoryBufferToDecode)); - - return true; - } - - public: - using T::initialize; - - bool uninitialize() - { - if (m_boxAlgorithm == nullptr || m_codec == nullptr) { return false; } - - m_oMatrix.uninitialize(); - m_frequencyAbscissa.uninitialize(); - m_sampling.uninitialize(); - m_iBuffer.uninitialize(); - m_codec->uninitialize(); - m_boxAlgorithm->getAlgorithmManager().releaseAlgorithm(*m_codec); - m_boxAlgorithm = NULL; - - return true; - } - - Kernel::TParameterHandler<uint64_t>& getOutputSamplingRate() { return m_sampling; } - Kernel::TParameterHandler<IMatrix*>& getOutputFrequencyAbscissa() { return m_frequencyAbscissa; } - - virtual bool isHeaderReceived() { return m_codec->isOutputTriggerActive(OVP_GD_Algorithm_SpectrumDecoder_OutputTriggerId_ReceivedHeader); } - virtual bool isBufferReceived() { return m_codec->isOutputTriggerActive(OVP_GD_Algorithm_SpectrumDecoder_OutputTriggerId_ReceivedBuffer); } - virtual bool isEndReceived() { return m_codec->isOutputTriggerActive(OVP_GD_Algorithm_SpectrumDecoder_OutputTriggerId_ReceivedEnd); } - }; - - template <class T> - class TSpectrumDecoder : public TSpectrumDecoderLocal<TStreamedMatrixDecoderLocal<TDecoder<T>>> - { - using TSpectrumDecoderLocal<TStreamedMatrixDecoderLocal<TDecoder<T>>>::m_boxAlgorithm; - public: - using TSpectrumDecoderLocal<TStreamedMatrixDecoderLocal<TDecoder<T>>>::uninitialize; - - TSpectrumDecoder() { } - - TSpectrumDecoder(T& boxAlgorithm, size_t index) - { - m_boxAlgorithm = NULL; - this->initialize(boxAlgorithm, index); - } - - virtual ~TSpectrumDecoder() { this->uninitialize(); } - }; - } // namespace Toolkit + m_boxAlgorithm = NULL; + this->initialize(boxAlgorithm, index); + } + + virtual ~TSpectrumDecoder() { this->uninitialize(); } +}; +} // namespace Toolkit } // namespace OpenViBE #endif // TARGET_HAS_ThirdPartyOpenViBEPluginsGlobalDefines diff --git a/toolkit/include/toolkit/codecs/decoders/ovtkTStimulationStreamDecoder.h b/toolkit/include/toolkit/codecs/decoders/ovtkTStimulationStreamDecoder.h index 69c38c6bad630caef139526ce18fb81b83cfc0f7..0e2a8ca3062bfb898108a8a03ad8161d31337025 100644 --- a/toolkit/include/toolkit/codecs/decoders/ovtkTStimulationStreamDecoder.h +++ b/toolkit/include/toolkit/codecs/decoders/ovtkTStimulationStreamDecoder.h @@ -6,73 +6,71 @@ #include "ovtkTDecoder.h" -namespace OpenViBE +namespace OpenViBE { +namespace Toolkit { +template <class T> +class TStimulationDecoderLocal : public T { - namespace Toolkit +protected: + + Kernel::TParameterHandler<IStimulationSet*> m_oStimulationSet; + + using T::m_codec; + using T::m_boxAlgorithm; + using T::m_iBuffer; + + bool initializeImpl() { - template <class T> - class TStimulationDecoderLocal : public T - { - protected: - - Kernel::TParameterHandler<IStimulationSet*> m_oStimulationSet; - - using T::m_codec; - using T::m_boxAlgorithm; - using T::m_iBuffer; - - bool initializeImpl() - { - m_codec = &m_boxAlgorithm->getAlgorithmManager().getAlgorithm( - m_boxAlgorithm->getAlgorithmManager().createAlgorithm(OVP_GD_ClassId_Algorithm_StimulationDecoder)); - m_codec->initialize(); - m_oStimulationSet.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_StimulationDecoder_OutputParameterId_StimulationSet)); - m_iBuffer.initialize(m_codec->getInputParameter(OVP_GD_Algorithm_StimulationDecoder_InputParameterId_MemoryBufferToDecode)); - - return true; - } - - public: - using T::initialize; - - bool uninitialize() - { - if (m_boxAlgorithm == nullptr || m_codec == nullptr) { return false; } - - m_oStimulationSet.uninitialize(); - m_iBuffer.uninitialize(); - m_codec->uninitialize(); - m_boxAlgorithm->getAlgorithmManager().releaseAlgorithm(*m_codec); - m_boxAlgorithm = NULL; - - return true; - } - - Kernel::TParameterHandler<IStimulationSet*>& getOutputStimulationSet() { return m_oStimulationSet; } - - virtual bool isHeaderReceived() { return m_codec->isOutputTriggerActive(OVP_GD_Algorithm_StimulationDecoder_OutputTriggerId_ReceivedHeader); } - virtual bool isBufferReceived() { return m_codec->isOutputTriggerActive(OVP_GD_Algorithm_StimulationDecoder_OutputTriggerId_ReceivedBuffer); } - virtual bool isEndReceived() { return m_codec->isOutputTriggerActive(OVP_GD_Algorithm_StimulationDecoder_OutputTriggerId_ReceivedEnd); } - }; - - template <class T> - class TStimulationDecoder : public TStimulationDecoderLocal<TDecoder<T>> - { - using TStimulationDecoderLocal<TDecoder<T>>::m_boxAlgorithm; - public: - using TStimulationDecoderLocal<TDecoder<T>>::uninitialize; - - TStimulationDecoder() { } - - TStimulationDecoder(T& boxAlgorithm, size_t index) - { - m_boxAlgorithm = NULL; - this->initialize(boxAlgorithm, index); - } - - virtual ~TStimulationDecoder() { this->uninitialize(); } - }; - } // namespace Toolkit + m_codec = &m_boxAlgorithm->getAlgorithmManager().getAlgorithm( + m_boxAlgorithm->getAlgorithmManager().createAlgorithm(OVP_GD_ClassId_Algorithm_StimulationDecoder)); + m_codec->initialize(); + m_oStimulationSet.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_StimulationDecoder_OutputParameterId_StimulationSet)); + m_iBuffer.initialize(m_codec->getInputParameter(OVP_GD_Algorithm_StimulationDecoder_InputParameterId_MemoryBufferToDecode)); + + return true; + } + +public: + using T::initialize; + + bool uninitialize() + { + if (m_boxAlgorithm == nullptr || m_codec == nullptr) { return false; } + + m_oStimulationSet.uninitialize(); + m_iBuffer.uninitialize(); + m_codec->uninitialize(); + m_boxAlgorithm->getAlgorithmManager().releaseAlgorithm(*m_codec); + m_boxAlgorithm = NULL; + + return true; + } + + Kernel::TParameterHandler<IStimulationSet*>& getOutputStimulationSet() { return m_oStimulationSet; } + + virtual bool isHeaderReceived() { return m_codec->isOutputTriggerActive(OVP_GD_Algorithm_StimulationDecoder_OutputTriggerId_ReceivedHeader); } + virtual bool isBufferReceived() { return m_codec->isOutputTriggerActive(OVP_GD_Algorithm_StimulationDecoder_OutputTriggerId_ReceivedBuffer); } + virtual bool isEndReceived() { return m_codec->isOutputTriggerActive(OVP_GD_Algorithm_StimulationDecoder_OutputTriggerId_ReceivedEnd); } +}; + +template <class T> +class TStimulationDecoder : public TStimulationDecoderLocal<TDecoder<T>> +{ + using TStimulationDecoderLocal<TDecoder<T>>::m_boxAlgorithm; +public: + using TStimulationDecoderLocal<TDecoder<T>>::uninitialize; + + TStimulationDecoder() { } + + TStimulationDecoder(T& boxAlgorithm, size_t index) + { + m_boxAlgorithm = NULL; + this->initialize(boxAlgorithm, index); + } + + virtual ~TStimulationDecoder() { this->uninitialize(); } +}; +} // namespace Toolkit } // namespace OpenViBE #endif // TARGET_HAS_ThirdPartyOpenViBEPluginsGlobalDefines diff --git a/toolkit/include/toolkit/codecs/decoders/ovtkTStreamStructureDecoder.h b/toolkit/include/toolkit/codecs/decoders/ovtkTStreamStructureDecoder.h index fa4dba4d2e45a514f09130adb0761549ce0a522e..0bebdaf2a51639a0be75a0b724adcb16dc678e00 100644 --- a/toolkit/include/toolkit/codecs/decoders/ovtkTStreamStructureDecoder.h +++ b/toolkit/include/toolkit/codecs/decoders/ovtkTStreamStructureDecoder.h @@ -4,67 +4,65 @@ #include "../../ovtk_base.h" -namespace OpenViBE +namespace OpenViBE { +namespace Toolkit { +template <class T> +class TStreamStructureDecoderLocal : public T { - namespace Toolkit +protected: + + using T::m_codec; + using T::m_boxAlgorithm; + using T::m_iBuffer; + + bool initializeImpl() + { + m_codec = &m_boxAlgorithm->getAlgorithmManager().getAlgorithm( + m_boxAlgorithm->getAlgorithmManager().createAlgorithm(OVP_GD_ClassId_Algorithm_StreamStructureDecoder)); + m_codec->initialize(); + m_iBuffer.initialize(m_codec->getInputParameter(OVP_GD_Algorithm_StreamStructureDecoder_InputParameterId_MemoryBufferToDecode)); + + return true; + } + +public: + using T::initialize; + + bool uninitialize() { - template <class T> - class TStreamStructureDecoderLocal : public T - { - protected: - - using T::m_codec; - using T::m_boxAlgorithm; - using T::m_iBuffer; - - bool initializeImpl() - { - m_codec = &m_boxAlgorithm->getAlgorithmManager().getAlgorithm( - m_boxAlgorithm->getAlgorithmManager().createAlgorithm(OVP_GD_ClassId_Algorithm_StreamStructureDecoder)); - m_codec->initialize(); - m_iBuffer.initialize(m_codec->getInputParameter(OVP_GD_Algorithm_StreamStructureDecoder_InputParameterId_MemoryBufferToDecode)); - - return true; - } - - public: - using T::initialize; - - bool uninitialize() - { - if (m_boxAlgorithm == nullptr || m_codec == nullptr) { return false; } - - m_iBuffer.uninitialize(); - m_codec->uninitialize(); - m_boxAlgorithm->getAlgorithmManager().releaseAlgorithm(*m_codec); - m_boxAlgorithm = NULL; - - return true; - } - - virtual bool isHeaderReceived() { return m_codec->isOutputTriggerActive(OVP_GD_Algorithm_StreamStructureDecoder_OutputTriggerId_ReceivedHeader); } - virtual bool isBufferReceived() { return m_codec->isOutputTriggerActive(OVP_GD_Algorithm_StreamStructureDecoder_OutputTriggerId_ReceivedBuffer); } - virtual bool isEndReceived() { return m_codec->isOutputTriggerActive(OVP_GD_Algorithm_StreamStructureDecoder_OutputTriggerId_ReceivedEnd); } - }; - - template <class T> - class TStreamStructureDecoder : public TStreamStructureDecoderLocal<TDecoder<T>> - { - using TStreamStructureDecoderLocal<TDecoder<T>>::m_boxAlgorithm; - public: - using TStreamStructureDecoderLocal<TDecoder<T>>::uninitialize; - - TStreamStructureDecoder() { } - - TStreamStructureDecoder(T& boxAlgorithm, size_t index) - { - m_boxAlgorithm = NULL; - this->initialize(boxAlgorithm, index); - } - - virtual ~TStreamStructureDecoder() { this->uninitialize(); } - }; - } // namespace Toolkit + if (m_boxAlgorithm == nullptr || m_codec == nullptr) { return false; } + + m_iBuffer.uninitialize(); + m_codec->uninitialize(); + m_boxAlgorithm->getAlgorithmManager().releaseAlgorithm(*m_codec); + m_boxAlgorithm = NULL; + + return true; + } + + virtual bool isHeaderReceived() { return m_codec->isOutputTriggerActive(OVP_GD_Algorithm_StreamStructureDecoder_OutputTriggerId_ReceivedHeader); } + virtual bool isBufferReceived() { return m_codec->isOutputTriggerActive(OVP_GD_Algorithm_StreamStructureDecoder_OutputTriggerId_ReceivedBuffer); } + virtual bool isEndReceived() { return m_codec->isOutputTriggerActive(OVP_GD_Algorithm_StreamStructureDecoder_OutputTriggerId_ReceivedEnd); } +}; + +template <class T> +class TStreamStructureDecoder : public TStreamStructureDecoderLocal<TDecoder<T>> +{ + using TStreamStructureDecoderLocal<TDecoder<T>>::m_boxAlgorithm; +public: + using TStreamStructureDecoderLocal<TDecoder<T>>::uninitialize; + + TStreamStructureDecoder() { } + + TStreamStructureDecoder(T& boxAlgorithm, size_t index) + { + m_boxAlgorithm = NULL; + this->initialize(boxAlgorithm, index); + } + + virtual ~TStreamStructureDecoder() { this->uninitialize(); } +}; +} // namespace Toolkit } // namespace OpenViBE #endif // TARGET_HAS_ThirdPartyOpenViBEPluginsGlobalDefines diff --git a/toolkit/include/toolkit/codecs/decoders/ovtkTStreamedMatrixDecoder.h b/toolkit/include/toolkit/codecs/decoders/ovtkTStreamedMatrixDecoder.h index 2f879974c9c87cda7579fe8e00bf7625f0d1aa22..30bf95e7d3a797ff8c9732b74c0422bbe79dbde4 100644 --- a/toolkit/include/toolkit/codecs/decoders/ovtkTStreamedMatrixDecoder.h +++ b/toolkit/include/toolkit/codecs/decoders/ovtkTStreamedMatrixDecoder.h @@ -6,73 +6,71 @@ #include "ovtkTDecoder.h" -namespace OpenViBE +namespace OpenViBE { +namespace Toolkit { +template <class T> +class TStreamedMatrixDecoderLocal : public T { - namespace Toolkit +protected: + + Kernel::TParameterHandler<IMatrix*> m_oMatrix; + + using T::m_codec; + using T::m_boxAlgorithm; + using T::m_iBuffer; + + virtual bool initializeImpl() { - template <class T> - class TStreamedMatrixDecoderLocal : public T - { - protected: - - Kernel::TParameterHandler<IMatrix*> m_oMatrix; - - using T::m_codec; - using T::m_boxAlgorithm; - using T::m_iBuffer; - - virtual bool initializeImpl() - { - m_codec = &m_boxAlgorithm->getAlgorithmManager().getAlgorithm( - m_boxAlgorithm->getAlgorithmManager().createAlgorithm(OVP_GD_ClassId_Algorithm_StreamedMatrixDecoder)); - m_codec->initialize(); - m_iBuffer.initialize(m_codec->getInputParameter(OVP_GD_Algorithm_StreamedMatrixDecoder_InputParameterId_MemoryBufferToDecode)); - m_oMatrix.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_StreamedMatrixDecoder_OutputParameterId_Matrix)); - - return true; - } - - public: - using T::initialize; - - virtual bool uninitialize() - { - if (m_boxAlgorithm == nullptr || m_codec == nullptr) { return false; } - - m_oMatrix.uninitialize(); - m_iBuffer.uninitialize(); - m_codec->uninitialize(); - m_boxAlgorithm->getAlgorithmManager().releaseAlgorithm(*m_codec); - m_boxAlgorithm = NULL; - - return true; - } - - virtual Kernel::TParameterHandler<IMatrix*>& getOutputMatrix() { return m_oMatrix; } - - virtual bool isHeaderReceived() { return m_codec->isOutputTriggerActive(OVP_GD_Algorithm_StreamedMatrixDecoder_OutputTriggerId_ReceivedHeader); } - virtual bool isBufferReceived() { return m_codec->isOutputTriggerActive(OVP_GD_Algorithm_StreamedMatrixDecoder_OutputTriggerId_ReceivedBuffer); } - virtual bool isEndReceived() { return m_codec->isOutputTriggerActive(OVP_GD_Algorithm_StreamedMatrixDecoder_OutputTriggerId_ReceivedEnd); } - }; - - template <class T> - class TStreamedMatrixDecoder : public TStreamedMatrixDecoderLocal<TDecoder<T>> - { - using TStreamedMatrixDecoderLocal<TDecoder<T>>::m_boxAlgorithm; - public: - using TStreamedMatrixDecoderLocal<TDecoder<T>>::uninitialize; - - TStreamedMatrixDecoder() { } - - TStreamedMatrixDecoder(T& boxAlgorithm, size_t index) - { - m_boxAlgorithm = NULL; - this->initialize(boxAlgorithm, index); - } - - virtual ~TStreamedMatrixDecoder() { this->uninitialize(); } - }; - } // namespace Toolkit + m_codec = &m_boxAlgorithm->getAlgorithmManager().getAlgorithm( + m_boxAlgorithm->getAlgorithmManager().createAlgorithm(OVP_GD_ClassId_Algorithm_StreamedMatrixDecoder)); + m_codec->initialize(); + m_iBuffer.initialize(m_codec->getInputParameter(OVP_GD_Algorithm_StreamedMatrixDecoder_InputParameterId_MemoryBufferToDecode)); + m_oMatrix.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_StreamedMatrixDecoder_OutputParameterId_Matrix)); + + return true; + } + +public: + using T::initialize; + + virtual bool uninitialize() + { + if (m_boxAlgorithm == nullptr || m_codec == nullptr) { return false; } + + m_oMatrix.uninitialize(); + m_iBuffer.uninitialize(); + m_codec->uninitialize(); + m_boxAlgorithm->getAlgorithmManager().releaseAlgorithm(*m_codec); + m_boxAlgorithm = NULL; + + return true; + } + + virtual Kernel::TParameterHandler<IMatrix*>& getOutputMatrix() { return m_oMatrix; } + + virtual bool isHeaderReceived() { return m_codec->isOutputTriggerActive(OVP_GD_Algorithm_StreamedMatrixDecoder_OutputTriggerId_ReceivedHeader); } + virtual bool isBufferReceived() { return m_codec->isOutputTriggerActive(OVP_GD_Algorithm_StreamedMatrixDecoder_OutputTriggerId_ReceivedBuffer); } + virtual bool isEndReceived() { return m_codec->isOutputTriggerActive(OVP_GD_Algorithm_StreamedMatrixDecoder_OutputTriggerId_ReceivedEnd); } +}; + +template <class T> +class TStreamedMatrixDecoder : public TStreamedMatrixDecoderLocal<TDecoder<T>> +{ + using TStreamedMatrixDecoderLocal<TDecoder<T>>::m_boxAlgorithm; +public: + using TStreamedMatrixDecoderLocal<TDecoder<T>>::uninitialize; + + TStreamedMatrixDecoder() { } + + TStreamedMatrixDecoder(T& boxAlgorithm, size_t index) + { + m_boxAlgorithm = NULL; + this->initialize(boxAlgorithm, index); + } + + virtual ~TStreamedMatrixDecoder() { this->uninitialize(); } +}; +} // namespace Toolkit } // namespace OpenViBE #endif // TARGET_HAS_ThirdPartyOpenViBEPluginsGlobalDefines diff --git a/toolkit/include/toolkit/codecs/encoders/ovtkTChannelLocalisationEncoder.h b/toolkit/include/toolkit/codecs/encoders/ovtkTChannelLocalisationEncoder.h index 57e75afb32245ac8df490f0c05706b25e0e95617..2fdd0cc2061574c7d14784033c8c5bf6eb824f7f 100644 --- a/toolkit/include/toolkit/codecs/encoders/ovtkTChannelLocalisationEncoder.h +++ b/toolkit/include/toolkit/codecs/encoders/ovtkTChannelLocalisationEncoder.h @@ -4,77 +4,75 @@ #include "ovtkTStreamedMatrixEncoder.h" -namespace OpenViBE +namespace OpenViBE { +namespace Toolkit { +template <class T> +class TChannelLocalisationEncoderLocal : public T { - namespace Toolkit +protected: + + Kernel::TParameterHandler<bool> m_iDynamic; + + using T::m_codec; + using T::m_boxAlgorithm; + using T::m_buffer; + using T::m_iMatrix; + + bool initializeImpl() { - template <class T> - class TChannelLocalisationEncoderLocal : public T - { - protected: - - Kernel::TParameterHandler<bool> m_iDynamic; - - using T::m_codec; - using T::m_boxAlgorithm; - using T::m_buffer; - using T::m_iMatrix; - - bool initializeImpl() - { - m_codec = &m_boxAlgorithm->getAlgorithmManager().getAlgorithm( - m_boxAlgorithm->getAlgorithmManager().createAlgorithm(OVP_GD_ClassId_Algorithm_ChannelLocalisationEncoder)); - m_codec->initialize(); - m_iMatrix.initialize(m_codec->getInputParameter(OVP_GD_Algorithm_ChannelLocalisationEncoder_InputParameterId_Matrix)); - m_iDynamic.initialize(m_codec->getInputParameter(OVP_GD_Algorithm_ChannelLocalisationEncoder_InputParameterId_Dynamic)); - m_buffer.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_ChannelLocalisationEncoder_OutputParameterId_EncodedMemoryBuffer)); - - return true; - } - - public: - using T::initialize; - - bool uninitialize() - { - if (m_boxAlgorithm == nullptr || m_codec == nullptr) { return false; } - - m_iMatrix.uninitialize(); - m_iDynamic.uninitialize(); - m_buffer.uninitialize(); - m_codec->uninitialize(); - m_boxAlgorithm->getAlgorithmManager().releaseAlgorithm(*m_codec); - m_boxAlgorithm = NULL; - - return true; - } - - Kernel::TParameterHandler<bool>& getInputDynamic() { return m_iDynamic; } - - protected: - bool encodeHeaderImpl() { return m_codec->process(OVP_GD_Algorithm_ChannelLocalisationEncoder_InputTriggerId_EncodeHeader); } - bool encodeBufferImpl() { return m_codec->process(OVP_GD_Algorithm_ChannelLocalisationEncoder_InputTriggerId_EncodeBuffer); } - bool encodeEndImpl() { return m_codec->process(OVP_GD_Algorithm_ChannelLocalisationEncoder_InputTriggerId_EncodeEnd); } - }; - - template <class T> - class TChannelLocalisationEncoder : public TChannelLocalisationEncoderLocal<TStreamedMatrixEncoderLocal<TEncoder<T>>> - { - using TChannelLocalisationEncoderLocal<TStreamedMatrixEncoderLocal<TEncoder<T>>>::m_boxAlgorithm; - public: - using TChannelLocalisationEncoderLocal<TStreamedMatrixEncoderLocal<TEncoder<T>>>::uninitialize; - - TChannelLocalisationEncoder() { } - - TChannelLocalisationEncoder(T& boxAlgorithm, size_t index) - { - m_boxAlgorithm = NULL; - this->initialize(boxAlgorithm, index); - } - - virtual ~TChannelLocalisationEncoder() { this->uninitialize(); } - }; - } // namespace Toolkit + m_codec = &m_boxAlgorithm->getAlgorithmManager().getAlgorithm( + m_boxAlgorithm->getAlgorithmManager().createAlgorithm(OVP_GD_ClassId_Algorithm_ChannelLocalisationEncoder)); + m_codec->initialize(); + m_iMatrix.initialize(m_codec->getInputParameter(OVP_GD_Algorithm_ChannelLocalisationEncoder_InputParameterId_Matrix)); + m_iDynamic.initialize(m_codec->getInputParameter(OVP_GD_Algorithm_ChannelLocalisationEncoder_InputParameterId_Dynamic)); + m_buffer.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_ChannelLocalisationEncoder_OutputParameterId_EncodedMemoryBuffer)); + + return true; + } + +public: + using T::initialize; + + bool uninitialize() + { + if (m_boxAlgorithm == nullptr || m_codec == nullptr) { return false; } + + m_iMatrix.uninitialize(); + m_iDynamic.uninitialize(); + m_buffer.uninitialize(); + m_codec->uninitialize(); + m_boxAlgorithm->getAlgorithmManager().releaseAlgorithm(*m_codec); + m_boxAlgorithm = NULL; + + return true; + } + + Kernel::TParameterHandler<bool>& getInputDynamic() { return m_iDynamic; } + +protected: + bool encodeHeaderImpl() { return m_codec->process(OVP_GD_Algorithm_ChannelLocalisationEncoder_InputTriggerId_EncodeHeader); } + bool encodeBufferImpl() { return m_codec->process(OVP_GD_Algorithm_ChannelLocalisationEncoder_InputTriggerId_EncodeBuffer); } + bool encodeEndImpl() { return m_codec->process(OVP_GD_Algorithm_ChannelLocalisationEncoder_InputTriggerId_EncodeEnd); } +}; + +template <class T> +class TChannelLocalisationEncoder : public TChannelLocalisationEncoderLocal<TStreamedMatrixEncoderLocal<TEncoder<T>>> +{ + using TChannelLocalisationEncoderLocal<TStreamedMatrixEncoderLocal<TEncoder<T>>>::m_boxAlgorithm; +public: + using TChannelLocalisationEncoderLocal<TStreamedMatrixEncoderLocal<TEncoder<T>>>::uninitialize; + + TChannelLocalisationEncoder() { } + + TChannelLocalisationEncoder(T& boxAlgorithm, size_t index) + { + m_boxAlgorithm = NULL; + this->initialize(boxAlgorithm, index); + } + + virtual ~TChannelLocalisationEncoder() { this->uninitialize(); } +}; +} // namespace Toolkit } // namespace OpenViBE #endif // TARGET_HAS_ThirdPartyOpenViBEPluginsGlobalDefines diff --git a/toolkit/include/toolkit/codecs/encoders/ovtkTChannelUnitsEncoder.h b/toolkit/include/toolkit/codecs/encoders/ovtkTChannelUnitsEncoder.h index 9fb5fa709f3c797c7fd2e6edb4dcbd56db270315..c1f52ed60ac8511763103e3e971e4b5679086090 100644 --- a/toolkit/include/toolkit/codecs/encoders/ovtkTChannelUnitsEncoder.h +++ b/toolkit/include/toolkit/codecs/encoders/ovtkTChannelUnitsEncoder.h @@ -4,78 +4,76 @@ #include "ovtkTStreamedMatrixEncoder.h" -namespace OpenViBE +namespace OpenViBE { +namespace Toolkit { +template <class T> +class TChannelUnitsEncoderLocal : public T { - namespace Toolkit +protected: + + Kernel::TParameterHandler<bool> m_iDynamic; + + using T::m_codec; + using T::m_boxAlgorithm; + using T::m_buffer; + using T::m_iMatrix; + + bool initializeImpl() + { + m_codec = &m_boxAlgorithm->getAlgorithmManager().getAlgorithm( + m_boxAlgorithm->getAlgorithmManager().createAlgorithm(OVP_GD_ClassId_Algorithm_ChannelUnitsEncoder)); + m_codec->initialize(); + m_iMatrix.initialize(m_codec->getInputParameter(OVP_GD_Algorithm_ChannelUnitsEncoder_InputParameterId_Matrix)); + m_iDynamic.initialize(m_codec->getInputParameter(OVP_GD_Algorithm_ChannelUnitsEncoder_InputParameterId_Dynamic)); + m_buffer.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_ChannelUnitsEncoder_OutputParameterId_EncodedMemoryBuffer)); + + return true; + } + +public: + using T::initialize; + + bool uninitialize() + { + if (m_boxAlgorithm == nullptr || m_codec == nullptr) { return false; } + + m_iMatrix.uninitialize(); + m_iDynamic.uninitialize(); + + m_buffer.uninitialize(); + m_codec->uninitialize(); + m_boxAlgorithm->getAlgorithmManager().releaseAlgorithm(*m_codec); + m_boxAlgorithm = NULL; + + return true; + } + + Kernel::TParameterHandler<bool>& getInputDynamic() { return m_iDynamic; } + +protected: + bool encodeHeaderImpl() { return m_codec->process(OVP_GD_Algorithm_ChannelUnitsEncoder_InputTriggerId_EncodeHeader); } + bool encodeBufferImpl() { return m_codec->process(OVP_GD_Algorithm_ChannelUnitsEncoder_InputTriggerId_EncodeBuffer); } + bool encodeEndImpl() { return m_codec->process(OVP_GD_Algorithm_ChannelUnitsEncoder_InputTriggerId_EncodeEnd); } +}; + +template <class T> +class TChannelUnitsEncoder : public TChannelUnitsEncoderLocal<TStreamedMatrixEncoderLocal<TEncoder<T>>> +{ + using TChannelUnitsEncoderLocal<TStreamedMatrixEncoderLocal<TEncoder<T>>>::m_boxAlgorithm; +public: + using TChannelUnitsEncoderLocal<TStreamedMatrixEncoderLocal<TEncoder<T>>>::uninitialize; + + TChannelUnitsEncoder() { } + + TChannelUnitsEncoder(T& boxAlgorithm, size_t index) { - template <class T> - class TChannelUnitsEncoderLocal : public T - { - protected: - - Kernel::TParameterHandler<bool> m_iDynamic; - - using T::m_codec; - using T::m_boxAlgorithm; - using T::m_buffer; - using T::m_iMatrix; - - bool initializeImpl() - { - m_codec = &m_boxAlgorithm->getAlgorithmManager().getAlgorithm( - m_boxAlgorithm->getAlgorithmManager().createAlgorithm(OVP_GD_ClassId_Algorithm_ChannelUnitsEncoder)); - m_codec->initialize(); - m_iMatrix.initialize(m_codec->getInputParameter(OVP_GD_Algorithm_ChannelUnitsEncoder_InputParameterId_Matrix)); - m_iDynamic.initialize(m_codec->getInputParameter(OVP_GD_Algorithm_ChannelUnitsEncoder_InputParameterId_Dynamic)); - m_buffer.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_ChannelUnitsEncoder_OutputParameterId_EncodedMemoryBuffer)); - - return true; - } - - public: - using T::initialize; - - bool uninitialize() - { - if (m_boxAlgorithm == nullptr || m_codec == nullptr) { return false; } - - m_iMatrix.uninitialize(); - m_iDynamic.uninitialize(); - - m_buffer.uninitialize(); - m_codec->uninitialize(); - m_boxAlgorithm->getAlgorithmManager().releaseAlgorithm(*m_codec); - m_boxAlgorithm = NULL; - - return true; - } - - Kernel::TParameterHandler<bool>& getInputDynamic() { return m_iDynamic; } - - protected: - bool encodeHeaderImpl() { return m_codec->process(OVP_GD_Algorithm_ChannelUnitsEncoder_InputTriggerId_EncodeHeader); } - bool encodeBufferImpl() { return m_codec->process(OVP_GD_Algorithm_ChannelUnitsEncoder_InputTriggerId_EncodeBuffer); } - bool encodeEndImpl() { return m_codec->process(OVP_GD_Algorithm_ChannelUnitsEncoder_InputTriggerId_EncodeEnd); } - }; - - template <class T> - class TChannelUnitsEncoder : public TChannelUnitsEncoderLocal<TStreamedMatrixEncoderLocal<TEncoder<T>>> - { - using TChannelUnitsEncoderLocal<TStreamedMatrixEncoderLocal<TEncoder<T>>>::m_boxAlgorithm; - public: - using TChannelUnitsEncoderLocal<TStreamedMatrixEncoderLocal<TEncoder<T>>>::uninitialize; - - TChannelUnitsEncoder() { } - - TChannelUnitsEncoder(T& boxAlgorithm, size_t index) - { - m_boxAlgorithm = NULL; - this->initialize(boxAlgorithm, index); - } - - virtual ~TChannelUnitsEncoder() { this->uninitialize(); } - }; - } // namespace Toolkit + m_boxAlgorithm = NULL; + this->initialize(boxAlgorithm, index); + } + + virtual ~TChannelUnitsEncoder() { this->uninitialize(); } +}; +} // namespace Toolkit } // namespace OpenViBE #endif // TARGET_HAS_ThirdPartyOpenViBEPluginsGlobalDefines diff --git a/toolkit/include/toolkit/codecs/encoders/ovtkTEncoder.h b/toolkit/include/toolkit/codecs/encoders/ovtkTEncoder.h index 96c3d1491064dd0149b6e143399c79cd6965a048..7e8e74d689d6f42af4e0535ec0bac1c42f420fbb 100644 --- a/toolkit/include/toolkit/codecs/encoders/ovtkTEncoder.h +++ b/toolkit/include/toolkit/codecs/encoders/ovtkTEncoder.h @@ -6,83 +6,80 @@ #include "../ovtkTCodec.h" -namespace OpenViBE +namespace OpenViBE { +namespace Toolkit { +template <class T> +class TEncoderLocal : public T { - namespace Toolkit +protected: + + Kernel::TParameterHandler<IMemoryBuffer*> m_buffer; + + using T::initialize; + using T::m_codec; + using T::m_boxAlgorithm; + using T::m_connectorIdx; + + virtual void setOutputChunk(IMemoryBuffer* pOutputChunkMemoryBuffer) { m_buffer = pOutputChunkMemoryBuffer; } + + virtual Kernel::TParameterHandler<IMemoryBuffer*>& getOutputMemoryBuffer() { return m_buffer; } + + virtual bool isOutputTriggerActive(const CIdentifier oTrigger) { return m_codec->isOutputTriggerActive(oTrigger); } + + virtual bool process(const CIdentifier& oTrigger) { return m_codec->process(oTrigger); } + virtual bool process() { return m_codec->process(); } + + // The functions that need to be specified by the encoders (specific Trigger ID) + virtual bool encodeHeaderImpl() = 0; + virtual bool encodeBufferImpl() = 0; + virtual bool encodeEndImpl() = 0; + +public: + + /* + These public methods handle every aspect of the encoding process : + - prepare the output memory buffer with a chunk + - encode (specific for each encoder) + - mark output as ready to be sent has to be done manually, for accurate timing. + */ + + bool encodeHeader() + { + this->setOutputChunk(m_boxAlgorithm->getDynamicBoxContext().getOutputChunk(m_connectorIdx)); + if (!this->encodeHeaderImpl()) return false; + return true; + } + + bool encodeBuffer() { - template <class T> - class TEncoderLocal : public T - { - protected: - - Kernel::TParameterHandler<IMemoryBuffer*> m_buffer; - - using T::initialize; - using T::m_codec; - using T::m_boxAlgorithm; - using T::m_connectorIdx; - - virtual void setOutputChunk(IMemoryBuffer* pOutputChunkMemoryBuffer) { m_buffer = pOutputChunkMemoryBuffer; } - - virtual Kernel::TParameterHandler<IMemoryBuffer*>& getOutputMemoryBuffer() { return m_buffer; } - - virtual bool isOutputTriggerActive(const CIdentifier oTrigger) { return m_codec->isOutputTriggerActive(oTrigger); } - - virtual bool process(const CIdentifier& oTrigger) { return m_codec->process(oTrigger); } - - virtual bool process() { return m_codec->process(); } - - // The functions that need to be specified by the encoders (specific Trigger ID) - virtual bool encodeHeaderImpl() = 0; - virtual bool encodeBufferImpl() = 0; - virtual bool encodeEndImpl() = 0; - - public: - - /* - These public methods handle every aspect of the encoding process : - - prepare the output memory buffer with a chunk - - encode (specific for each encoder) - - mark output as ready to be sent has to be done manually, for accurate timing. - */ - - bool encodeHeader() - { - this->setOutputChunk(m_boxAlgorithm->getDynamicBoxContext().getOutputChunk(m_connectorIdx)); - if (!this->encodeHeaderImpl()) return false; - return true; - } - - bool encodeBuffer() - { - this->setOutputChunk(m_boxAlgorithm->getDynamicBoxContext().getOutputChunk(m_connectorIdx)); - if (!this->encodeBufferImpl()) return false; - return true; - } - - bool encodeEnd() - { - this->setOutputChunk(m_boxAlgorithm->getDynamicBoxContext().getOutputChunk(m_connectorIdx)); - if (!this->encodeEndImpl()) return false; - return true; - } - }; - - /* - This class provides an access to the superclass TEncoder. - Use case : iterating over a vector of TEncoder, calling encodeHeader() each time. - You don't need to know which type of encoder is in the vector. - */ - template <class T> - class TEncoder : public TEncoderLocal<TCodec<T>> - { - public: - virtual ~TEncoder() { } - protected: - // constructor is protected, ensuring we can't instanciate a TEncoder - TEncoder() { } - }; - } // namespace Toolkit + this->setOutputChunk(m_boxAlgorithm->getDynamicBoxContext().getOutputChunk(m_connectorIdx)); + if (!this->encodeBufferImpl()) return false; + return true; + } + + bool encodeEnd() + { + this->setOutputChunk(m_boxAlgorithm->getDynamicBoxContext().getOutputChunk(m_connectorIdx)); + if (!this->encodeEndImpl()) return false; + return true; + } +}; + +/* +This class provides an access to the superclass TEncoder. +Use case : iterating over a vector of TEncoder, calling encodeHeader() each time. +You don't need to know which type of encoder is in the vector. +*/ +template <class T> +class TEncoder : public TEncoderLocal<TCodec<T>> +{ +public: + virtual ~TEncoder() { } +protected: + // constructor is protected, ensuring we can't instanciate a TEncoder + TEncoder() { } +}; +} // namespace Toolkit } // namespace OpenViBE #endif // TARGET_HAS_ThirdPartyOpenViBEPluginsGlobalDefines diff --git a/toolkit/include/toolkit/codecs/encoders/ovtkTExperimentInfoEncoder.h b/toolkit/include/toolkit/codecs/encoders/ovtkTExperimentInfoEncoder.h index 837f9affcbfe6010f3c203c1a7162be6c9863d50..d719398fa951f105efe1e43051972f9a8a4627a5 100644 --- a/toolkit/include/toolkit/codecs/encoders/ovtkTExperimentInfoEncoder.h +++ b/toolkit/include/toolkit/codecs/encoders/ovtkTExperimentInfoEncoder.h @@ -6,117 +6,115 @@ #include "ovtkTEncoder.h" -namespace OpenViBE +namespace OpenViBE { +namespace Toolkit { +template <class T> +class TExperimentInfoEncoderLocal : public T { - namespace Toolkit +protected: + + Kernel::TParameterHandler<uint64_t> m_experimentID; + Kernel::TParameterHandler<CString*> m_experimentDate; + + Kernel::TParameterHandler<uint64_t> m_subjectID; + Kernel::TParameterHandler<CString*> m_subjectName; + Kernel::TParameterHandler<uint64_t> m_subjectAge; + Kernel::TParameterHandler<uint64_t> m_subjectGender; + + Kernel::TParameterHandler<uint64_t> m_laboratoryID; + Kernel::TParameterHandler<CString*> m_laboratoryName; + Kernel::TParameterHandler<uint64_t> m_technicianID; + Kernel::TParameterHandler<CString*> m_technicianName; + + using T::m_codec; + using T::m_boxAlgorithm; + using T::m_buffer; + + bool initializeImpl() + { + m_codec = &m_boxAlgorithm->getAlgorithmManager().getAlgorithm( + m_boxAlgorithm->getAlgorithmManager().createAlgorithm(OVP_GD_ClassId_Algorithm_ExperimentInfoEncoder)); + m_codec->initialize(); + m_experimentID.initialize(m_codec->getInputParameter(OVP_GD_Algorithm_ExperimentInfoEncoder_InputParameterId_ExperimentID)); + m_experimentDate.initialize(m_codec->getInputParameter(OVP_GD_Algorithm_ExperimentInfoEncoder_InputParameterId_ExperimentDate)); + + m_subjectID.initialize(m_codec->getInputParameter(OVP_GD_Algorithm_ExperimentInfoEncoder_InputParameterId_SubjectID)); + m_subjectName.initialize(m_codec->getInputParameter(OVP_GD_Algorithm_ExperimentInfoEncoder_InputParameterId_SubjectName)); + m_subjectAge.initialize(m_codec->getInputParameter(OVP_GD_Algorithm_ExperimentInfoEncoder_InputParameterId_SubjectAge)); + m_subjectGender.initialize(m_codec->getInputParameter(OVP_GD_Algorithm_ExperimentInfoEncoder_InputParameterId_SubjectGender)); + + m_laboratoryID.initialize(m_codec->getInputParameter(OVP_GD_Algorithm_ExperimentInfoEncoder_InputParameterId_LaboratoryID)); + m_laboratoryName.initialize(m_codec->getInputParameter(OVP_GD_Algorithm_ExperimentInfoEncoder_InputParameterId_LaboratoryName)); + m_technicianID.initialize(m_codec->getInputParameter(OVP_GD_Algorithm_ExperimentInfoEncoder_InputParameterId_TechnicianID)); + m_technicianName.initialize(m_codec->getInputParameter(OVP_GD_Algorithm_ExperimentInfoEncoder_InputParameterId_TechnicianName)); + + m_buffer.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_ExperimentInfoEncoder_OutputParameterId_EncodedMemoryBuffer)); + + return true; + } + +public: + using T::initialize; + + bool uninitialize() { - template <class T> - class TExperimentInfoEncoderLocal : public T - { - protected: - - Kernel::TParameterHandler<uint64_t> m_experimentID; - Kernel::TParameterHandler<CString*> m_experimentDate; - - Kernel::TParameterHandler<uint64_t> m_subjectID; - Kernel::TParameterHandler<CString*> m_subjectName; - Kernel::TParameterHandler<uint64_t> m_subjectAge; - Kernel::TParameterHandler<uint64_t> m_subjectGender; - - Kernel::TParameterHandler<uint64_t> m_laboratoryID; - Kernel::TParameterHandler<CString*> m_laboratoryName; - Kernel::TParameterHandler<uint64_t> m_technicianID; - Kernel::TParameterHandler<CString*> m_technicianName; - - using T::m_codec; - using T::m_boxAlgorithm; - using T::m_buffer; - - bool initializeImpl() - { - m_codec = &m_boxAlgorithm->getAlgorithmManager().getAlgorithm( - m_boxAlgorithm->getAlgorithmManager().createAlgorithm(OVP_GD_ClassId_Algorithm_ExperimentInfoEncoder)); - m_codec->initialize(); - m_experimentID.initialize(m_codec->getInputParameter(OVP_GD_Algorithm_ExperimentInfoEncoder_InputParameterId_ExperimentID)); - m_experimentDate.initialize(m_codec->getInputParameter(OVP_GD_Algorithm_ExperimentInfoEncoder_InputParameterId_ExperimentDate)); - - m_subjectID.initialize(m_codec->getInputParameter(OVP_GD_Algorithm_ExperimentInfoEncoder_InputParameterId_SubjectID)); - m_subjectName.initialize(m_codec->getInputParameter(OVP_GD_Algorithm_ExperimentInfoEncoder_InputParameterId_SubjectName)); - m_subjectAge.initialize(m_codec->getInputParameter(OVP_GD_Algorithm_ExperimentInfoEncoder_InputParameterId_SubjectAge)); - m_subjectGender.initialize(m_codec->getInputParameter(OVP_GD_Algorithm_ExperimentInfoEncoder_InputParameterId_SubjectGender)); - - m_laboratoryID.initialize(m_codec->getInputParameter(OVP_GD_Algorithm_ExperimentInfoEncoder_InputParameterId_LaboratoryID)); - m_laboratoryName.initialize(m_codec->getInputParameter(OVP_GD_Algorithm_ExperimentInfoEncoder_InputParameterId_LaboratoryName)); - m_technicianID.initialize(m_codec->getInputParameter(OVP_GD_Algorithm_ExperimentInfoEncoder_InputParameterId_TechnicianID)); - m_technicianName.initialize(m_codec->getInputParameter(OVP_GD_Algorithm_ExperimentInfoEncoder_InputParameterId_TechnicianName)); - - m_buffer.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_ExperimentInfoEncoder_OutputParameterId_EncodedMemoryBuffer)); - - return true; - } - - public: - using T::initialize; - - bool uninitialize() - { - if (m_boxAlgorithm == nullptr || m_codec == nullptr) { return false; } - - m_experimentID.uninitialize(); - m_experimentDate.uninitialize(); - m_subjectID.uninitialize(); - m_subjectName.uninitialize(); - m_subjectAge.uninitialize(); - m_subjectGender.uninitialize(); - m_laboratoryID.uninitialize(); - m_laboratoryName.uninitialize(); - m_technicianID.uninitialize(); - m_technicianName.uninitialize(); - - m_buffer.uninitialize(); - m_codec->uninitialize(); - m_boxAlgorithm->getAlgorithmManager().releaseAlgorithm(*m_codec); - m_boxAlgorithm = NULL; - - return true; - } - - Kernel::TParameterHandler<uint64_t>& getInputExperimentID() { return m_experimentID; } - Kernel::TParameterHandler<CString*>& getInputExperimentDate() { return m_experimentDate; } - Kernel::TParameterHandler<uint64_t>& getInputSubjectID() { return m_subjectID; } - Kernel::TParameterHandler<CString*>& getInputSubjectName() { return m_subjectName; } - Kernel::TParameterHandler<uint64_t>& getInputSubjectAge() { return m_subjectAge; } - Kernel::TParameterHandler<uint64_t>& getInputSubjectGender() { return m_subjectGender; } - Kernel::TParameterHandler<uint64_t>& getInputLaboratoryID() { return m_laboratoryID; } - Kernel::TParameterHandler<CString*>& getInputLaboratoryName() { return m_laboratoryName; } - Kernel::TParameterHandler<uint64_t>& getInputTechnicianID() { return m_technicianID; } - Kernel::TParameterHandler<CString*>& getInputTechnicianName() { return m_technicianName; } - - protected: - bool encodeHeaderImpl() { return m_codec->process(OVP_GD_Algorithm_ExperimentInfoEncoder_InputTriggerId_EncodeHeader); } - bool encodeBufferImpl() { return m_codec->process(OVP_GD_Algorithm_ExperimentInfoEncoder_InputTriggerId_EncodeBuffer); } - bool encodeEndImpl() { return m_codec->process(OVP_GD_Algorithm_ExperimentInfoEncoder_InputTriggerId_EncodeEnd); } - }; - - template <class T> - class TExperimentInfoEncoder : public TExperimentInfoEncoderLocal<TEncoder<T>> - { - using TExperimentInfoEncoderLocal<TEncoder<T>>::m_boxAlgorithm; - - public: - using TExperimentInfoEncoderLocal<TEncoder<T>>::uninitialize; - - TExperimentInfoEncoder() { } - - TExperimentInfoEncoder(T& boxAlgorithm, size_t index) - { - m_boxAlgorithm = NULL; - this->initialize(boxAlgorithm, index); - } - - virtual ~TExperimentInfoEncoder() { this->uninitialize(); } - }; - } // namespace Toolkit + if (m_boxAlgorithm == nullptr || m_codec == nullptr) { return false; } + + m_experimentID.uninitialize(); + m_experimentDate.uninitialize(); + m_subjectID.uninitialize(); + m_subjectName.uninitialize(); + m_subjectAge.uninitialize(); + m_subjectGender.uninitialize(); + m_laboratoryID.uninitialize(); + m_laboratoryName.uninitialize(); + m_technicianID.uninitialize(); + m_technicianName.uninitialize(); + + m_buffer.uninitialize(); + m_codec->uninitialize(); + m_boxAlgorithm->getAlgorithmManager().releaseAlgorithm(*m_codec); + m_boxAlgorithm = NULL; + + return true; + } + + Kernel::TParameterHandler<uint64_t>& getInputExperimentID() { return m_experimentID; } + Kernel::TParameterHandler<CString*>& getInputExperimentDate() { return m_experimentDate; } + Kernel::TParameterHandler<uint64_t>& getInputSubjectID() { return m_subjectID; } + Kernel::TParameterHandler<CString*>& getInputSubjectName() { return m_subjectName; } + Kernel::TParameterHandler<uint64_t>& getInputSubjectAge() { return m_subjectAge; } + Kernel::TParameterHandler<uint64_t>& getInputSubjectGender() { return m_subjectGender; } + Kernel::TParameterHandler<uint64_t>& getInputLaboratoryID() { return m_laboratoryID; } + Kernel::TParameterHandler<CString*>& getInputLaboratoryName() { return m_laboratoryName; } + Kernel::TParameterHandler<uint64_t>& getInputTechnicianID() { return m_technicianID; } + Kernel::TParameterHandler<CString*>& getInputTechnicianName() { return m_technicianName; } + +protected: + bool encodeHeaderImpl() { return m_codec->process(OVP_GD_Algorithm_ExperimentInfoEncoder_InputTriggerId_EncodeHeader); } + bool encodeBufferImpl() { return m_codec->process(OVP_GD_Algorithm_ExperimentInfoEncoder_InputTriggerId_EncodeBuffer); } + bool encodeEndImpl() { return m_codec->process(OVP_GD_Algorithm_ExperimentInfoEncoder_InputTriggerId_EncodeEnd); } +}; + +template <class T> +class TExperimentInfoEncoder : public TExperimentInfoEncoderLocal<TEncoder<T>> +{ + using TExperimentInfoEncoderLocal<TEncoder<T>>::m_boxAlgorithm; + +public: + using TExperimentInfoEncoderLocal<TEncoder<T>>::uninitialize; + + TExperimentInfoEncoder() { } + + TExperimentInfoEncoder(T& boxAlgorithm, size_t index) + { + m_boxAlgorithm = NULL; + this->initialize(boxAlgorithm, index); + } + + virtual ~TExperimentInfoEncoder() { this->uninitialize(); } +}; +} // namespace Toolkit } // namespace OpenViBE #endif // TARGET_HAS_ThirdPartyOpenViBEPluginsGlobalDefines diff --git a/toolkit/include/toolkit/codecs/encoders/ovtkTFeatureVectorEncoder.h b/toolkit/include/toolkit/codecs/encoders/ovtkTFeatureVectorEncoder.h index a63e1e8caf886e5e30f2a6ecf545814a6aad3806..99b56fdb2635074a99bd026778ca89614ae118b3 100644 --- a/toolkit/include/toolkit/codecs/encoders/ovtkTFeatureVectorEncoder.h +++ b/toolkit/include/toolkit/codecs/encoders/ovtkTFeatureVectorEncoder.h @@ -6,60 +6,58 @@ #include "ovtkTStreamedMatrixEncoder.h" -namespace OpenViBE +namespace OpenViBE { +namespace Toolkit { +template <class T> +class TFeatureVectorEncoderLocal : public T { - namespace Toolkit - { - template <class T> - class TFeatureVectorEncoderLocal : public T - { - protected: - // the feature vector stream is just a streamed matrix with some constraint (dimension = 2). - // no specific parameter. - - using T::m_codec; - using T::m_boxAlgorithm; - using T::m_buffer; - using T::m_iMatrix; - - bool initializeImpl() - { - m_codec = &m_boxAlgorithm->getAlgorithmManager().getAlgorithm( - m_boxAlgorithm->getAlgorithmManager().createAlgorithm(OVP_GD_ClassId_Algorithm_FeatureVectorEncoder)); - m_codec->initialize(); - m_iMatrix.initialize(m_codec->getInputParameter(OVP_GD_Algorithm_FeatureVectorEncoder_InputParameterId_Matrix)); - m_buffer.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_FeatureVectorEncoder_OutputParameterId_EncodedMemoryBuffer)); - - return true; - } +protected: + // the feature vector stream is just a streamed matrix with some constraint (dimension = 2). + // no specific parameter. - bool encodeHeaderImpl() { return m_codec->process(OVP_GD_Algorithm_FeatureVectorEncoder_InputTriggerId_EncodeHeader); } - bool encodeBufferImpl() { return m_codec->process(OVP_GD_Algorithm_FeatureVectorEncoder_InputTriggerId_EncodeBuffer); } - bool encodeEndImpl() { return m_codec->process(OVP_GD_Algorithm_FeatureVectorEncoder_InputTriggerId_EncodeEnd); } + using T::m_codec; + using T::m_boxAlgorithm; + using T::m_buffer; + using T::m_iMatrix; - public: - using T::initialize; - using T::uninitialize; - }; - - template <class T> - class TFeatureVectorEncoder : public TFeatureVectorEncoderLocal<TStreamedMatrixEncoderLocal<TEncoder<T>>> - { - using TFeatureVectorEncoderLocal<TStreamedMatrixEncoderLocal<TEncoder<T>>>::m_boxAlgorithm; - public: - using TFeatureVectorEncoderLocal<TStreamedMatrixEncoderLocal<TEncoder<T>>>::uninitialize; + bool initializeImpl() + { + m_codec = &m_boxAlgorithm->getAlgorithmManager().getAlgorithm( + m_boxAlgorithm->getAlgorithmManager().createAlgorithm(OVP_GD_ClassId_Algorithm_FeatureVectorEncoder)); + m_codec->initialize(); + m_iMatrix.initialize(m_codec->getInputParameter(OVP_GD_Algorithm_FeatureVectorEncoder_InputParameterId_Matrix)); + m_buffer.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_FeatureVectorEncoder_OutputParameterId_EncodedMemoryBuffer)); + + return true; + } + + bool encodeHeaderImpl() { return m_codec->process(OVP_GD_Algorithm_FeatureVectorEncoder_InputTriggerId_EncodeHeader); } + bool encodeBufferImpl() { return m_codec->process(OVP_GD_Algorithm_FeatureVectorEncoder_InputTriggerId_EncodeBuffer); } + bool encodeEndImpl() { return m_codec->process(OVP_GD_Algorithm_FeatureVectorEncoder_InputTriggerId_EncodeEnd); } + +public: + using T::initialize; + using T::uninitialize; +}; + +template <class T> +class TFeatureVectorEncoder : public TFeatureVectorEncoderLocal<TStreamedMatrixEncoderLocal<TEncoder<T>>> +{ + using TFeatureVectorEncoderLocal<TStreamedMatrixEncoderLocal<TEncoder<T>>>::m_boxAlgorithm; +public: + using TFeatureVectorEncoderLocal<TStreamedMatrixEncoderLocal<TEncoder<T>>>::uninitialize; - TFeatureVectorEncoder() { } + TFeatureVectorEncoder() { } - TFeatureVectorEncoder(T& boxAlgorithm, size_t index) - { - m_boxAlgorithm = NULL; - this->initialize(boxAlgorithm, index); - } + TFeatureVectorEncoder(T& boxAlgorithm, size_t index) + { + m_boxAlgorithm = NULL; + this->initialize(boxAlgorithm, index); + } - virtual ~TFeatureVectorEncoder() { this->uninitialize(); } - }; - } // namespace Toolkit + virtual ~TFeatureVectorEncoder() { this->uninitialize(); } +}; +} // namespace Toolkit } // namespace OpenViBE #endif // TARGET_HAS_ThirdPartyOpenViBEPluginsGlobalDefines diff --git a/toolkit/include/toolkit/codecs/encoders/ovtkTSignalEncoder.h b/toolkit/include/toolkit/codecs/encoders/ovtkTSignalEncoder.h index ec9c51159d485615cb303822081ddc60a07a6439..56e2d265a848bfc2191bec0829130ec3eed0c42c 100644 --- a/toolkit/include/toolkit/codecs/encoders/ovtkTSignalEncoder.h +++ b/toolkit/include/toolkit/codecs/encoders/ovtkTSignalEncoder.h @@ -6,86 +6,84 @@ #include "ovtkTStreamedMatrixEncoder.h" -namespace OpenViBE +namespace OpenViBE { +namespace Toolkit { +template <class T> +class TSignalEncoderLocal : public T { - namespace Toolkit +protected: + //The signal stream is a streamed matrix plus a sampling rate + Kernel::TParameterHandler<uint64_t> m_iSampling; + + using T::m_codec; + using T::m_boxAlgorithm; + using T::m_buffer; + using T::m_iMatrix; + + bool initializeImpl() + { + m_codec = &m_boxAlgorithm->getAlgorithmManager().getAlgorithm( + m_boxAlgorithm->getAlgorithmManager().createAlgorithm(OVP_GD_ClassId_Algorithm_SignalEncoder)); + m_codec->initialize(); + m_iMatrix.initialize(m_codec->getInputParameter(OVP_GD_Algorithm_SignalEncoder_InputParameterId_Matrix)); + m_iSampling.initialize(m_codec->getInputParameter(OVP_GD_Algorithm_SignalEncoder_InputParameterId_Sampling)); + m_buffer.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_StreamedMatrixEncoder_OutputParameterId_EncodedMemoryBuffer)); + + return true; + } + +public: + //again... we propagate initialize from upperclass. + using T::initialize; + + bool uninitialize() { - template <class T> - class TSignalEncoderLocal : public T - { - protected: - //The signal stream is a streamed matrix plus a sampling rate - Kernel::TParameterHandler<uint64_t> m_iSampling; - - using T::m_codec; - using T::m_boxAlgorithm; - using T::m_buffer; - using T::m_iMatrix; - - bool initializeImpl() - { - m_codec = &m_boxAlgorithm->getAlgorithmManager().getAlgorithm( - m_boxAlgorithm->getAlgorithmManager().createAlgorithm(OVP_GD_ClassId_Algorithm_SignalEncoder)); - m_codec->initialize(); - m_iMatrix.initialize(m_codec->getInputParameter(OVP_GD_Algorithm_SignalEncoder_InputParameterId_Matrix)); - m_iSampling.initialize(m_codec->getInputParameter(OVP_GD_Algorithm_SignalEncoder_InputParameterId_Sampling)); - m_buffer.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_StreamedMatrixEncoder_OutputParameterId_EncodedMemoryBuffer)); - - return true; - } - - public: - //again... we propagate initialize from upperclass. - using T::initialize; - - bool uninitialize() - { - if (m_boxAlgorithm == nullptr || m_codec == nullptr) { return false; } - - m_iMatrix.uninitialize(); - m_iSampling.uninitialize(); - m_buffer.uninitialize(); - m_codec->uninitialize(); - m_boxAlgorithm->getAlgorithmManager().releaseAlgorithm(*m_codec); - m_boxAlgorithm = NULL; - - return true; - } - - Kernel::TParameterHandler<uint64_t>& getInputSamplingRate() { return m_iSampling; } - - protected: - - /* - The methods specific to the Signal encoder (overriding the TStreamedMatrixEncoderLocal implementations): - */ - bool encodeHeaderImpl() { return m_codec->process(OVP_GD_Algorithm_SignalEncoder_InputTriggerId_EncodeHeader); } - bool encodeBufferImpl() { return m_codec->process(OVP_GD_Algorithm_SignalEncoder_InputTriggerId_EncodeBuffer); } - bool encodeEndImpl() { return m_codec->process(OVP_GD_Algorithm_SignalEncoder_InputTriggerId_EncodeEnd); } - }; - - /* - The Signal encoder can be instanciated easily through this class. - You just need one template class : the box (T). - */ - template <class T> - class TSignalEncoder : public TSignalEncoderLocal<TStreamedMatrixEncoderLocal<TEncoder<T>>> - { - using TSignalEncoderLocal<TStreamedMatrixEncoderLocal<TEncoder<T>>>::m_boxAlgorithm; - public: - using TSignalEncoderLocal<TStreamedMatrixEncoderLocal<TEncoder<T>>>::uninitialize; - - TSignalEncoder() { } - - TSignalEncoder(T& boxAlgorithm, size_t index) - { - m_boxAlgorithm = NULL; - this->initialize(boxAlgorithm, index); - } - - virtual ~TSignalEncoder() { this->uninitialize(); } - }; - } // namespace Toolkit + if (m_boxAlgorithm == nullptr || m_codec == nullptr) { return false; } + + m_iMatrix.uninitialize(); + m_iSampling.uninitialize(); + m_buffer.uninitialize(); + m_codec->uninitialize(); + m_boxAlgorithm->getAlgorithmManager().releaseAlgorithm(*m_codec); + m_boxAlgorithm = NULL; + + return true; + } + + Kernel::TParameterHandler<uint64_t>& getInputSamplingRate() { return m_iSampling; } + +protected: + + /* + The methods specific to the Signal encoder (overriding the TStreamedMatrixEncoderLocal implementations): + */ + bool encodeHeaderImpl() { return m_codec->process(OVP_GD_Algorithm_SignalEncoder_InputTriggerId_EncodeHeader); } + bool encodeBufferImpl() { return m_codec->process(OVP_GD_Algorithm_SignalEncoder_InputTriggerId_EncodeBuffer); } + bool encodeEndImpl() { return m_codec->process(OVP_GD_Algorithm_SignalEncoder_InputTriggerId_EncodeEnd); } +}; + +/* +The Signal encoder can be instanciated easily through this class. +You just need one template class : the box (T). +*/ +template <class T> +class TSignalEncoder : public TSignalEncoderLocal<TStreamedMatrixEncoderLocal<TEncoder<T>>> +{ + using TSignalEncoderLocal<TStreamedMatrixEncoderLocal<TEncoder<T>>>::m_boxAlgorithm; +public: + using TSignalEncoderLocal<TStreamedMatrixEncoderLocal<TEncoder<T>>>::uninitialize; + + TSignalEncoder() { } + + TSignalEncoder(T& boxAlgorithm, size_t index) + { + m_boxAlgorithm = NULL; + this->initialize(boxAlgorithm, index); + } + + virtual ~TSignalEncoder() { this->uninitialize(); } +}; +} // namespace Toolkit } // namespace OpenViBE #endif // TARGET_HAS_ThirdPartyOpenViBEPluginsGlobalDefines diff --git a/toolkit/include/toolkit/codecs/encoders/ovtkTSpectrumEncoder.h b/toolkit/include/toolkit/codecs/encoders/ovtkTSpectrumEncoder.h index a9931240ff19b3850e4b4bf64a718886a0f9147b..5ee23678285d8dfbdda42da714bd4fac71a13927 100755 --- a/toolkit/include/toolkit/codecs/encoders/ovtkTSpectrumEncoder.h +++ b/toolkit/include/toolkit/codecs/encoders/ovtkTSpectrumEncoder.h @@ -5,85 +5,83 @@ #include "../../ovtk_base.h" #include "ovtkTStreamedMatrixEncoder.h" -namespace OpenViBE +namespace OpenViBE { +namespace Toolkit { +template <class T> +class TSpectrumEncoderLocal : public T { - namespace Toolkit +protected: + + Kernel::TParameterHandler<IMatrix*> m_iFrequencyAbscissa; + Kernel::TParameterHandler<uint64_t> m_iSampling; + + using T::m_codec; + using T::m_boxAlgorithm; + using T::m_buffer; + using T::m_iMatrix; + + bool initializeImpl() + { + m_codec = &m_boxAlgorithm->getAlgorithmManager().getAlgorithm( + m_boxAlgorithm->getAlgorithmManager().createAlgorithm(OVP_GD_ClassId_Algorithm_SpectrumEncoder)); + m_codec->initialize(); + m_iMatrix.initialize(m_codec->getInputParameter(OVP_GD_Algorithm_SpectrumEncoder_InputParameterId_Matrix)); + m_iFrequencyAbscissa.initialize(m_codec->getInputParameter(OVP_GD_Algorithm_SpectrumEncoder_InputParameterId_FrequencyAbscissa)); + m_iSampling.initialize(m_codec->getInputParameter(OVP_GD_Algorithm_SpectrumEncoder_InputParameterId_Sampling)); + m_buffer.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_SpectrumEncoder_OutputParameterId_EncodedMemoryBuffer)); + + + return true; + } + +public: + using T::initialize; + + bool uninitialize() + { + if (m_boxAlgorithm == nullptr || m_codec == nullptr) { return false; } + + m_iMatrix.uninitialize(); + m_iFrequencyAbscissa.uninitialize(); + m_iSampling.uninitialize(); + m_buffer.uninitialize(); + m_codec->uninitialize(); + m_boxAlgorithm->getAlgorithmManager().releaseAlgorithm(*m_codec); + m_boxAlgorithm = NULL; + + return true; + } + + Kernel::TParameterHandler<uint64_t>& getInputSamplingRate() { return m_iSampling; } + Kernel::TParameterHandler<IMatrix*>& getInputFrequencyAbscissa() { return m_iFrequencyAbscissa; } + + size_t getInputFrequencyAbscissaCount() { return m_iFrequencyAbscissa->getDimensionSize(0); } + + +protected: + bool encodeHeaderImpl() { return m_codec->process(OVP_GD_Algorithm_SpectrumEncoder_InputTriggerId_EncodeHeader); } + bool encodeBufferImpl() { return m_codec->process(OVP_GD_Algorithm_SpectrumEncoder_InputTriggerId_EncodeBuffer); } + bool encodeEndImpl() { return m_codec->process(OVP_GD_Algorithm_SpectrumEncoder_InputTriggerId_EncodeEnd); } +}; + +template <class T> +class TSpectrumEncoder : public TSpectrumEncoderLocal<TStreamedMatrixEncoderLocal<TEncoder<T>>> +{ + using TSpectrumEncoderLocal<TStreamedMatrixEncoderLocal<TEncoder<T>>>::m_boxAlgorithm; +public: + using TSpectrumEncoderLocal<TStreamedMatrixEncoderLocal<TEncoder<T>>>::uninitialize; + + TSpectrumEncoder() { } + + TSpectrumEncoder(T& boxAlgorithm, size_t index) { - template <class T> - class TSpectrumEncoderLocal : public T - { - protected: - - Kernel::TParameterHandler<IMatrix*> m_iFrequencyAbscissa; - Kernel::TParameterHandler<uint64_t> m_iSampling; - - using T::m_codec; - using T::m_boxAlgorithm; - using T::m_buffer; - using T::m_iMatrix; - - bool initializeImpl() - { - m_codec = &m_boxAlgorithm->getAlgorithmManager().getAlgorithm( - m_boxAlgorithm->getAlgorithmManager().createAlgorithm(OVP_GD_ClassId_Algorithm_SpectrumEncoder)); - m_codec->initialize(); - m_iMatrix.initialize(m_codec->getInputParameter(OVP_GD_Algorithm_SpectrumEncoder_InputParameterId_Matrix)); - m_iFrequencyAbscissa.initialize(m_codec->getInputParameter(OVP_GD_Algorithm_SpectrumEncoder_InputParameterId_FrequencyAbscissa)); - m_iSampling.initialize(m_codec->getInputParameter(OVP_GD_Algorithm_SpectrumEncoder_InputParameterId_Sampling)); - m_buffer.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_SpectrumEncoder_OutputParameterId_EncodedMemoryBuffer)); - - - return true; - } - - public: - using T::initialize; - - bool uninitialize() - { - if (m_boxAlgorithm == nullptr || m_codec == nullptr) { return false; } - - m_iMatrix.uninitialize(); - m_iFrequencyAbscissa.uninitialize(); - m_iSampling.uninitialize(); - m_buffer.uninitialize(); - m_codec->uninitialize(); - m_boxAlgorithm->getAlgorithmManager().releaseAlgorithm(*m_codec); - m_boxAlgorithm = NULL; - - return true; - } - - Kernel::TParameterHandler<uint64_t>& getInputSamplingRate() { return m_iSampling; } - Kernel::TParameterHandler<IMatrix*>& getInputFrequencyAbscissa() { return m_iFrequencyAbscissa; } - - size_t getInputFrequencyAbscissaCount() { return m_iFrequencyAbscissa->getDimensionSize(0); } - - - protected: - bool encodeHeaderImpl() { return m_codec->process(OVP_GD_Algorithm_SpectrumEncoder_InputTriggerId_EncodeHeader); } - bool encodeBufferImpl() { return m_codec->process(OVP_GD_Algorithm_SpectrumEncoder_InputTriggerId_EncodeBuffer); } - bool encodeEndImpl() { return m_codec->process(OVP_GD_Algorithm_SpectrumEncoder_InputTriggerId_EncodeEnd); } - }; - - template <class T> - class TSpectrumEncoder : public TSpectrumEncoderLocal<TStreamedMatrixEncoderLocal<TEncoder<T>>> - { - using TSpectrumEncoderLocal<TStreamedMatrixEncoderLocal<TEncoder<T>>>::m_boxAlgorithm; - public: - using TSpectrumEncoderLocal<TStreamedMatrixEncoderLocal<TEncoder<T>>>::uninitialize; - - TSpectrumEncoder() { } - - TSpectrumEncoder(T& boxAlgorithm, size_t index) - { - m_boxAlgorithm = NULL; - this->initialize(boxAlgorithm, index); - } - - virtual ~TSpectrumEncoder() { this->uninitialize(); } - }; - } // namespace Toolkit + m_boxAlgorithm = NULL; + this->initialize(boxAlgorithm, index); + } + + virtual ~TSpectrumEncoder() { this->uninitialize(); } +}; +} // namespace Toolkit } // namespace OpenViBE #endif // TARGET_HAS_ThirdPartyOpenViBEPluginsGlobalDefines diff --git a/toolkit/include/toolkit/codecs/encoders/ovtkTStimulationStreamEncoder.h b/toolkit/include/toolkit/codecs/encoders/ovtkTStimulationStreamEncoder.h index 5feb3029476ca4979c3a41baea64de1ad3255e33..b78a31e7e9f051f86785dc8493f047c4c219729f 100644 --- a/toolkit/include/toolkit/codecs/encoders/ovtkTStimulationStreamEncoder.h +++ b/toolkit/include/toolkit/codecs/encoders/ovtkTStimulationStreamEncoder.h @@ -6,74 +6,72 @@ #include "ovtkTEncoder.h" -namespace OpenViBE +namespace OpenViBE { +namespace Toolkit { +template <class T> +class TStimulationEncoderLocal : public T { - namespace Toolkit +protected: + + Kernel::TParameterHandler<IStimulationSet*> m_iStimulationSet; + + using T::m_codec; + using T::m_boxAlgorithm; + using T::m_buffer; + + bool initializeImpl() { - template <class T> - class TStimulationEncoderLocal : public T - { - protected: - - Kernel::TParameterHandler<IStimulationSet*> m_iStimulationSet; - - using T::m_codec; - using T::m_boxAlgorithm; - using T::m_buffer; - - bool initializeImpl() - { - m_codec = &m_boxAlgorithm->getAlgorithmManager().getAlgorithm( - m_boxAlgorithm->getAlgorithmManager().createAlgorithm(OVP_GD_ClassId_Algorithm_StimulationEncoder)); - m_codec->initialize(); - m_iStimulationSet.initialize(m_codec->getInputParameter(OVP_GD_Algorithm_StimulationEncoder_InputParameterId_StimulationSet)); - m_buffer.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_StimulationEncoder_OutputParameterId_EncodedMemoryBuffer)); - - return true; - } - - public: - using T::initialize; - - bool uninitialize() - { - if (m_boxAlgorithm == nullptr || m_codec == nullptr) { return false; } - - m_iStimulationSet.uninitialize(); - m_buffer.uninitialize(); - m_codec->uninitialize(); - m_boxAlgorithm->getAlgorithmManager().releaseAlgorithm(*m_codec); - m_boxAlgorithm = NULL; - - return true; - } - - Kernel::TParameterHandler<IStimulationSet*>& getInputStimulationSet() { return m_iStimulationSet; } - - protected: - bool encodeHeaderImpl() { return m_codec->process(OVP_GD_Algorithm_StimulationEncoder_InputTriggerId_EncodeHeader); } - bool encodeBufferImpl() { return m_codec->process(OVP_GD_Algorithm_StimulationEncoder_InputTriggerId_EncodeBuffer); } - bool encodeEndImpl() { return m_codec->process(OVP_GD_Algorithm_StimulationEncoder_InputTriggerId_EncodeEnd); } - }; - - template <class T> - class TStimulationEncoder : public TStimulationEncoderLocal<TEncoder<T>> - { - using TStimulationEncoderLocal<TEncoder<T>>::m_boxAlgorithm; - public: - using TStimulationEncoderLocal<TEncoder<T>>::uninitialize; - - TStimulationEncoder() { } - - TStimulationEncoder(T& boxAlgorithm, size_t index) - { - m_boxAlgorithm = NULL; - this->initialize(boxAlgorithm, index); - } - - virtual ~TStimulationEncoder() { this->uninitialize(); } - }; - } // namespace Toolkit + m_codec = &m_boxAlgorithm->getAlgorithmManager().getAlgorithm( + m_boxAlgorithm->getAlgorithmManager().createAlgorithm(OVP_GD_ClassId_Algorithm_StimulationEncoder)); + m_codec->initialize(); + m_iStimulationSet.initialize(m_codec->getInputParameter(OVP_GD_Algorithm_StimulationEncoder_InputParameterId_StimulationSet)); + m_buffer.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_StimulationEncoder_OutputParameterId_EncodedMemoryBuffer)); + + return true; + } + +public: + using T::initialize; + + bool uninitialize() + { + if (m_boxAlgorithm == nullptr || m_codec == nullptr) { return false; } + + m_iStimulationSet.uninitialize(); + m_buffer.uninitialize(); + m_codec->uninitialize(); + m_boxAlgorithm->getAlgorithmManager().releaseAlgorithm(*m_codec); + m_boxAlgorithm = NULL; + + return true; + } + + Kernel::TParameterHandler<IStimulationSet*>& getInputStimulationSet() { return m_iStimulationSet; } + +protected: + bool encodeHeaderImpl() { return m_codec->process(OVP_GD_Algorithm_StimulationEncoder_InputTriggerId_EncodeHeader); } + bool encodeBufferImpl() { return m_codec->process(OVP_GD_Algorithm_StimulationEncoder_InputTriggerId_EncodeBuffer); } + bool encodeEndImpl() { return m_codec->process(OVP_GD_Algorithm_StimulationEncoder_InputTriggerId_EncodeEnd); } +}; + +template <class T> +class TStimulationEncoder : public TStimulationEncoderLocal<TEncoder<T>> +{ + using TStimulationEncoderLocal<TEncoder<T>>::m_boxAlgorithm; +public: + using TStimulationEncoderLocal<TEncoder<T>>::uninitialize; + + TStimulationEncoder() { } + + TStimulationEncoder(T& boxAlgorithm, size_t index) + { + m_boxAlgorithm = NULL; + this->initialize(boxAlgorithm, index); + } + + virtual ~TStimulationEncoder() { this->uninitialize(); } +}; +} // namespace Toolkit } // namespace OpenViBE #endif // TARGET_HAS_ThirdPartyOpenViBEPluginsGlobalDefines diff --git a/toolkit/include/toolkit/codecs/encoders/ovtkTStreamedMatrixEncoder.h b/toolkit/include/toolkit/codecs/encoders/ovtkTStreamedMatrixEncoder.h index bb56e0e84270d6961013baa78827be33145d8975..a28a8350174ac541ede499e45294e807b056991b 100644 --- a/toolkit/include/toolkit/codecs/encoders/ovtkTStreamedMatrixEncoder.h +++ b/toolkit/include/toolkit/codecs/encoders/ovtkTStreamedMatrixEncoder.h @@ -6,83 +6,81 @@ #include "ovtkTEncoder.h" -namespace OpenViBE +namespace OpenViBE { +namespace Toolkit { +template <class T> +class TStreamedMatrixEncoderLocal : public T { - namespace Toolkit +protected: + //specific attribute : a matrix handler + Kernel::TParameterHandler<IMatrix*> m_iMatrix; + + using T::m_codec; + using T::m_boxAlgorithm; + using T::m_buffer; + + bool initializeImpl() + { + m_codec = &m_boxAlgorithm->getAlgorithmManager().getAlgorithm( + m_boxAlgorithm->getAlgorithmManager().createAlgorithm(OVP_GD_ClassId_Algorithm_StreamedMatrixEncoder)); + m_codec->initialize(); + m_iMatrix.initialize(m_codec->getInputParameter(OVP_GD_Algorithm_StreamedMatrixEncoder_InputParameterId_Matrix)); + m_buffer.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_StreamedMatrixEncoder_OutputParameterId_EncodedMemoryBuffer)); + + return true; + } + +public: + // we propagate the visiblity of TCodec::initialize + using T::initialize; + + bool uninitialize() { - template <class T> - class TStreamedMatrixEncoderLocal : public T - { - protected: - //specific attribute : a matrix handler - Kernel::TParameterHandler<IMatrix*> m_iMatrix; - - using T::m_codec; - using T::m_boxAlgorithm; - using T::m_buffer; - - bool initializeImpl() - { - m_codec = &m_boxAlgorithm->getAlgorithmManager().getAlgorithm( - m_boxAlgorithm->getAlgorithmManager().createAlgorithm(OVP_GD_ClassId_Algorithm_StreamedMatrixEncoder)); - m_codec->initialize(); - m_iMatrix.initialize(m_codec->getInputParameter(OVP_GD_Algorithm_StreamedMatrixEncoder_InputParameterId_Matrix)); - m_buffer.initialize(m_codec->getOutputParameter(OVP_GD_Algorithm_StreamedMatrixEncoder_OutputParameterId_EncodedMemoryBuffer)); - - return true; - } - - public: - // we propagate the visiblity of TCodec::initialize - using T::initialize; - - bool uninitialize() - { - if (m_boxAlgorithm == nullptr || m_codec == nullptr) { return false; } - - m_iMatrix.uninitialize(); - m_buffer.uninitialize(); - m_codec->uninitialize(); - m_boxAlgorithm->getAlgorithmManager().releaseAlgorithm(*m_codec); - m_boxAlgorithm = NULL; - - return true; - } - - Kernel::TParameterHandler<IMatrix*>& getInputMatrix() { return m_iMatrix; } - - protected: - - /* - The methods specific to the Streamed Matrix encoder : - */ - bool encodeHeaderImpl() { return m_codec->process(OVP_GD_Algorithm_StreamedMatrixEncoder_InputTriggerId_EncodeHeader); } - bool encodeBufferImpl() { return m_codec->process(OVP_GD_Algorithm_StreamedMatrixEncoder_InputTriggerId_EncodeBuffer); } - bool encodeEndImpl() { return m_codec->process(OVP_GD_Algorithm_StreamedMatrixEncoder_InputTriggerId_EncodeEnd); } - }; - - /* - This class provides an access to the Local class. - It makes a lot easier the declaration of a Streamed Matrix encoder, as you don't have to specify any more template than the Box class (T). - */ - template <class T> - class TStreamedMatrixEncoder : public TStreamedMatrixEncoderLocal<TEncoder<T>> - { - using TStreamedMatrixEncoderLocal<TEncoder<T>>::m_boxAlgorithm; - public: - using TStreamedMatrixEncoderLocal<TEncoder<T>>::uninitialize; - - TStreamedMatrixEncoder() { } - - TStreamedMatrixEncoder(T& boxAlgorithm, size_t index) - { - m_boxAlgorithm = NULL; - this->initialize(boxAlgorithm, index); - } - - virtual ~TStreamedMatrixEncoder() { this->uninitialize(); } - }; - } // namespace Toolkit + if (m_boxAlgorithm == nullptr || m_codec == nullptr) { return false; } + + m_iMatrix.uninitialize(); + m_buffer.uninitialize(); + m_codec->uninitialize(); + m_boxAlgorithm->getAlgorithmManager().releaseAlgorithm(*m_codec); + m_boxAlgorithm = NULL; + + return true; + } + + Kernel::TParameterHandler<IMatrix*>& getInputMatrix() { return m_iMatrix; } + +protected: + + /* + The methods specific to the Streamed Matrix encoder : + */ + bool encodeHeaderImpl() { return m_codec->process(OVP_GD_Algorithm_StreamedMatrixEncoder_InputTriggerId_EncodeHeader); } + bool encodeBufferImpl() { return m_codec->process(OVP_GD_Algorithm_StreamedMatrixEncoder_InputTriggerId_EncodeBuffer); } + bool encodeEndImpl() { return m_codec->process(OVP_GD_Algorithm_StreamedMatrixEncoder_InputTriggerId_EncodeEnd); } +}; + +/* +This class provides an access to the Local class. +It makes a lot easier the declaration of a Streamed Matrix encoder, as you don't have to specify any more template than the Box class (T). +*/ +template <class T> +class TStreamedMatrixEncoder : public TStreamedMatrixEncoderLocal<TEncoder<T>> +{ + using TStreamedMatrixEncoderLocal<TEncoder<T>>::m_boxAlgorithm; +public: + using TStreamedMatrixEncoderLocal<TEncoder<T>>::uninitialize; + + TStreamedMatrixEncoder() { } + + TStreamedMatrixEncoder(T& boxAlgorithm, size_t index) + { + m_boxAlgorithm = NULL; + this->initialize(boxAlgorithm, index); + } + + virtual ~TStreamedMatrixEncoder() { this->uninitialize(); } +}; +} // namespace Toolkit } // namespace OpenViBE #endif // TARGET_HAS_ThirdPartyOpenViBEPluginsGlobalDefines diff --git a/toolkit/include/toolkit/codecs/ovtkTCodec.h b/toolkit/include/toolkit/codecs/ovtkTCodec.h index 99f8882454125d54b78489f42adf622e232c2ea3..8f7ac1af37a34d6e4042d4afe96277f09bdad8c0 100644 --- a/toolkit/include/toolkit/codecs/ovtkTCodec.h +++ b/toolkit/include/toolkit/codecs/ovtkTCodec.h @@ -55,55 +55,53 @@ The Codec Toolkit reference page may also be useful. GL&HF */ -namespace OpenViBE +namespace OpenViBE { +namespace Toolkit { +template <class T> +class TCodec { - namespace Toolkit +protected: + + // We will need the dynamic box context when trying to decode and encode, thus we keep a pointer on the underlying box. + T* m_boxAlgorithm = nullptr; + + // Every codec has an algorithm + Kernel::IAlgorithmProxy* m_codec = nullptr; + size_t m_connectorIdx = 0;//one codec per connector + +public: + TCodec() : m_boxAlgorithm(nullptr) { } + virtual ~TCodec() { } + + //The initialization need a reference to the underlying box + //it will certainly be called in the box in such manner : m_codec.initialize(*this); + bool initialize(T& boxAlgorithm, const size_t connectorIdx) { - template <class T> - class TCodec + if (m_boxAlgorithm == nullptr) { - protected: - - // We will need the dynamic box context when trying to decode and encode, thus we keep a pointer on the underlying box. - T* m_boxAlgorithm = nullptr; - - // Every codec has an algorithm - Kernel::IAlgorithmProxy* m_codec = nullptr; - size_t m_connectorIdx = 0;//one codec per connector - - public: - TCodec() : m_boxAlgorithm(nullptr) { } - virtual ~TCodec() { } - - //The initialization need a reference to the underlying box - //it will certainly be called in the box in such manner : m_codec.initialize(*this); - bool initialize(T& boxAlgorithm, const size_t connectorIdx) - { - if (m_boxAlgorithm == nullptr) - { - m_boxAlgorithm = &boxAlgorithm; - m_connectorIdx = connectorIdx; //TODO : can we check the box static context and verify the requested connector exist? - } - else { return false; } - // we call the initialization process specific to each codec - return initializeImpl(); - } - - // As we need to properly uninit parameter handlers before anything else, we can't design a common uninit behavior - virtual bool uninitialize() = 0; - - protected: - - // Note that this method is NOT public. - virtual bool initializeImpl() = 0; - - // for easier access to algorithm functionnality, we redefine some functions: - virtual bool isOutputTriggerActive(const CIdentifier trigger) { return m_codec->isOutputTriggerActive(trigger); } - - virtual bool process(const CIdentifier& trigger) { return m_codec->process(trigger); } - virtual bool process() { return m_codec->process(); } - }; - } // namespace Toolkit + m_boxAlgorithm = &boxAlgorithm; + m_connectorIdx = connectorIdx; //TODO : can we check the box static context and verify the requested connector exist? + } + else { return false; } + // we call the initialization process specific to each codec + return initializeImpl(); + } + + // As we need to properly uninit parameter handlers before anything else, we can't design a common uninit behavior + virtual bool uninitialize() = 0; + +protected: + + // Note that this method is NOT public. + virtual bool initializeImpl() = 0; + + // for easier access to algorithm functionnality, we redefine some functions: + virtual bool isOutputTriggerActive(const CIdentifier trigger) { return m_codec->isOutputTriggerActive(trigger); } + + virtual bool process(const CIdentifier& trigger) { return m_codec->process(trigger); } + virtual bool process() { return m_codec->process(); } +}; +} // namespace Toolkit } // namespace OpenViBE #endif // TARGET_HAS_ThirdPartyOpenViBEPluginsGlobalDefines diff --git a/toolkit/include/toolkit/codecs/ovtkTGenericCodec.h b/toolkit/include/toolkit/codecs/ovtkTGenericCodec.h index 5db6e11841b2d7536eefdc93c61b33f6eb5e3d4c..bcc99e1efae8251ede70a222a8972c7d0848ddd3 100644 --- a/toolkit/include/toolkit/codecs/ovtkTGenericCodec.h +++ b/toolkit/include/toolkit/codecs/ovtkTGenericCodec.h @@ -36,14 +36,12 @@ #include "encoders/ovtkTSpectrumEncoder.h" #include "encoders/ovtkTFeatureVectorEncoder.h" -namespace OpenViBE -{ - namespace Toolkit - { +namespace OpenViBE { +namespace Toolkit { - // ______________________________________________________________________________________________________________________________________________________________________________ - // ______________________________________________________________________________________________________________________________________________________________________________ - // +// ______________________________________________________________________________________________________________________________________________________________________________ +// ______________________________________________________________________________________________________________________________________________________________________________ +// #define decoder_return_impl(what) \ if(m_signalDecoder) { return m_signalDecoder->what; } \ @@ -51,105 +49,105 @@ namespace OpenViBE if(m_featureVectorDecoder) { return m_featureVectorDecoder->what; } \ return m_streamedMatrixDecoder->what; - template <class T> - class TGenericDecoder - { - protected: - - void reset() - { - m_streamedMatrixDecoder = nullptr; - m_signalDecoder = nullptr; - m_spectrumDecoder = nullptr; - m_featureVectorDecoder = nullptr; - } - - public: - - TGenericDecoder() : m_streamedMatrixDecoder(nullptr), m_signalDecoder(nullptr), m_spectrumDecoder(nullptr), m_featureVectorDecoder(nullptr) - { - this->reset(); - } - - ~TGenericDecoder() { this->uninitialize(); } - - TGenericDecoder<T>& operator=(TStreamedMatrixDecoder<T>* decoder) - { - this->reset(); - m_streamedMatrixDecoder = decoder; - return *this; - } - - TGenericDecoder<T>& operator=(TSignalDecoder<T>* decoder) - { - this->reset(); - m_signalDecoder = decoder; - return *this; - } - - TGenericDecoder<T>& operator=(TSpectrumDecoder<T>* decoder) - { - this->reset(); - m_spectrumDecoder = decoder; - return *this; - } - - TGenericDecoder<T>& operator=(TFeatureVectorDecoder<T>* decoder) - { - this->reset(); - m_featureVectorDecoder = decoder; - return *this; - } - - void uninitialize() { this->reset(); } - - Kernel::TParameterHandler<IMatrix*>& getOutputMatrix() - { - decoder_return_impl(getOutputMatrix()); - } - - Kernel::TParameterHandler<uint64_t>& getOutputSamplingRate() - { - if (m_signalDecoder) { return m_signalDecoder->getOutputSamplingRate(); } - return m_spectrumDecoder->getOutputSamplingRate(); - } - - Kernel::TParameterHandler<IMatrix*>& getOutputFrequencyAbcissa() { return m_spectrumDecoder->getOutputFrequencyAbscissa(); } - - bool decode(int, int) = delete; - bool decode(size_t, size_t) = delete; - - bool decode(const size_t chunkIdx, bool bMarkInputAsDeprecated = true) - { - decoder_return_impl(decode(chunkIdx, bMarkInputAsDeprecated)); - } - - bool isHeaderReceived() - { - decoder_return_impl(isHeaderReceived()); - } - - bool isBufferReceived() - { - decoder_return_impl(isBufferReceived()); - } - - bool isEndReceived() - { - decoder_return_impl(isEndReceived()); - } - - protected: - - TStreamedMatrixDecoder<T>* m_streamedMatrixDecoder = nullptr; - TSignalDecoder<T>* m_signalDecoder = nullptr; - TSpectrumDecoder<T>* m_spectrumDecoder = nullptr; - TFeatureVectorDecoder<T>* m_featureVectorDecoder = nullptr; - }; - - // ______________________________________________________________________________________________________________________________________________________________________________ - // ______________________________________________________________________________________________________________________________________________________________________________ - // +template <class T> +class TGenericDecoder +{ +protected: + + void reset() + { + m_streamedMatrixDecoder = nullptr; + m_signalDecoder = nullptr; + m_spectrumDecoder = nullptr; + m_featureVectorDecoder = nullptr; + } + +public: + + TGenericDecoder() : m_streamedMatrixDecoder(nullptr), m_signalDecoder(nullptr), m_spectrumDecoder(nullptr), m_featureVectorDecoder(nullptr) + { + this->reset(); + } + + ~TGenericDecoder() { this->uninitialize(); } + + TGenericDecoder<T>& operator=(TStreamedMatrixDecoder<T>* decoder) + { + this->reset(); + m_streamedMatrixDecoder = decoder; + return *this; + } + + TGenericDecoder<T>& operator=(TSignalDecoder<T>* decoder) + { + this->reset(); + m_signalDecoder = decoder; + return *this; + } + + TGenericDecoder<T>& operator=(TSpectrumDecoder<T>* decoder) + { + this->reset(); + m_spectrumDecoder = decoder; + return *this; + } + + TGenericDecoder<T>& operator=(TFeatureVectorDecoder<T>* decoder) + { + this->reset(); + m_featureVectorDecoder = decoder; + return *this; + } + + void uninitialize() { this->reset(); } + + Kernel::TParameterHandler<IMatrix*>& getOutputMatrix() + { + decoder_return_impl(getOutputMatrix()); + } + + Kernel::TParameterHandler<uint64_t>& getOutputSamplingRate() + { + if (m_signalDecoder) { return m_signalDecoder->getOutputSamplingRate(); } + return m_spectrumDecoder->getOutputSamplingRate(); + } + + Kernel::TParameterHandler<IMatrix*>& getOutputFrequencyAbcissa() { return m_spectrumDecoder->getOutputFrequencyAbscissa(); } + + bool decode(int, int) = delete; + bool decode(size_t, size_t) = delete; + + bool decode(const size_t chunkIdx, bool bMarkInputAsDeprecated = true) + { + decoder_return_impl(decode(chunkIdx, bMarkInputAsDeprecated)); + } + + bool isHeaderReceived() + { + decoder_return_impl(isHeaderReceived()); + } + + bool isBufferReceived() + { + decoder_return_impl(isBufferReceived()); + } + + bool isEndReceived() + { + decoder_return_impl(isEndReceived()); + } + +protected: + + TStreamedMatrixDecoder<T>* m_streamedMatrixDecoder = nullptr; + TSignalDecoder<T>* m_signalDecoder = nullptr; + TSpectrumDecoder<T>* m_spectrumDecoder = nullptr; + TFeatureVectorDecoder<T>* m_featureVectorDecoder = nullptr; +}; + +// ______________________________________________________________________________________________________________________________________________________________________________ +// ______________________________________________________________________________________________________________________________________________________________________________ +// #define encoder_return_impl(what) \ if(m_signalEncoder) { return m_signalEncoder->what; } \ @@ -157,164 +155,164 @@ namespace OpenViBE if(m_featureVectorEncoder) { return m_featureVectorEncoder->what; } \ return m_streamedMatrixDecoder->what; - template <class T> - class TGenericEncoder +template <class T> +class TGenericEncoder +{ +protected: + + void reset() + { + m_streamedMatrixDecoder = nullptr; + m_signalEncoder = nullptr; + m_spectrumEncoder = nullptr; + m_featureVectorEncoder = nullptr; + } + +public: + + TGenericEncoder() : m_streamedMatrixDecoder(nullptr), m_signalEncoder(nullptr), m_spectrumEncoder(nullptr), m_featureVectorEncoder(nullptr) + { + this->reset(); + } + + ~TGenericEncoder() { this->uninitialize(); } + + TGenericEncoder<T>& operator=(TStreamedMatrixEncoder<T>* pEncoder) + { + this->reset(); + m_streamedMatrixDecoder = pEncoder; + return *this; + } + + TGenericEncoder<T>& operator=(TSignalEncoder<T>* pEncoder) + { + this->reset(); + m_signalEncoder = pEncoder; + return *this; + } + + TGenericEncoder<T>& operator=(TSpectrumEncoder<T>* pEncoder) + { + this->reset(); + m_spectrumEncoder = pEncoder; + return *this; + } + + TGenericEncoder<T>& operator=(TFeatureVectorEncoder<T>* pEncoder) + { + this->reset(); + m_featureVectorEncoder = pEncoder; + return *this; + } + + void uninitialize() { this->reset(); } + + Kernel::TParameterHandler<IMatrix*>& getInputMatrix() + { + encoder_return_impl(getInputMatrix()); + } + + Kernel::TParameterHandler<uint64_t>& getInputSamplingRate() + { + if (m_signalEncoder) { return m_signalEncoder->getInputSamplingRate(); } + return m_spectrumEncoder->getInputSamplingRate(); + } + + Kernel::TParameterHandler<IMatrix*>& getInputFrequencyAbcissa() { return m_spectrumEncoder->getInputFrequencyAbscissa(); } + + bool encodeHeader() + { + encoder_return_impl(encodeHeader()); + } + + bool encodeBuffer() + { + encoder_return_impl(encodeBuffer()); + } + + bool encodeEnd() + { + encoder_return_impl(encodeEnd()); + } + +protected: + + TStreamedMatrixEncoder<T>* m_streamedMatrixDecoder = nullptr; + TSignalEncoder<T>* m_signalEncoder = nullptr; + TSpectrumEncoder<T>* m_spectrumEncoder = nullptr; + TFeatureVectorEncoder<T>* m_featureVectorEncoder = nullptr; +}; + +// ______________________________________________________________________________________________________________________________________________________________________________ +// ______________________________________________________________________________________________________________________________________________________________________________ +// + +template <class T> +class TGenericListener final : public T +{ +public: + + typedef enum + { + Type_None = 0x00000000, + Type_StreamedMatrix = 0x00000001, + Type_Signal = 0x00000002, + Type_Spectrum = 0x00000004, + Type_Covariance = 0x00000008, + Type_All = 0xffffffff + } EType; + + explicit TGenericListener(const size_t typeFlag = Type_All) + { + if (typeFlag & Type_StreamedMatrix) m_allowedTypeIDs[OV_TypeId_StreamedMatrix] = true; + if (typeFlag & Type_Signal) m_allowedTypeIDs[OV_TypeId_Signal] = true; + if (typeFlag & Type_Spectrum) m_allowedTypeIDs[OV_TypeId_Spectrum] = true; + if (typeFlag & Type_Covariance) m_allowedTypeIDs[OV_TypeId_CovarianceMatrix] = true; + } + + bool isValidInputType(const CIdentifier& typeID, size_t /*index*/) + { + return m_allowedTypeIDs[typeID]; + //return (typeID==OV_TypeId_Signal || typeID==OV_TypeId_Spectrum); + } + + virtual bool onInputTypeChanged(Kernel::IBox& box, const size_t index) + { + CIdentifier typeID = OV_UndefinedIdentifier; + box.getInputType(index, typeID); + if (this->isValidInputType(typeID, index)) { box.setOutputType(index, typeID); } + else { - protected: - - void reset() - { - m_streamedMatrixDecoder = nullptr; - m_signalEncoder = nullptr; - m_spectrumEncoder = nullptr; - m_featureVectorEncoder = nullptr; - } - - public: - - TGenericEncoder() : m_streamedMatrixDecoder(nullptr), m_signalEncoder(nullptr), m_spectrumEncoder(nullptr), m_featureVectorEncoder(nullptr) - { - this->reset(); - } - - ~TGenericEncoder() { this->uninitialize(); } - - TGenericEncoder<T>& operator=(TStreamedMatrixEncoder<T>* pEncoder) - { - this->reset(); - m_streamedMatrixDecoder = pEncoder; - return *this; - } - - TGenericEncoder<T>& operator=(TSignalEncoder<T>* pEncoder) - { - this->reset(); - m_signalEncoder = pEncoder; - return *this; - } - - TGenericEncoder<T>& operator=(TSpectrumEncoder<T>* pEncoder) - { - this->reset(); - m_spectrumEncoder = pEncoder; - return *this; - } - - TGenericEncoder<T>& operator=(TFeatureVectorEncoder<T>* pEncoder) - { - this->reset(); - m_featureVectorEncoder = pEncoder; - return *this; - } - - void uninitialize() { this->reset(); } - - Kernel::TParameterHandler<IMatrix*>& getInputMatrix() - { - encoder_return_impl(getInputMatrix()); - } - - Kernel::TParameterHandler<uint64_t>& getInputSamplingRate() - { - if (m_signalEncoder) { return m_signalEncoder->getInputSamplingRate(); } - return m_spectrumEncoder->getInputSamplingRate(); - } - - Kernel::TParameterHandler<IMatrix*>& getInputFrequencyAbcissa() { return m_spectrumEncoder->getInputFrequencyAbscissa(); } - - bool encodeHeader() - { - encoder_return_impl(encodeHeader()); - } - - bool encodeBuffer() - { - encoder_return_impl(encodeBuffer()); - } - - bool encodeEnd() - { - encoder_return_impl(encodeEnd()); - } - - protected: - - TStreamedMatrixEncoder<T>* m_streamedMatrixDecoder = nullptr; - TSignalEncoder<T>* m_signalEncoder = nullptr; - TSpectrumEncoder<T>* m_spectrumEncoder = nullptr; - TFeatureVectorEncoder<T>* m_featureVectorEncoder = nullptr; - }; - - // ______________________________________________________________________________________________________________________________________________________________________________ - // ______________________________________________________________________________________________________________________________________________________________________________ - // - - template <class T> - class TGenericListener final : public T + box.getOutputType(index, typeID); + box.setInputType(index, typeID); + } + return true; + } + + bool isValidOutputType(const CIdentifier& typeID, size_t /*index*/) + { + return m_allowedTypeIDs[typeID]; + //return (typeID==OV_TypeId_Signal || typeID==OV_TypeId_Spectrum); + } + + virtual bool onOutputTypeChanged(Kernel::IBox& box, const size_t index) + { + CIdentifier typeID = OV_UndefinedIdentifier; + box.getOutputType(index, typeID); + if (this->isValidOutputType(typeID, index)) { box.setInputType(index, typeID); } + else { - public: - - typedef enum - { - Type_None = 0x00000000, - Type_StreamedMatrix = 0x00000001, - Type_Signal = 0x00000002, - Type_Spectrum = 0x00000004, - Type_Covariance = 0x00000008, - Type_All = 0xffffffff - } EType; - - explicit TGenericListener(const size_t typeFlag = Type_All) - { - if (typeFlag & Type_StreamedMatrix) m_allowedTypeIDs[OV_TypeId_StreamedMatrix] = true; - if (typeFlag & Type_Signal) m_allowedTypeIDs[OV_TypeId_Signal] = true; - if (typeFlag & Type_Spectrum) m_allowedTypeIDs[OV_TypeId_Spectrum] = true; - if (typeFlag & Type_Covariance) m_allowedTypeIDs[OV_TypeId_CovarianceMatrix] = true; - } - - bool isValidInputType(const CIdentifier& typeID, size_t /*index*/) - { - return m_allowedTypeIDs[typeID]; - //return (typeID==OV_TypeId_Signal || typeID==OV_TypeId_Spectrum); - } - - virtual bool onInputTypeChanged(Kernel::IBox& box, const size_t index) - { - CIdentifier typeID = OV_UndefinedIdentifier; - box.getInputType(index, typeID); - if (this->isValidInputType(typeID, index)) { box.setOutputType(index, typeID); } - else - { - box.getOutputType(index, typeID); - box.setInputType(index, typeID); - } - return true; - } - - bool isValidOutputType(const CIdentifier& typeID, size_t /*index*/) - { - return m_allowedTypeIDs[typeID]; - //return (typeID==OV_TypeId_Signal || typeID==OV_TypeId_Spectrum); - } - - virtual bool onOutputTypeChanged(Kernel::IBox& box, const size_t index) - { - CIdentifier typeID = OV_UndefinedIdentifier; - box.getOutputType(index, typeID); - if (this->isValidOutputType(typeID, index)) { box.setInputType(index, typeID); } - else - { - box.getInputType(index, typeID); - box.setOutputType(index, typeID); - } - return true; - } - - _IsDerivedFromClass_Final_(T, OV_UndefinedIdentifier) - - private: - - std::map<CIdentifier, bool> m_allowedTypeIDs; - }; - } // namespace Toolkit + box.getInputType(index, typeID); + box.setOutputType(index, typeID); + } + return true; + } + + _IsDerivedFromClass_Final_(T, OV_UndefinedIdentifier) + +private: + + std::map<CIdentifier, bool> m_allowedTypeIDs; +}; +} // namespace Toolkit } // namespace OpenViBE diff --git a/toolkit/include/toolkit/ovtkIFeatureVector.h b/toolkit/include/toolkit/ovtkIFeatureVector.h index abf9ce8e45c866ad16a13a2e477cecf6a55c5ea2..724c806877f788198f16878d405cc06c4aab49c7 100644 --- a/toolkit/include/toolkit/ovtkIFeatureVector.h +++ b/toolkit/include/toolkit/ovtkIFeatureVector.h @@ -2,18 +2,16 @@ #include "ovtkIVector.h" -namespace OpenViBE +namespace OpenViBE { +namespace Toolkit { +class OVTK_API IFeatureVector : public IVector { - namespace Toolkit - { - class OVTK_API IFeatureVector : public IVector - { - public: +public: - virtual double getLabel() const = 0; - virtual bool setLabel(const double label) = 0; + virtual double getLabel() const = 0; + virtual bool setLabel(const double label) = 0; - _IsDerivedFromClass_(IVector, OVTK_ClassId_FeatureVector) - }; - } // namespace Toolkit + _IsDerivedFromClass_(IVector, OVTK_ClassId_FeatureVector) +}; +} // namespace Toolkit } // namespace OpenViBE diff --git a/toolkit/include/toolkit/ovtkIFeatureVectorSet.h b/toolkit/include/toolkit/ovtkIFeatureVectorSet.h index e91226d5cb50cbb13a97ad1ee09f9f4de0010623..904e5fa6e7ec9ab8c7249fbedd441ae3e821c152 100644 --- a/toolkit/include/toolkit/ovtkIFeatureVectorSet.h +++ b/toolkit/include/toolkit/ovtkIFeatureVectorSet.h @@ -2,29 +2,27 @@ #include "ovtk_base.h" -namespace OpenViBE -{ - namespace Toolkit - { - class IFeatureVector; +namespace OpenViBE { +namespace Toolkit { +class IFeatureVector; - class OVTK_API IFeatureVectorSet : public IObject - { - public: +class OVTK_API IFeatureVectorSet : public IObject +{ +public: - virtual size_t getFeatureVectorCount() const = 0; - virtual bool setFeatureVectorCount(const size_t featureVector) = 0; - virtual bool addFeatureVector(const IFeatureVector& featureVector) = 0; + virtual size_t getFeatureVectorCount() const = 0; + virtual bool setFeatureVectorCount(const size_t featureVector) = 0; + virtual bool addFeatureVector(const IFeatureVector& featureVector) = 0; - virtual IFeatureVector& getFeatureVector(const size_t index) = 0; - virtual const IFeatureVector& getFeatureVector(const size_t index) const = 0; - virtual size_t getLabelCount() const = 0; + virtual IFeatureVector& getFeatureVector(const size_t index) = 0; + virtual const IFeatureVector& getFeatureVector(const size_t index) const = 0; + virtual size_t getLabelCount() const = 0; - _IsDerivedFromClass_(IObject, OVTK_ClassId_FeatureVectorSet) + _IsDerivedFromClass_(IObject, OVTK_ClassId_FeatureVectorSet) - const IFeatureVector& operator [](const size_t index) const { return this->getFeatureVector(index); } + const IFeatureVector& operator [](const size_t index) const { return this->getFeatureVector(index); } - IFeatureVector& operator [](const size_t index) { return this->getFeatureVector(index); } - }; - } // namespace Toolkit + IFeatureVector& operator [](const size_t index) { return this->getFeatureVector(index); } +}; +} // namespace Toolkit } // namespace OpenViBE diff --git a/toolkit/include/toolkit/ovtkIVector.h b/toolkit/include/toolkit/ovtkIVector.h index 27ea85d9bbe0ab73d0ef71972d57a8d651f30318..86dda79cb64f61de84aca852fba9818104308ba1 100644 --- a/toolkit/include/toolkit/ovtkIVector.h +++ b/toolkit/include/toolkit/ovtkIVector.h @@ -2,25 +2,23 @@ #include "ovtk_base.h" -namespace OpenViBE +namespace OpenViBE { +namespace Toolkit { +class OVTK_API IVector : public IObject { - namespace Toolkit - { - class OVTK_API IVector : public IObject - { - public: +public: - virtual uint32_t getSize() const = 0; - virtual bool setSize(const uint32_t size) = 0; - virtual double* getBuffer() = 0; - virtual const double* getBuffer() const = 0; - virtual const char* getElementLabel(const uint32_t index) const = 0; - virtual bool setElementLabel(const uint32_t index, const char* sElementLabel) = 0; + virtual uint32_t getSize() const = 0; + virtual bool setSize(const uint32_t size) = 0; + virtual double* getBuffer() = 0; + virtual const double* getBuffer() const = 0; + virtual const char* getElementLabel(const uint32_t index) const = 0; + virtual bool setElementLabel(const uint32_t index, const char* sElementLabel) = 0; - _IsDerivedFromClass_(IObject, OVTK_ClassId_Vector) + _IsDerivedFromClass_(IObject, OVTK_ClassId_Vector) - const double& operator [](const uint32_t index) const { return this->getBuffer()[index]; } - double& operator [](const uint32_t index) { return this->getBuffer()[index]; } - }; - } // namespace Toolkit + const double& operator [](const uint32_t index) const { return this->getBuffer()[index]; } + double& operator [](const uint32_t index) { return this->getBuffer()[index]; } +}; +} // namespace Toolkit } // namespace OpenViBE diff --git a/toolkit/include/toolkit/ovtk_all.h b/toolkit/include/toolkit/ovtk_all.h index e6d3a5be3d4f1cc2bee1cc76026fcbaab9a0d479..157f51f2365567a33f21fc532830accdeec051fc 100644 --- a/toolkit/include/toolkit/ovtk_all.h +++ b/toolkit/include/toolkit/ovtk_all.h @@ -87,13 +87,11 @@ //___________________________________________________________________// // // -namespace OpenViBE -{ - namespace Toolkit - { - OVTK_API bool initialize(const Kernel::IKernelContext& ctx); - OVTK_API bool uninitialize(const Kernel::IKernelContext& ctx); - - bool initializeStimulationList(const Kernel::IKernelContext& ctx); - } // namespace Toolkit +namespace OpenViBE { +namespace Toolkit { +OVTK_API bool initialize(const Kernel::IKernelContext& ctx); +OVTK_API bool uninitialize(const Kernel::IKernelContext& ctx); + +bool initializeStimulationList(const Kernel::IKernelContext& ctx); +} // namespace Toolkit } // namespace OpenViBE diff --git a/toolkit/include/toolkit/ovtk_base.h b/toolkit/include/toolkit/ovtk_base.h index ccbeef2df97afe273462e6f52385fb4a599fc5b5..9a867e4c11c787bd2632bb871b51032e3e8707b9 100644 --- a/toolkit/include/toolkit/ovtk_base.h +++ b/toolkit/include/toolkit/ovtk_base.h @@ -4,32 +4,29 @@ #include <openvibe/ov_all.h> -namespace EBML -{ - class IWriter; - class IWriterCallback; - class IWriterHelper; - class IReader; - class IReaderCallback; - class IReaderHelper; -} // namespace EBML +namespace EBML { +class IWriter; +class IWriterCallback; +class IWriterHelper; +class IReader; +class IReaderCallback; +class IReaderHelper; +} // namespace EBML -namespace OpenViBE +namespace OpenViBE { +namespace Toolkit { +template <class THandledType> +class TScopeHandle { - namespace Toolkit - { - template <class THandledType> - class TScopeHandle - { - public: +public: - TScopeHandle(THandledType& rHandler, THandledType& rHandledValue) : m_handler(rHandler), m_lastHandledValue(rHandler) { m_handler = rHandledValue; } - ~TScopeHandle() { m_handler = m_lastHandledValue; } + TScopeHandle(THandledType& rHandler, THandledType& rHandledValue) : m_handler(rHandler), m_lastHandledValue(rHandler) { m_handler = rHandledValue; } + ~TScopeHandle() { m_handler = m_lastHandledValue; } - private: +private: - THandledType& m_handler; - THandledType m_lastHandledValue; - }; - } // namespace Toolkit + THandledType& m_handler; + THandledType m_lastHandledValue; +}; +} // namespace Toolkit } // namespace OpenViBE diff --git a/toolkit/include/toolkit/ovtk_defines.h b/toolkit/include/toolkit/ovtk_defines.h index 946fea537c026081364873e1d50da01e4fa7b2f7..0b83c7385cf5dcd16b58972c53ac6269d5dd7344 100755 --- a/toolkit/include/toolkit/ovtk_defines.h +++ b/toolkit/include/toolkit/ovtk_defines.h @@ -31,11 +31,11 @@ #define OVTK_TypeId_ExperimentationInformation OpenViBE::CIdentifier(0x403488E7, 0x565D70B6) // deprecated token, kept for compatibility, equal to the one above #define OVTK_TypeId_Stimulations OpenViBE::CIdentifier(0x6F752DD0, 0x082A321E) #define OVTK_TypeId_StreamedMatrix OpenViBE::CIdentifier(0x544A003E, 0x6DCBA5F6) -#define OVTK_TypeId_FeatureVector OpenViBE::CIdentifier(0x17341935, 0x152FF448) -#define OVTK_TypeId_Signal OpenViBE::CIdentifier(0x5BA36127, 0x195FEAE1) -#define OVTK_TypeId_Spectrum OpenViBE::CIdentifier(0x1F261C0A, 0x593BF6BD) -#define OVTK_TypeId_ChannelLocalisation OpenViBE::CIdentifier(0x013DF452, 0xA3A8879A) -#define OVTK_TypeId_ChannelUnits OpenViBE::CIdentifier(0x6AB26B81, 0x0F8C02F3) +#define OVTK_TypeId_FeatureVector OpenViBE::CIdentifier(0x17341935, 0x152FF448) +#define OVTK_TypeId_Signal OpenViBE::CIdentifier(0x5BA36127, 0x195FEAE1) +#define OVTK_TypeId_Spectrum OpenViBE::CIdentifier(0x1F261C0A, 0x593BF6BD) +#define OVTK_TypeId_ChannelLocalisation OpenViBE::CIdentifier(0x013DF452, 0xA3A8879A) +#define OVTK_TypeId_ChannelUnits OpenViBE::CIdentifier(0x6AB26B81, 0x0F8C02F3) //__________________________________________________________________// @@ -303,7 +303,6 @@ #define OVTK_UNIT_Degree_Per_Second 100001 - //__________________________________________________________________// // // // Measurement Factors // diff --git a/toolkit/include/toolkit/tools/ovtkMatrix.h b/toolkit/include/toolkit/tools/ovtkMatrix.h index 2f68c7211bd344dd77052d3f5c2180c3206a0898..0a4f900cb8ff8b18734e8c8175b007f754974275 100644 --- a/toolkit/include/toolkit/tools/ovtkMatrix.h +++ b/toolkit/include/toolkit/tools/ovtkMatrix.h @@ -2,33 +2,29 @@ #include "../ovtk_base.h" -namespace OpenViBE -{ - namespace Toolkit - { - namespace Matrix - { - OVTK_API bool copy(IMatrix& dst, const IMatrix& src); - OVTK_API bool copyDescription(IMatrix& dst, const IMatrix& src); - OVTK_API bool copyContent(IMatrix& dst, const IMatrix& src); - OVTK_API bool clearContent(IMatrix& matrix); - OVTK_API bool isDescriptionSimilar(const IMatrix& src1, const IMatrix& src2, bool checkLabels = true); - OVTK_API bool isContentSimilar(const IMatrix& src1, const IMatrix& src2); - OVTK_API bool isContentValid(const IMatrix& src, const bool checkNotANumber = true, const bool checkInfinity = true); +namespace OpenViBE { +namespace Toolkit { +namespace Matrix { +OVTK_API bool copy(IMatrix& dst, const IMatrix& src); +OVTK_API bool copyDescription(IMatrix& dst, const IMatrix& src); +OVTK_API bool copyContent(IMatrix& dst, const IMatrix& src); +OVTK_API bool clearContent(IMatrix& matrix); +OVTK_API bool isDescriptionSimilar(const IMatrix& src1, const IMatrix& src2, bool checkLabels = true); +OVTK_API bool isContentSimilar(const IMatrix& src1, const IMatrix& src2); +OVTK_API bool isContentValid(const IMatrix& src, const bool checkNotANumber = true, const bool checkInfinity = true); - OVTK_API bool toString(const IMatrix& matrix, CString& str, const size_t precision = 6); - OVTK_API bool fromString(IMatrix& matrix, const CString& str); +OVTK_API bool toString(const IMatrix& matrix, CString& str, const size_t precision = 6); +OVTK_API bool fromString(IMatrix& matrix, const CString& str); - OVTK_API bool saveToTextFile(const IMatrix& matrix, const CString& filename, const size_t precision = 6); - OVTK_API bool loadFromTextFile(IMatrix& matrix, const CString& filename); - } // namespace Matrix +OVTK_API bool saveToTextFile(const IMatrix& matrix, const CString& filename, const size_t precision = 6); +OVTK_API bool loadFromTextFile(IMatrix& matrix, const CString& filename); +} // namespace Matrix - namespace MatrixManipulation - { - inline bool copy(IMatrix& dst, const IMatrix& src) { return Matrix::copy(dst, src); } - inline bool copyDescription(IMatrix& dst, const IMatrix& src) { return Matrix::copyDescription(dst, src); } - inline bool copyContent(IMatrix& dst, const IMatrix& src) { return Matrix::copyContent(dst, src); } - inline bool clearContent(IMatrix& rMatrix) { return Matrix::clearContent(rMatrix); } - } // namespace MatrixManipulation - } // namespace Toolkit +namespace MatrixManipulation { +inline bool copy(IMatrix& dst, const IMatrix& src) { return Matrix::copy(dst, src); } +inline bool copyDescription(IMatrix& dst, const IMatrix& src) { return Matrix::copyDescription(dst, src); } +inline bool copyContent(IMatrix& dst, const IMatrix& src) { return Matrix::copyContent(dst, src); } +inline bool clearContent(IMatrix& rMatrix) { return Matrix::clearContent(rMatrix); } +} // namespace MatrixManipulation +} // namespace Toolkit } // namespace OpenViBE diff --git a/toolkit/include/toolkit/tools/ovtkStimulationSet.h b/toolkit/include/toolkit/tools/ovtkStimulationSet.h index f9c86756b765fa3c0be754568bbd2df18034bbfc..c291d8f2fb1f82ff7bdcb0c7695e6b119bb8ef79 100644 --- a/toolkit/include/toolkit/tools/ovtkStimulationSet.h +++ b/toolkit/include/toolkit/tools/ovtkStimulationSet.h @@ -2,18 +2,14 @@ #include "../ovtk_base.h" -namespace OpenViBE -{ - namespace Toolkit - { - namespace StimulationSet - { - OVTK_API bool shift(IStimulationSet& stimSet, uint64_t timeShift); - OVTK_API bool copy(IStimulationSet& dst, const IStimulationSet& src, uint64_t timeShift = 0); - OVTK_API bool append(IStimulationSet& dst, const IStimulationSet& src, uint64_t timeShift = 0); - OVTK_API bool appendRange(IStimulationSet& dst, const IStimulationSet& src, uint64_t srcStartTime, - uint64_t srcEndTime, uint64_t timeShift = 0); - OVTK_API bool removeRange(IStimulationSet& stimSet, uint64_t startTime, uint64_t endTime); - } // namespace StimulationSet - } // namespace Toolkit +namespace OpenViBE { +namespace Toolkit { +namespace StimulationSet { +OVTK_API bool shift(IStimulationSet& stimSet, uint64_t timeShift); +OVTK_API bool copy(IStimulationSet& dst, const IStimulationSet& src, uint64_t timeShift = 0); +OVTK_API bool append(IStimulationSet& dst, const IStimulationSet& src, uint64_t timeShift = 0); +OVTK_API bool appendRange(IStimulationSet& dst, const IStimulationSet& src, uint64_t srcStartTime, uint64_t srcEndTime, uint64_t timeShift = 0); +OVTK_API bool removeRange(IStimulationSet& stimSet, uint64_t startTime, uint64_t endTime); +} // namespace StimulationSet +} // namespace Toolkit } // namespace OpenViBE diff --git a/toolkit/include/toolkit/tools/ovtkString.h b/toolkit/include/toolkit/tools/ovtkString.h index e88baff26087a29c9a5442ccd48a905f645a2efd..f4c955eb2e8a512351c2046a7b9ddfb7d9f27318 100644 --- a/toolkit/include/toolkit/tools/ovtkString.h +++ b/toolkit/include/toolkit/tools/ovtkString.h @@ -2,39 +2,35 @@ #include "../ovtk_base.h" -namespace OpenViBE +namespace OpenViBE { +namespace Toolkit { +namespace String { +class OVTK_API ISplitCallback { - namespace Toolkit - { - namespace String - { - class OVTK_API ISplitCallback - { - public: - virtual ~ISplitCallback() { } - virtual void beginSplit() const { } - virtual void endSplit() const { } - virtual void setToken(const char* token) const = 0; - }; - - template <class TContainer> - class TSplitCallback final : public ISplitCallback - { - public: - - explicit TSplitCallback(TContainer& tokenContainers) : m_tokenContainer(&tokenContainers) { } - - void setToken(const char* token) const override { m_tokenContainer->push_back(token); } - - protected: - - TContainer* m_tokenContainer = nullptr; - }; - - OVTK_API size_t split(const CString& str, const ISplitCallback& splitCB, uint8_t separator); - OVTK_API size_t split(const CString& str, const ISplitCallback& splitCB, uint8_t* separator, const size_t nSeparator); - OVTK_API bool isAlmostEqual(const CString& str1, const CString& str2, bool caseSensitive = true, bool removeStartSpaces = true, - bool removeEndSpaces = true); - } // namespace String - } // namespace Toolkit +public: + virtual ~ISplitCallback() { } + virtual void beginSplit() const { } + virtual void endSplit() const { } + virtual void setToken(const char* token) const = 0; +}; + +template <class TContainer> +class TSplitCallback final : public ISplitCallback +{ +public: + + explicit TSplitCallback(TContainer& tokenContainers) : m_tokenContainer(&tokenContainers) { } + + void setToken(const char* token) const override { m_tokenContainer->push_back(token); } + +protected: + + TContainer* m_tokenContainer = nullptr; +}; + +OVTK_API size_t split(const CString& str, const ISplitCallback& splitCB, uint8_t separator); +OVTK_API size_t split(const CString& str, const ISplitCallback& splitCB, uint8_t* separator, const size_t nSeparator); +OVTK_API bool isAlmostEqual(const CString& str1, const CString& str2, bool caseSensitive = true, bool removeStartSpaces = true, bool removeEndSpaces = true); +} // namespace String +} // namespace Toolkit } // namespace OpenViBE diff --git a/toolkit/include/toolkit/training/ovtkISignalTrial.h b/toolkit/include/toolkit/training/ovtkISignalTrial.h index edfb5a8f2b079f87a2c2dcf5eff871999242b11a..2d19211c492b9b4792cc9b3697184a0fcf362095 100644 --- a/toolkit/include/toolkit/training/ovtkISignalTrial.h +++ b/toolkit/include/toolkit/training/ovtkISignalTrial.h @@ -2,44 +2,42 @@ #include "../ovtk_base.h" -namespace OpenViBE +namespace OpenViBE { +namespace Toolkit { +class OVTK_API ISignalTrial : public IObject { - namespace Toolkit - { - class OVTK_API ISignalTrial : public IObject - { - public: +public: - virtual bool setSamplingRate(size_t sampling) = 0; - virtual bool setChannelCount(size_t count) = 0; - virtual bool setChannelName(size_t index, const char* name) = 0; - virtual bool setLabelIdentifier(const CIdentifier& labelIdentifier) = 0; - virtual bool setSampleCount(size_t count, bool preserve) = 0; + virtual bool setSamplingRate(size_t sampling) = 0; + virtual bool setChannelCount(size_t count) = 0; + virtual bool setChannelName(size_t index, const char* name) = 0; + virtual bool setLabelIdentifier(const CIdentifier& labelIdentifier) = 0; + virtual bool setSampleCount(size_t count, bool preserve) = 0; - virtual size_t getSamplingRate() const = 0; - virtual size_t getChannelCount() const = 0; - virtual const char* getChannelName(const size_t index) const = 0; - virtual CIdentifier getLabelIdentifier() const = 0; - virtual size_t getSampleCount() const = 0; - virtual uint64_t getDuration() const = 0; - virtual double* getChannelSampleBuffer(size_t index) const = 0; + virtual size_t getSamplingRate() const = 0; + virtual size_t getChannelCount() const = 0; + virtual const char* getChannelName(const size_t index) const = 0; + virtual CIdentifier getLabelIdentifier() const = 0; + virtual size_t getSampleCount() const = 0; + virtual uint64_t getDuration() const = 0; + virtual double* getChannelSampleBuffer(size_t index) const = 0; - _IsDerivedFromClass_(IObject, OVTK_ClassId_) - }; + _IsDerivedFromClass_(IObject, OVTK_ClassId_) +}; - extern OVTK_API ISignalTrial* createSignalTrial(); - extern OVTK_API void releaseSignalTrial(ISignalTrial* trial); +extern OVTK_API ISignalTrial* createSignalTrial(); +extern OVTK_API void releaseSignalTrial(ISignalTrial* trial); - // operations - extern OVTK_API ISignalTrial& copyHeader(ISignalTrial& trial, const ISignalTrial* srcTrial = nullptr); - extern OVTK_API ISignalTrial& copy(ISignalTrial& trial, const ISignalTrial* srcTrial = nullptr); - extern OVTK_API ISignalTrial& selectSamples(ISignalTrial& trial, size_t sampleStart, size_t sampleEnd, const ISignalTrial* srcTrial = nullptr); - extern OVTK_API ISignalTrial& selectTime(ISignalTrial& trial, uint64_t timeStart, uint64_t timeEnd, const ISignalTrial* srcTrial = nullptr); - extern OVTK_API ISignalTrial& removeSamples(ISignalTrial& trial, size_t sampleStart, size_t sampleEnd, const ISignalTrial* srcTrial = nullptr); - extern OVTK_API ISignalTrial& removeTime(ISignalTrial& trial, uint64_t timeStart, uint64_t timeEnd, const ISignalTrial* srcTrial = nullptr); - extern OVTK_API ISignalTrial& insertBufferSamples(ISignalTrial& trial, size_t sampleStart, size_t nSample, const double* buffer, - const ISignalTrial* srcTrial = nullptr); - extern OVTK_API ISignalTrial& insertBufferTime(ISignalTrial& trial, uint64_t timeStart, size_t nSample, const double* buffer, - const ISignalTrial* srcTrial = nullptr); - } // namespace Toolkit +// operations +extern OVTK_API ISignalTrial& copyHeader(ISignalTrial& trial, const ISignalTrial* srcTrial = nullptr); +extern OVTK_API ISignalTrial& copy(ISignalTrial& trial, const ISignalTrial* srcTrial = nullptr); +extern OVTK_API ISignalTrial& selectSamples(ISignalTrial& trial, size_t sampleStart, size_t sampleEnd, const ISignalTrial* srcTrial = nullptr); +extern OVTK_API ISignalTrial& selectTime(ISignalTrial& trial, uint64_t timeStart, uint64_t timeEnd, const ISignalTrial* srcTrial = nullptr); +extern OVTK_API ISignalTrial& removeSamples(ISignalTrial& trial, size_t sampleStart, size_t sampleEnd, const ISignalTrial* srcTrial = nullptr); +extern OVTK_API ISignalTrial& removeTime(ISignalTrial& trial, uint64_t timeStart, uint64_t timeEnd, const ISignalTrial* srcTrial = nullptr); +extern OVTK_API ISignalTrial& insertBufferSamples(ISignalTrial& trial, size_t sampleStart, size_t nSample, const double* buffer, + const ISignalTrial* srcTrial = nullptr); +extern OVTK_API ISignalTrial& insertBufferTime(ISignalTrial& trial, uint64_t timeStart, size_t nSample, const double* buffer, + const ISignalTrial* srcTrial = nullptr); +} // namespace Toolkit } // namespace OpenViBE diff --git a/toolkit/include/toolkit/training/ovtkISignalTrialSet.h b/toolkit/include/toolkit/training/ovtkISignalTrialSet.h index 82c05bacf426b5d7ff3b98a0f9c8f97dff8fc949..d5bf0246b18df8ab8420f3a81a799cd28beb4c5a 100644 --- a/toolkit/include/toolkit/training/ovtkISignalTrialSet.h +++ b/toolkit/include/toolkit/training/ovtkISignalTrialSet.h @@ -2,26 +2,24 @@ #include "../ovtk_base.h" -namespace OpenViBE -{ - namespace Toolkit - { - class ISignalTrial; +namespace OpenViBE { +namespace Toolkit { +class ISignalTrial; - class OVTK_API ISignalTrialSet : public IObject - { - public: +class OVTK_API ISignalTrialSet : public IObject +{ +public: - virtual bool addSignalTrial(ISignalTrial& signalTrial) = 0; - virtual bool clear() = 0; + virtual bool addSignalTrial(ISignalTrial& signalTrial) = 0; + virtual bool clear() = 0; - virtual size_t getSignalTrialCount() const = 0; - virtual ISignalTrial& getSignalTrial(const size_t index) const = 0; + virtual size_t getSignalTrialCount() const = 0; + virtual ISignalTrial& getSignalTrial(const size_t index) const = 0; - _IsDerivedFromClass_(IObject, OVTK_ClassId_) - }; + _IsDerivedFromClass_(IObject, OVTK_ClassId_) +}; - extern OVTK_API ISignalTrialSet* createSignalTrialSet(); - extern OVTK_API void releaseSignalTrialSet(ISignalTrialSet* signalTrialSet); - } // namespace Toolkit +extern OVTK_API ISignalTrialSet* createSignalTrialSet(); +extern OVTK_API void releaseSignalTrialSet(ISignalTrialSet* signalTrialSet); +} // namespace Toolkit } // namespace OpenViBE diff --git a/toolkit/src/algorithms/classification/ovtkCFeatureVector.hpp b/toolkit/src/algorithms/classification/ovtkCFeatureVector.hpp index a0eea0f1c75ca0ab767f60cc0a18a7dfe8ad8c3b..dde3957aa69d51529d99b1e9b10268faa698b65d 100644 --- a/toolkit/src/algorithms/classification/ovtkCFeatureVector.hpp +++ b/toolkit/src/algorithms/classification/ovtkCFeatureVector.hpp @@ -3,25 +3,21 @@ #include "ovtkCVector.hpp" #include "../../ovtkIFeatureVector.h" -namespace OpenViBE +namespace OpenViBE { +namespace Toolkit { +template <class TParent> +class TFeatureVector final : public TVector<TParent> { - namespace Toolkit - { - template <class TParent> - class TFeatureVector final : public TVector<TParent> - { - public: +public: - explicit TFeatureVector(IMatrix& rMatrix) - : TVector<TParent>(rMatrix) { } + explicit TFeatureVector(IMatrix& rMatrix) : TVector<TParent>(rMatrix) { } - double getLabel() const override { return 0; } + double getLabel() const override { return 0; } + bool setLabel(const double /*label*/) override { return false; } - bool setLabel(const double /*label*/) override { return false; } + _IsDerivedFromClass_Final_(TVector<TParent>, OV_UndefinedIdentifier) +}; - _IsDerivedFromClass_Final_(TVector<TParent>, OV_UndefinedIdentifier) - }; - - typedef TFeatureVector<IFeatureVector> CFeatureVector; - } // namespace Toolkit +typedef TFeatureVector<IFeatureVector> CFeatureVector; +} // namespace Toolkit } // namespace OpenViBE diff --git a/toolkit/src/algorithms/classification/ovtkCFeatureVectorSet.hpp b/toolkit/src/algorithms/classification/ovtkCFeatureVectorSet.hpp index 674bef565c300980f7a615170c32c700e466121a..61f7f32e10dba0067effd036090993cafdeae52d 100644 --- a/toolkit/src/algorithms/classification/ovtkCFeatureVectorSet.hpp +++ b/toolkit/src/algorithms/classification/ovtkCFeatureVectorSet.hpp @@ -5,50 +5,48 @@ #include <map> -namespace OpenViBE +namespace OpenViBE { +namespace Toolkit { +class CInternalFeatureVector final : public IFeatureVector { - namespace Toolkit - { - class CInternalFeatureVector final : public IFeatureVector - { - public: - - CInternalFeatureVector() { } - uint32_t getSize() const override { return m_Size; } - bool setSize(const uint32_t /*size*/) override { return false; } - double* getBuffer() override { return nullptr; } - const double* getBuffer() const override { return m_Buffer; } - const char* getElementLabel(const uint32_t index) const override { return m_Matrix->getDimensionLabel(m_DimensionIdx, index); } - bool setElementLabel(const uint32_t /*index*/, const char* /*elementLabel*/) override { return false; } - double getLabel() const override { return m_Buffer[m_Size]; } - bool setLabel(const double /*label*/) override { return false; } - - _IsDerivedFromClass_Final_(IFeatureVector, OV_UndefinedIdentifier) - - const IMatrix* m_Matrix = nullptr; - uint32_t m_DimensionIdx = 0; - uint32_t m_Size = 0; - const double* m_Buffer = nullptr; - }; - - class CFeatureVectorSet final : public IFeatureVectorSet - { - public: - - explicit CFeatureVectorSet(const IMatrix& matrix); - size_t getFeatureVectorCount() const override { return m_matrix.getDimensionSize(0); } - bool setFeatureVectorCount(const size_t /*nFeatureVector*/) override { return false; } - bool addFeatureVector(const IFeatureVector& /*featureVector*/) override { return false; } - IFeatureVector& getFeatureVector(const size_t index) override; - const IFeatureVector& getFeatureVector(const size_t index) const override; - size_t getLabelCount() const override; - - _IsDerivedFromClass_Final_(IFeatureVectorSet, OV_UndefinedIdentifier) - - protected: - - const IMatrix& m_matrix; - std::map<uint32_t, CInternalFeatureVector> m_features; - }; - } // namespace Toolkit +public: + + CInternalFeatureVector() { } + uint32_t getSize() const override { return m_Size; } + bool setSize(const uint32_t /*size*/) override { return false; } + double* getBuffer() override { return nullptr; } + const double* getBuffer() const override { return m_Buffer; } + const char* getElementLabel(const uint32_t index) const override { return m_Matrix->getDimensionLabel(m_DimensionIdx, index); } + bool setElementLabel(const uint32_t /*index*/, const char* /*elementLabel*/) override { return false; } + double getLabel() const override { return m_Buffer[m_Size]; } + bool setLabel(const double /*label*/) override { return false; } + + _IsDerivedFromClass_Final_(IFeatureVector, OV_UndefinedIdentifier) + + const IMatrix* m_Matrix = nullptr; + uint32_t m_DimensionIdx = 0; + uint32_t m_Size = 0; + const double* m_Buffer = nullptr; +}; + +class CFeatureVectorSet final : public IFeatureVectorSet +{ +public: + + explicit CFeatureVectorSet(const IMatrix& matrix); + size_t getFeatureVectorCount() const override { return m_matrix.getDimensionSize(0); } + bool setFeatureVectorCount(const size_t /*nFeatureVector*/) override { return false; } + bool addFeatureVector(const IFeatureVector& /*featureVector*/) override { return false; } + IFeatureVector& getFeatureVector(const size_t index) override; + const IFeatureVector& getFeatureVector(const size_t index) const override; + size_t getLabelCount() const override; + + _IsDerivedFromClass_Final_(IFeatureVectorSet, OV_UndefinedIdentifier) + +protected: + + const IMatrix& m_matrix; + std::map<uint32_t, CInternalFeatureVector> m_features; +}; +} // namespace Toolkit } // namespace OpenViBE diff --git a/toolkit/src/algorithms/classification/ovtkCVector.hpp b/toolkit/src/algorithms/classification/ovtkCVector.hpp index f534d2602dcbae94fa7b49c01cc0cf11d38e6085..4736d0dd4586da8ad523d554decab261284db95c 100644 --- a/toolkit/src/algorithms/classification/ovtkCVector.hpp +++ b/toolkit/src/algorithms/classification/ovtkCVector.hpp @@ -3,43 +3,41 @@ #include "../../ovtk_base.h" #include "../../ovtkIVector.h" -namespace OpenViBE +namespace OpenViBE { +namespace Toolkit { +template <class TParent> +class TVector : public TParent { - namespace Toolkit - { - template <class TParent> - class TVector : public TParent - { - public: +public: - explicit TVector(IMatrix& matrix) : m_matrix(matrix) { } + explicit TVector(IMatrix& matrix) : m_matrix(matrix) { } - uint32_t getSize() const override { return m_matrix.getBufferElementCount(); } + uint32_t getSize() const override { return m_matrix.getBufferElementCount(); } - bool setSize(const uint32_t size) override - { - m_matrix.setDimensionCount(1); - m_matrix.setDimensionSize(0, size); - return true; - } + bool setSize(const uint32_t size) override + { + m_matrix.setDimensionCount(1); + m_matrix.setDimensionSize(0, size); + return true; + } - double* getBuffer() override { return m_matrix.getBuffer(); } - const double* getBuffer() const override { return m_matrix.getBuffer(); } - const char* getElementLabel(const uint32_t index) const override { return m_matrix.getDimensionLabel(0, index); } + double* getBuffer() override { return m_matrix.getBuffer(); } + const double* getBuffer() const override { return m_matrix.getBuffer(); } + const char* getElementLabel(const uint32_t index) const override { return m_matrix.getDimensionLabel(0, index); } - bool setElementLabel(const uint32_t index, const char* label) override - { - m_matrix.setDimensionLabel(0, index, label); - return true; - } + bool setElementLabel(const uint32_t index, const char* label) override + { + m_matrix.setDimensionLabel(0, index, label); + return true; + } - _IsDerivedFromClass_Final_(TParent, OV_UndefinedIdentifier) + _IsDerivedFromClass_Final_(TParent, OV_UndefinedIdentifier) - protected: +protected: - IMatrix& m_matrix; - }; + IMatrix& m_matrix; +}; - typedef TVector<IVector> CVector; - } // namespace Toolkit +typedef TVector<IVector> CVector; +} // namespace Toolkit } // namespace OpenViBE diff --git a/toolkit/src/algorithms/scenario-io/ovtkCAlgorithmScenarioExporter.cpp b/toolkit/src/algorithms/scenario-io/ovtkCAlgorithmScenarioExporter.cpp index 637232cc74a3e1a427a025d207267e49b4dd2238..d83158100d775929ebbf857a23da0c78b722d5c7 100644 --- a/toolkit/src/algorithms/scenario-io/ovtkCAlgorithmScenarioExporter.cpp +++ b/toolkit/src/algorithms/scenario-io/ovtkCAlgorithmScenarioExporter.cpp @@ -7,36 +7,33 @@ using namespace /*OpenViBE::*/Kernel; using namespace /*OpenViBE::*/Plugins; using namespace /*OpenViBE::*/Toolkit; -namespace OpenViBE +namespace OpenViBE { +namespace Toolkit { +namespace { +class CAlgorithmScenarioExporterHelper { - namespace Toolkit - { - namespace - { - class CAlgorithmScenarioExporterHelper - { - friend class CAlgorithmScenarioExporter; - public: - - CAlgorithmScenarioExporterHelper(IAlgorithmContext& context, CAlgorithmScenarioExporter& parent); - bool exportBox(IMemoryBuffer& buffer, const IBox& box) const; - bool exportComment(IMemoryBuffer& buffer, const IComment& comment) const; - bool exportMetadata(IMemoryBuffer& buffer, const IMetadata& metadata) const; - bool exportSetting(IMemoryBuffer& buffer, const IScenario& scenario, const size_t index) const; - bool exportInput(IMemoryBuffer& buffer, const IScenario& scenario, size_t index) const; - bool exportOutput(IMemoryBuffer& buffer, const IScenario& scenario, size_t index) const; - bool exportLink(IMemoryBuffer& buffer, const ILink& rLink) const; - void exportAttributes(const IAttributable& attributable, IMemoryBuffer& buffer, const CIdentifier& idAttributes, - const CIdentifier& idAttribute, const CIdentifier& idAttributeID, const CIdentifier& idAttributeValue) const; - - - protected: - - IAlgorithmContext& m_algorithmContext; - CAlgorithmScenarioExporter& m_parent; - }; - } // namespace - } // namespace Toolkit + friend class CAlgorithmScenarioExporter; +public: + + CAlgorithmScenarioExporterHelper(IAlgorithmContext& context, CAlgorithmScenarioExporter& parent); + bool exportBox(IMemoryBuffer& buffer, const IBox& box) const; + bool exportComment(IMemoryBuffer& buffer, const IComment& comment) const; + bool exportMetadata(IMemoryBuffer& buffer, const IMetadata& metadata) const; + bool exportSetting(IMemoryBuffer& buffer, const IScenario& scenario, const size_t index) const; + bool exportInput(IMemoryBuffer& buffer, const IScenario& scenario, size_t index) const; + bool exportOutput(IMemoryBuffer& buffer, const IScenario& scenario, size_t index) const; + bool exportLink(IMemoryBuffer& buffer, const ILink& rLink) const; + void exportAttributes(const IAttributable& attributable, IMemoryBuffer& buffer, const CIdentifier& idAttributes, + const CIdentifier& idAttribute, const CIdentifier& idAttributeID, const CIdentifier& idAttributeValue) const; + + +protected: + + IAlgorithmContext& m_algorithmContext; + CAlgorithmScenarioExporter& m_parent; +}; +} // namespace +} // namespace Toolkit } // namespace OpenViBE #define exportAttributesMacro(exporter, attributable, memoryBuffer, AttributableName) \ diff --git a/toolkit/src/algorithms/scenario-io/ovtkCAlgorithmScenarioImporter.cpp b/toolkit/src/algorithms/scenario-io/ovtkCAlgorithmScenarioImporter.cpp index bd688f4bfea74b0791979c8ac4e7c577a801c652..4b3a29f1e0cf3a20bac09f78736c272cb769ae4c 100644 --- a/toolkit/src/algorithms/scenario-io/ovtkCAlgorithmScenarioImporter.cpp +++ b/toolkit/src/algorithms/scenario-io/ovtkCAlgorithmScenarioImporter.cpp @@ -10,117 +10,116 @@ using namespace /*OpenViBE::*/Kernel; using namespace /*OpenViBE::*/Plugins; using namespace /*OpenViBE::*/Toolkit; -namespace +namespace { +typedef struct SScenarioInput { - typedef struct SScenarioInput - { - CIdentifier id = OV_UndefinedIdentifier; - CIdentifier typeID = OV_UndefinedIdentifier; - CString name; - CIdentifier linkedBoxID = OV_UndefinedIdentifier; - size_t linkedBoxInputIdx = size_t(-1); - CIdentifier linkedBoxInputID = OV_UndefinedIdentifier; - } scenario_input_t; - - typedef struct SScenarioOutput - { - CIdentifier id = OV_UndefinedIdentifier; - CIdentifier typeID = OV_UndefinedIdentifier; - CString name; - CIdentifier linkedBoxID = OV_UndefinedIdentifier; - size_t linkedBoxOutputIdx = size_t(-1); - CIdentifier linkedBoxOutputID = OV_UndefinedIdentifier; - } scenario_output_t; - - typedef struct SInput - { - CIdentifier id = OV_UndefinedIdentifier; - CIdentifier typeID = OV_UndefinedIdentifier; - CString name; - } input_t; + CIdentifier id = OV_UndefinedIdentifier; + CIdentifier typeID = OV_UndefinedIdentifier; + CString name; + CIdentifier linkedBoxID = OV_UndefinedIdentifier; + size_t linkedBoxInputIdx = size_t(-1); + CIdentifier linkedBoxInputID = OV_UndefinedIdentifier; +} scenario_input_t; + +typedef struct SScenarioOutput +{ + CIdentifier id = OV_UndefinedIdentifier; + CIdentifier typeID = OV_UndefinedIdentifier; + CString name; + CIdentifier linkedBoxID = OV_UndefinedIdentifier; + size_t linkedBoxOutputIdx = size_t(-1); + CIdentifier linkedBoxOutputID = OV_UndefinedIdentifier; +} scenario_output_t; + +typedef struct SInput +{ + CIdentifier id = OV_UndefinedIdentifier; + CIdentifier typeID = OV_UndefinedIdentifier; + CString name; +} input_t; - typedef struct SOutput - { - CIdentifier id = OV_UndefinedIdentifier; - CIdentifier typeID = OV_UndefinedIdentifier; - CString name; - } output_t; +typedef struct SOutput +{ + CIdentifier id = OV_UndefinedIdentifier; + CIdentifier typeID = OV_UndefinedIdentifier; + CString name; +} output_t; - typedef struct SSetting - { - CIdentifier typeID = OV_UndefinedIdentifier; - CString name; - CString defaultValue; - CString value; - bool modifiability = false; - CIdentifier id = OV_UndefinedIdentifier; - } setting_t; - - typedef struct SAttribute - { - CIdentifier id = OV_UndefinedIdentifier; - CString value; - } attribute_t; +typedef struct SSetting +{ + CIdentifier typeID = OV_UndefinedIdentifier; + CString name; + CString defaultValue; + CString value; + bool modifiability = false; + CIdentifier id = OV_UndefinedIdentifier; +} setting_t; + +typedef struct SAttribute +{ + CIdentifier id = OV_UndefinedIdentifier; + CString value; +} attribute_t; - typedef struct SBox - { - CIdentifier id = OV_UndefinedIdentifier; - CIdentifier algorithmClassID = OV_UndefinedIdentifier; - CString name; - std::vector<input_t> inputs; - std::vector<output_t> outputs; - std::vector<setting_t> settings; - std::vector<attribute_t> attributes; - } box_t; - - typedef struct SComment - { - CIdentifier id; - CString text; - std::vector<attribute_t> attributes; - } comment_t; +typedef struct SBox +{ + CIdentifier id = OV_UndefinedIdentifier; + CIdentifier algorithmClassID = OV_UndefinedIdentifier; + CString name; + std::vector<input_t> inputs; + std::vector<output_t> outputs; + std::vector<setting_t> settings; + std::vector<attribute_t> attributes; +} box_t; + +typedef struct SComment +{ + CIdentifier id; + CString text; + std::vector<attribute_t> attributes; +} comment_t; - typedef struct SMetadata - { - CIdentifier identifier; - CIdentifier type; - CString data; - } metadata_t; +typedef struct SMetadata +{ + CIdentifier identifier; + CIdentifier type; + CString data; +} metadata_t; - typedef struct SLinkSrc - { - CIdentifier boxID; - size_t boxOutputIdx = size_t(-1); - CIdentifier boxOutputID = OV_UndefinedIdentifier; - } link_src_t; +typedef struct SLinkSrc +{ + CIdentifier boxID; + size_t boxOutputIdx = size_t(-1); + CIdentifier boxOutputID = OV_UndefinedIdentifier; +} link_src_t; - typedef struct SLinkDst - { - CIdentifier boxID; - size_t boxInputIdx = size_t(-1); - CIdentifier boxInputID = OV_UndefinedIdentifier; - } link_dst_t; +typedef struct SLinkDst +{ + CIdentifier boxID; + size_t boxInputIdx = size_t(-1); + CIdentifier boxInputID = OV_UndefinedIdentifier; +} link_dst_t; - typedef struct SLink - { - CIdentifier id; - link_src_t linkSrc; - link_dst_t linkDst; - std::vector<attribute_t> attributes; - } link_t; +typedef struct SLink +{ + CIdentifier id; + link_src_t linkSrc; + link_dst_t linkDst; + std::vector<attribute_t> attributes; +} link_t; - typedef struct SScenario - { - std::vector<setting_t> settings; - std::vector<scenario_input_t> iScenarios; - std::vector<scenario_output_t> oScenarios; - std::vector<box_t> boxes; - std::vector<comment_t> comments; - std::vector<metadata_t> metadata; - std::vector<link_t> links; - std::vector<attribute_t> attributes; - } scenario_t; -} // namespace +typedef struct SScenario +{ + std::vector<setting_t> settings; + std::vector<scenario_input_t> iScenarios; + std::vector<scenario_output_t> oScenarios; + std::vector<box_t> boxes; + std::vector<comment_t> comments; + std::vector<metadata_t> metadata; + std::vector<link_t> links; + std::vector<attribute_t> attributes; +} scenario_t; +} // namespace class CAlgorithmScenarioImporterContext final : public IAlgorithmScenarioImporterContext { @@ -254,13 +253,11 @@ bool CAlgorithmScenarioImporter::process() if (srcBoxOutputID != OV_UndefinedIdentifier) { scenario->getSourceBoxOutputIndex(boxIdMapping[l->linkSrc.boxID], srcBoxOutputID, srcBoxOutputIdx); } - OV_ERROR_UNLESS_KRF(srcBoxOutputIdx != size_t(-1), "Output index of the source box could not be found", - ErrorType::BadOutput); + OV_ERROR_UNLESS_KRF(srcBoxOutputIdx != size_t(-1), "Output index of the source box could not be found", ErrorType::BadOutput); if (dstBoxInputID != OV_UndefinedIdentifier) { scenario->getTargetBoxInputIndex(boxIdMapping[l->linkDst.boxID], dstBoxInputID, dstBoxInputIdx); } - OV_ERROR_UNLESS_KRF(dstBoxInputIdx != size_t(-1), "Input index of the target box could not be found", - ErrorType::BadOutput); + OV_ERROR_UNLESS_KRF(dstBoxInputIdx != size_t(-1), "Input index of the target box could not be found", ErrorType::BadOutput); scenario->connect(newLinkID, boxIdMapping[l->linkSrc.boxID], srcBoxOutputIdx, boxIdMapping[l->linkDst.boxID], dstBoxInputIdx, l->id); diff --git a/toolkit/src/tools/ovtkString.cpp b/toolkit/src/tools/ovtkString.cpp index 717f1106a06c10b24e18a9642e79f48082996064..b31fca1019971114455323eba67f40282517a4b5 100644 --- a/toolkit/src/tools/ovtkString.cpp +++ b/toolkit/src/tools/ovtkString.cpp @@ -12,28 +12,24 @@ using namespace OpenViBE; using namespace /*OpenViBE::*/Toolkit; -namespace OpenViBE +namespace OpenViBE { +namespace Toolkit { +namespace String { +namespace { +bool isSeparator(const uint8_t value, const uint8_t* separator, const size_t nSeparator) { - namespace Toolkit - { - namespace String - { - namespace - { - bool isSeparator(const uint8_t value, const uint8_t* separator, const size_t nSeparator) - { - for (size_t i = 0; i < nSeparator; ++i) { if (value == separator[i]) { return true; } } - return false; - } - - // because std::tolower has multiple signatures, - // it can not be easily used in std::transform - // this workaround is taken from http://www.gcek.net/ref/books/sw/cpp/ticppv2/ - template <class TCharT> - TCharT ToLower(TCharT c) { return std::tolower(c); } - } // namespace - } // namespace String - } // namespace Toolkit + for (size_t i = 0; i < nSeparator; ++i) { if (value == separator[i]) { return true; } } + return false; +} + +// because std::tolower has multiple signatures, +// it can not be easily used in std::transform +// this workaround is taken from http://www.gcek.net/ref/books/sw/cpp/ticppv2/ +template <class TCharT> +TCharT ToLower(TCharT c) { return std::tolower(c); } +} // namespace +} // namespace String +} // namespace Toolkit } // namespace OpenViBE size_t String::split(const CString& str, const ISplitCallback& splitCB, uint8_t separator) { return split(str, splitCB, &separator, 1); } diff --git a/toolkit/src/training/ovtkCSignalTrial.hpp b/toolkit/src/training/ovtkCSignalTrial.hpp index cd01a8ed4c349e124c82e5d61fe50057f597afc3..6a880cbd8bcd584fc4f73f38f4502798ee8e85bb 100644 --- a/toolkit/src/training/ovtkCSignalTrial.hpp +++ b/toolkit/src/training/ovtkCSignalTrial.hpp @@ -5,40 +5,38 @@ #include <map> #include <string> -namespace OpenViBE +namespace OpenViBE { +namespace Toolkit { +class CSignalTrial final : public ISignalTrial { - namespace Toolkit - { - class CSignalTrial final : public ISignalTrial - { - public: +public: - CSignalTrial() {} - ~CSignalTrial() override { for (auto& s : m_channelSamples) { delete [] s.second; } } - bool setSamplingRate(size_t sampling) override; - bool setChannelCount(size_t count) override; - bool setChannelName(size_t index, const char* name) override; - bool setLabelIdentifier(const CIdentifier& labelID) override; - bool setSampleCount(size_t count, bool preserve) override; - size_t getSamplingRate() const override { return m_sampling; } - size_t getChannelCount() const override { return m_nChannel; } - const char* getChannelName(const size_t index) const override; - CIdentifier getLabelIdentifier() const override { return m_labelID; } - size_t getSampleCount() const override { return m_nSample; } - uint64_t getDuration() const override { return (m_sampling ? CTime(m_sampling, m_nSample).time() : 0); } - double* getChannelSampleBuffer(size_t index) const override; + CSignalTrial() {} + ~CSignalTrial() override { for (auto& s : m_channelSamples) { delete [] s.second; } } + bool setSamplingRate(size_t sampling) override; + bool setChannelCount(size_t count) override; + bool setChannelName(size_t index, const char* name) override; + bool setLabelIdentifier(const CIdentifier& labelID) override; + bool setSampleCount(size_t count, bool preserve) override; + size_t getSamplingRate() const override { return m_sampling; } + size_t getChannelCount() const override { return m_nChannel; } + const char* getChannelName(const size_t index) const override; + CIdentifier getLabelIdentifier() const override { return m_labelID; } + size_t getSampleCount() const override { return m_nSample; } + uint64_t getDuration() const override { return (m_sampling ? CTime(m_sampling, m_nSample).time() : 0); } + double* getChannelSampleBuffer(size_t index) const override; - _IsDerivedFromClass_Final_(ISignalTrial, OVTK_ClassId_) + _IsDerivedFromClass_Final_(ISignalTrial, OVTK_ClassId_) - protected: +protected: - std::map<size_t, std::string> m_channelNames; - std::map<size_t, double*> m_channelSamples; - size_t m_nChannel = 0; - size_t m_nSample = 0; - size_t m_nSampleReserved = 0; - size_t m_sampling = 0; - CIdentifier m_labelID = OV_UndefinedIdentifier; - }; - } // namespace Toolkit + std::map<size_t, std::string> m_channelNames; + std::map<size_t, double*> m_channelSamples; + size_t m_nChannel = 0; + size_t m_nSample = 0; + size_t m_nSampleReserved = 0; + size_t m_sampling = 0; + CIdentifier m_labelID = OV_UndefinedIdentifier; +}; +} // namespace Toolkit } // namespace OpenViBE diff --git a/toolkit/src/training/ovtkCSignalTrialSet.hpp b/toolkit/src/training/ovtkCSignalTrialSet.hpp index 895cded21bf2bd7812f2eccff592f0672475a034..c86c462bd0e83d819b2ee7d857b1b5e98b61fa14 100644 --- a/toolkit/src/training/ovtkCSignalTrialSet.hpp +++ b/toolkit/src/training/ovtkCSignalTrialSet.hpp @@ -4,25 +4,23 @@ #include <vector> -namespace OpenViBE +namespace OpenViBE { +namespace Toolkit { +class CSignalTrialSet final : public ISignalTrialSet { - namespace Toolkit - { - class CSignalTrialSet final : public ISignalTrialSet - { - public: - bool addSignalTrial(ISignalTrial& rSignalTrial) override; - bool clear() override; - size_t getSignalTrialCount() const override { return m_signalTrials.size(); } - ISignalTrial& getSignalTrial(const size_t index) const override { return *m_signalTrials[index]; } +public: + bool addSignalTrial(ISignalTrial& rSignalTrial) override; + bool clear() override; + size_t getSignalTrialCount() const override { return m_signalTrials.size(); } + ISignalTrial& getSignalTrial(const size_t index) const override { return *m_signalTrials[index]; } - _IsDerivedFromClass_Final_(ISignalTrialSet, OVTK_ClassId_) + _IsDerivedFromClass_Final_(ISignalTrialSet, OVTK_ClassId_) - protected: +protected: - mutable std::vector<ISignalTrial*> m_signalTrials; - }; + mutable std::vector<ISignalTrial*> m_signalTrials; +}; - extern OVTK_API ISignalTrialSet* createSignalTrialSet(); - } // namespace Toolkit +extern OVTK_API ISignalTrialSet* createSignalTrialSet(); +} // namespace Toolkit } // namespace OpenViBE diff --git a/unit-test/CMakeLists.txt b/unit-test/CMakeLists.txt index 7924df5244448e7a0d32212e97da8c17de8eb029..8b27b9cb79dd7d7c270aa6ec0424c5f783c4846a 100755 --- a/unit-test/CMakeLists.txt +++ b/unit-test/CMakeLists.txt @@ -13,15 +13,6 @@ IF(NOT DEFINED OVT_TEST_DATA_DIR) MESSAGE(FATAL_ERROR "Path to tests input data files is not set") ENDIF() -# ---------------------- -# Project configuration -# ---------------------- - -# Sort target into directories for better visualization in IDE -SET_PROPERTY(GLOBAL PROPERTY USE_FOLDERS ON) -SET(OVT_UNIT_TESTS_FOLDER unit-tests) -SET(OVT_TOOLS_FOLDER tools) - # --------------------- # Project dependencies # --------------------- diff --git a/unit-test/common/ovtKernelContext.cpp b/unit-test/common/ovtKernelContext.cpp index ac557b3aaf32ec6ebf62d21cb0de8bc5bea50613..b3b0595109ad4e5349029b8bb9c213c32901db76 100755 --- a/unit-test/common/ovtKernelContext.cpp +++ b/unit-test/common/ovtKernelContext.cpp @@ -27,70 +27,68 @@ using namespace OpenViBE; using namespace /*OpenViBE::*/Kernel; using namespace /*OpenViBE::*/Plugins; -namespace OpenViBE +namespace OpenViBE { +namespace Test { +bool ctx::initialize() { - namespace Test - { - bool ctx::initialize() - { #if defined TARGET_OS_Windows - const CString kernelFile = Directories::getLibDir() + "/openvibe-kernel.dll"; + const CString kernelFile = Directories::getLibDir() + "/openvibe-kernel.dll"; #elif defined TARGET_OS_Linux - const CString kernelFile = Directories::getLibDir() + "/libopenvibe-kernel.so"; + const CString kernelFile = Directories::getLibDir() + "/libopenvibe-kernel.so"; #elif defined TARGET_OS_MacOS - const CString kernelFile = Directories::getLibDir() + "/libopenvibe-kernel.dylib"; + const CString kernelFile = Directories::getLibDir() + "/libopenvibe-kernel.dylib"; #endif - CString error; - - if (!m_KernelLoader.load(kernelFile, &error)) - { - std::cerr << "ERROR: impossible to load kernel from file located at: " << kernelFile << std::endl; - std::cerr << "ERROR: kernel error: " << error << std::endl; - return false; - } + CString error; - m_KernelLoader.initialize(); - - IKernelDesc* kernelDesc{ nullptr }; - m_KernelLoader.getKernelDesc(kernelDesc); + if (!m_KernelLoader.load(kernelFile, &error)) + { + std::cerr << "ERROR: impossible to load kernel from file located at: " << kernelFile << std::endl; + std::cerr << "ERROR: kernel error: " << error << std::endl; + return false; + } - if (!kernelDesc) - { - std::cerr << "ERROR: impossible to retrieve kernel descriptor " << std::endl; - return false; - } + m_KernelLoader.initialize(); - const CString configFile = CString(Directories::getDataDir() + "/kernel/openvibe.conf"); + IKernelDesc* kernelDesc{ nullptr }; + m_KernelLoader.getKernelDesc(kernelDesc); - IKernelContext* ctx = kernelDesc->createKernel("test-kernel", configFile); + if (!kernelDesc) + { + std::cerr << "ERROR: impossible to retrieve kernel descriptor " << std::endl; + return false; + } - if (!ctx) - { - std::cerr << "ERROR: impossible to create kernel context " << std::endl; - return false; - } + const CString configFile = CString(Directories::getDataDir() + "/kernel/openvibe.conf"); - ctx->initialize(); + IKernelContext* ctx = kernelDesc->createKernel("test-kernel", configFile); - m_Context = ctx; + if (!ctx) + { + std::cerr << "ERROR: impossible to create kernel context " << std::endl; + return false; + } - return true; - } + ctx->initialize(); - bool ctx::uninitialize() - { - if (m_Context) - { - IKernelDesc* kernelDesc{ nullptr }; - m_KernelLoader.getKernelDesc(kernelDesc); - kernelDesc->releaseKernel(m_Context); - m_Context = nullptr; - } + m_Context = ctx; - m_KernelLoader.uninitialize(); - m_KernelLoader.unload(); + return true; +} - return true; - } - } // namespace Test +bool ctx::uninitialize() +{ + if (m_Context) + { + IKernelDesc* kernelDesc{ nullptr }; + m_KernelLoader.getKernelDesc(kernelDesc); + kernelDesc->releaseKernel(m_Context); + m_Context = nullptr; + } + + m_KernelLoader.uninitialize(); + m_KernelLoader.unload(); + + return true; +} +} // namespace Test } // namespace OpenViBE diff --git a/unit-test/openvibe-kernel/CMakeLists.txt b/unit-test/openvibe-kernel/CMakeLists.txt index b2af529188e83aed17deaa061386a4dcf8aaff6e..1fdb9c94f7266d1f462fa456c6e4c3fb58076a42 100755 --- a/unit-test/openvibe-kernel/CMakeLists.txt +++ b/unit-test/openvibe-kernel/CMakeLists.txt @@ -23,9 +23,7 @@ PROJECT(openvibe-kernel-test) # --------------------------------- # Target macros -# Defines target operating system -# Defines target architecture -# Defines target compiler +# Defines target operating system, architecture and compiler # --------------------------------- SET_BUILD_PLATFORM() @@ -56,7 +54,7 @@ CREATE_TEST_SOURCELIST (Tests ADD_EXECUTABLE(${PROJECT_NAME} ${Tests}) INCLUDE("FindOpenViBE") INCLUDE("FindOpenViBECommon") -SET_PROPERTY(TARGET ${PROJECT_NAME} PROPERTY FOLDER ${OVT_UNIT_TESTS_FOLDER}) +SET_PROPERTY(TARGET ${PROJECT_NAME} PROPERTY FOLDER ${TESTS_FOLDER}) TARGET_LINK_LIBRARIES(${PROJECT_NAME} ${OVT_UNIT_TOOLKIT_LIB} ${GTEST_BOTH_LIBRARIES} ${OV_LIBS}) # Add test without parameter to driver diff --git a/unit-test/openvibe-module-csv/CMakeLists.txt b/unit-test/openvibe-module-csv/CMakeLists.txt index 6c3deb578034ef924c31002e17cce9a8bd86582b..b2e6968665edefbd41e2c984952e755007e118a4 100755 --- a/unit-test/openvibe-module-csv/CMakeLists.txt +++ b/unit-test/openvibe-module-csv/CMakeLists.txt @@ -23,9 +23,7 @@ PROJECT(openvibe-module-csv-test) # --------------------------------- # Target macros -# Defines target operating system -# Defines target architecture -# Defines target compiler +# Defines target operating system, architecture and compiler # --------------------------------- SET_BUILD_PLATFORM() @@ -59,7 +57,7 @@ ADD_EXECUTABLE(${PROJECT_NAME} ${Tests}) INCLUDE("FindOpenViBE") INCLUDE("FindOpenViBEModuleCSV") -SET_PROPERTY(TARGET ${PROJECT_NAME} PROPERTY FOLDER ${OVT_UNIT_TESTS_FOLDER}) +SET_PROPERTY(TARGET ${PROJECT_NAME} PROPERTY FOLDER ${TESTS_FOLDER}) # set(OV_MODULE_CSV "C:/gitdir/build/openvibe-sdk-debug/modules/csv/openvibe-module-csv") TARGET_LINK_LIBRARIES(${PROJECT_NAME} ${OVT_UNIT_TOOLKIT_LIB} ${GTEST_BOTH_LIBRARIES} ${OV_LIBS} ${OV_MODULE_CSV}) diff --git a/unit-test/openvibe-module-csv/uoCSVReaderTest.cpp b/unit-test/openvibe-module-csv/uoCSVReaderTest.cpp index d0a87ae05617d57f160550a44f2bdf7a507b2af8..b51c4d7dde4887520c41aaf73e4de87becb8d8d9 100755 --- a/unit-test/openvibe-module-csv/uoCSVReaderTest.cpp +++ b/unit-test/openvibe-module-csv/uoCSVReaderTest.cpp @@ -36,38 +36,37 @@ struct SSignalFile std::vector<std::pair<std::pair<double, double>, std::vector<double>>> m_data; }; -namespace -{ - std::string dataDirectory = ""; +namespace { +std::string dataDirectory = ""; - const struct SSignalFile SIMPLE_SIGNAL_FILE = { - { "Time Signal" }, - 32, - 8, - { - { - { 0.00000, 0.25000 }, - { 0.00000, 0.03125, 0.06250, 0.09375, 0.125, 0.15625, 0.1875, 0.21875 } - }, - { - { 0.250000, 0.500000 }, - { 0.250000, 0.281250, 0.312500, 0.343750, 0.375000, 0.406250, 0.437500, 0.468750 } - }, - { - { 0.500000, 0.750000 }, - { 0.500000, 0.531250, 0.562500, 0.593750, 0.625000, 0.656250, 0.687500, 0.718750 } - }, - } - }; - - void compareChunks(const std::pair<std::pair<double, double>, std::vector<double>>& expected, const SMatrixChunk& actual) +const struct SSignalFile SIMPLE_SIGNAL_FILE = { + { "Time Signal" }, + 32, + 8, { - ASSERT_EQ(expected.first.first, actual.startTime); - ASSERT_EQ(expected.first.second, actual.endTime); - ASSERT_EQ(expected.second.size(), actual.matrix.size()); - for (size_t sample = 0; sample < expected.second.size(); ++sample) { ASSERT_EQ(expected.second[sample], actual.matrix[sample]); } + { + { 0.00000, 0.25000 }, + { 0.00000, 0.03125, 0.06250, 0.09375, 0.125, 0.15625, 0.1875, 0.21875 } + }, + { + { 0.250000, 0.500000 }, + { 0.250000, 0.281250, 0.312500, 0.343750, 0.375000, 0.406250, 0.437500, 0.468750 } + }, + { + { 0.500000, 0.750000 }, + { 0.500000, 0.531250, 0.562500, 0.593750, 0.625000, 0.656250, 0.687500, 0.718750 } + }, } -} // namespace +}; + +void compareChunks(const std::pair<std::pair<double, double>, std::vector<double>>& expected, const SMatrixChunk& actual) +{ + ASSERT_EQ(expected.first.first, actual.startTime); + ASSERT_EQ(expected.first.second, actual.endTime); + ASSERT_EQ(expected.second.size(), actual.matrix.size()); + for (size_t sample = 0; sample < expected.second.size(); ++sample) { ASSERT_EQ(expected.second[sample], actual.matrix[sample]); } +} +} // namespace TEST(CSV_Reader_Test_Case, signalReaderUNIXEndlines) { diff --git a/unit-test/openvibe-module-ebml/CMakeLists.txt b/unit-test/openvibe-module-ebml/CMakeLists.txt index 576c6c075481382f1499f9d85eebabf0e4d50220..b59a4ebc82d280ebc2733f68b4a1f4d6801204bf 100755 --- a/unit-test/openvibe-module-ebml/CMakeLists.txt +++ b/unit-test/openvibe-module-ebml/CMakeLists.txt @@ -23,9 +23,7 @@ PROJECT(openvibe-module-ebml-test) # --------------------------------- # Target macros -# Defines target operating system -# Defines target architecture -# Defines target compiler +# Defines target operating system, architecture and compiler # --------------------------------- SET_BUILD_PLATFORM() @@ -58,7 +56,7 @@ ADD_EXECUTABLE(${PROJECT_NAME} ${Tests}) INCLUDE("FindOpenViBE") INCLUDE("FindOpenViBECommon") INCLUDE("FindOpenViBEModuleEBML") -SET_PROPERTY(TARGET ${PROJECT_NAME} PROPERTY FOLDER ${OVT_UNIT_TESTS_FOLDER}) +SET_PROPERTY(TARGET ${PROJECT_NAME} PROPERTY FOLDER ${TESTS_FOLDER}) TARGET_LINK_LIBRARIES(${PROJECT_NAME} ${OVT_UNIT_TOOLKIT_LIB} ${OV_MODULE_EBML}) # Add test without parameter to driver diff --git a/unit-test/openvibe-module-ebml/uoEBMLWriterTest.cpp b/unit-test/openvibe-module-ebml/uoEBMLWriterTest.cpp index 4fdd8ac8164eb9a1b3adc3333854dc7ee466d31a..c31b789746c9cac86e982a3934a0fc897a2dd9f8 100755 --- a/unit-test/openvibe-module-ebml/uoEBMLWriterTest.cpp +++ b/unit-test/openvibe-module-ebml/uoEBMLWriterTest.cpp @@ -48,13 +48,7 @@ class CWriterCallBack : public EBML::IWriterCallBack public: CWriterCallBack(const char* filename) { m_file = std::fopen(filename, "wb"); } - ~CWriterCallBack() override - { - if (m_file) - { - std::fclose(m_file); // in case release is not called - } - } + ~CWriterCallBack() override { if (m_file) { std::fclose(m_file); } } // in case release is not called void write(const void* buffer, const size_t size) override { if (m_file) { std::fwrite(buffer, size_t(size), 1, m_file); } } diff --git a/unit-test/openvibe-module-fs/CMakeLists.txt b/unit-test/openvibe-module-fs/CMakeLists.txt index d75ff2d1730e5bf57187a47fce3055f97adab898..5b4ad2a8da9b885b655108f0a4167d02877c551a 100755 --- a/unit-test/openvibe-module-fs/CMakeLists.txt +++ b/unit-test/openvibe-module-fs/CMakeLists.txt @@ -30,6 +30,8 @@ INCLUDE("FindThirdPartyBoost") #INCLUDE("FindThirdPartyBoost_System") INCLUDE("FindThirdPartyBoost_FileSystem") +SET_PROPERTY(TARGET ${PROJECT_NAME} PROPERTY FOLDER ${TESTS_FOLDER}) # Place project in folder unit-test (for some IDE) + TARGET_LINK_LIBRARIES(${PROJECT_NAME} ${GTEST_BOTH_LIBRARIES}) ADD_DEFINITIONS("-DDATA_DIR=\"${CMAKE_CURRENT_SOURCE_DIR}/data\"") @@ -40,9 +42,7 @@ PROJECT(openvibe-module-fs-test) # --------------------------------- # Target macros -# Defines target operating system -# Defines target architecture -# Defines target compiler +# Defines target operating system, architecture and compiler # --------------------------------- SET_BUILD_PLATFORM() @@ -75,7 +75,7 @@ ADD_EXECUTABLE(${PROJECT_NAME} ${Tests}) INCLUDE("FindOpenViBE") INCLUDE("FindOpenViBECommon") INCLUDE("FindOpenViBEModuleFS") -SET_PROPERTY(TARGET ${PROJECT_NAME} PROPERTY FOLDER ${OVT_UNIT_TESTS_FOLDER}) +SET_PROPERTY(TARGET ${PROJECT_NAME} PROPERTY FOLDER ${TESTS_FOLDER}) TARGET_LINK_LIBRARIES(${PROJECT_NAME} ${OVT_UNIT_TOOLKIT_LIB} ${OV_MODULE_FS}) # Add test without parameter to driver diff --git a/unit-test/openvibe-module-fs/uoEntryEnumeratorTest.cpp b/unit-test/openvibe-module-fs/uoEntryEnumeratorTest.cpp index 2dff3119addde8976c46aaf6f04768c5f345b83d..d1d288d29f38b5018a266ebe41e7923b5d9012f3 100755 --- a/unit-test/openvibe-module-fs/uoEntryEnumeratorTest.cpp +++ b/unit-test/openvibe-module-fs/uoEntryEnumeratorTest.cpp @@ -33,7 +33,6 @@ public: bool callback(FS::IEntryEnumerator::IEntry& rEntry, FS::IEntryEnumerator::IAttributes& rAttributes) override { if (rAttributes.isFile()) { m_files.push_back(rEntry.getName()); } - return true; } diff --git a/unit-test/openvibe-module-fs/uoFilesTest.cpp b/unit-test/openvibe-module-fs/uoFilesTest.cpp index e4018e48487b925491904d41f064930047652c52..68a45cbc1c333bb16d331ed778a9924c6e4bdce2 100755 --- a/unit-test/openvibe-module-fs/uoFilesTest.cpp +++ b/unit-test/openvibe-module-fs/uoFilesTest.cpp @@ -113,7 +113,7 @@ int uoFilesTest(int /*argc*/, char* argv[]) FS::Files::openOFStream(ostream2, testFile2.c_str()); OVT_ASSERT(FS::Files::fileExists(testFile2.c_str()), "Failure to create file in subfolder"); OVT_ASSERT(ostream2.is_open(), "Failure to open file"); - ostream2.close(); + ostream2.close(); // copy folder testDir = outputDirectory + "uoFilesTest"; FS::Files::copyDirectory(testDir.c_str(), testTargetDir.c_str()); diff --git a/unit-test/openvibe-module-socket/CMakeLists.txt b/unit-test/openvibe-module-socket/CMakeLists.txt index 51f5d2e78de7e42ad7dd3f2268b5b0ea1f668b75..088c05509a9276fb8aba7e8b74d633527e8adc8b 100755 --- a/unit-test/openvibe-module-socket/CMakeLists.txt +++ b/unit-test/openvibe-module-socket/CMakeLists.txt @@ -23,9 +23,7 @@ PROJECT(openvibe-module-socket-test) # --------------------------------- # Target macros -# Defines target operating system -# Defines target architecture -# Defines target compiler +# Defines target operating system, architecture and compiler # --------------------------------- SET_BUILD_PLATFORM() @@ -59,7 +57,7 @@ ADD_EXECUTABLE(${PROJECT_NAME} ${Tests}) INCLUDE("FindOpenViBE") INCLUDE("FindOpenViBECommon") INCLUDE("FindOpenViBEModuleSocket") -SET_PROPERTY(TARGET ${PROJECT_NAME} PROPERTY FOLDER ${OVT_UNIT_TESTS_FOLDER}) +SET_PROPERTY(TARGET ${PROJECT_NAME} PROPERTY FOLDER ${TESTS_FOLDER}) TARGET_LINK_LIBRARIES(${PROJECT_NAME} ${OVT_UNIT_TOOLKIT_LIB} ${OV_MODULE_SOCKET}) # Add test without parameter to driver diff --git a/unit-test/openvibe-module-socket/uoSocketClientServerASyncCommunicationTest.cpp b/unit-test/openvibe-module-socket/uoSocketClientServerASyncCommunicationTest.cpp index 83cbd00caa63949cd8737b109dd0b1affca7d096..ae431bf96a13edc0be6da826dc17277782d71f73 100755 --- a/unit-test/openvibe-module-socket/uoSocketClientServerASyncCommunicationTest.cpp +++ b/unit-test/openvibe-module-socket/uoSocketClientServerASyncCommunicationTest.cpp @@ -31,68 +31,67 @@ #include "ovtAssert.h" -namespace +namespace { +std::condition_variable gServerStartedCondVar; +std::mutex gServerStartedMutex; +std::vector<std::string> gReceivedData; +bool gServerStarted = false; + +// server callback run from a child thread +void onServerListening(const int port, const size_t expectedPacketCount) { - std::condition_variable gServerStartedCondVar; - std::mutex gServerStartedMutex; - std::vector<std::string> gReceivedData; - bool gServerStarted = false; + gReceivedData.clear(); - // server callback run from a child thread - void onServerListening(const int port, const size_t expectedPacketCount) - { - gReceivedData.clear(); + Socket::IConnection* clientConnection = nullptr; - Socket::IConnection* clientConnection = nullptr; + // create server + Socket::IConnectionServer* server = Socket::createConnectionServer(); + server->listen(port); - // create server - Socket::IConnectionServer* server = Socket::createConnectionServer(); - server->listen(port); + // keep the scope braces here, as it ensures mutex is released + { + std::lock_guard<std::mutex> lockOnServerStart(gServerStartedMutex); + gServerStarted = true; + } - // keep the scope braces here, as it ensures mutex is released - { - std::lock_guard<std::mutex> lockOnServerStart(gServerStartedMutex); - gServerStarted = true; - } + // notify main thread that the server is created so that it can connect a single client + gServerStartedCondVar.notify_one(); - // notify main thread that the server is created so that it can connect a single client - gServerStartedCondVar.notify_one(); + // loop until all packet are received + while (gReceivedData.size() < expectedPacketCount) + { + if (server->isReadyToReceive()) { clientConnection = server->accept(); } - // loop until all packet are received - while (gReceivedData.size() < expectedPacketCount) + if (clientConnection && clientConnection->isReadyToReceive()) { - if (server->isReadyToReceive()) { clientConnection = server->accept(); } - - if (clientConnection && clientConnection->isReadyToReceive()) - { - size_t dataSize = 0; - size_t bytesToReceive = sizeof(dataSize); - size_t bytesReceived = 0; - char dataBuffer[32]; + size_t dataSize = 0; + size_t bytesToReceive = sizeof(dataSize); + size_t bytesReceived = 0; + char dataBuffer[32]; - // first receive data size - while (bytesReceived < bytesToReceive) { bytesReceived += clientConnection->receiveBuffer(&dataSize, bytesToReceive - bytesReceived); } + // first receive data size + while (bytesReceived < bytesToReceive) { bytesReceived += clientConnection->receiveBuffer(&dataSize, bytesToReceive - bytesReceived); } - // then receive data - bytesToReceive = dataSize; - bytesReceived = 0; + // then receive data + bytesToReceive = dataSize; + bytesReceived = 0; - while (bytesReceived < bytesToReceive) { bytesReceived += clientConnection->receiveBuffer(dataBuffer, bytesToReceive - bytesReceived); } + while (bytesReceived < bytesToReceive) { bytesReceived += clientConnection->receiveBuffer(dataBuffer, bytesToReceive - bytesReceived); } - gReceivedData.push_back(std::string(dataBuffer, dataSize)); - } + gReceivedData.push_back(std::string(dataBuffer, dataSize)); } - - server->release(); } - void sendData(Socket::IConnectionClient* client, void* data, const size_t size) - { - const size_t bytesToSend = size; - size_t bytesSent = 0; + server->release(); +} - while (bytesSent < bytesToSend) { bytesSent += client->sendBuffer(data, bytesToSend - bytesSent); } - } +void sendData(Socket::IConnectionClient* client, void* data, const size_t size) +{ + const size_t bytesToSend = size; + size_t bytesSent = 0; + + while (bytesSent < bytesToSend) { bytesSent += client->sendBuffer(data, bytesToSend - bytesSent); } +} } // namespace int uoSocketClientServerASyncCommunicationTest(int argc, char* argv[]) diff --git a/unit-test/openvibe-module-socket/uoSocketClientServerBaseTest.cpp b/unit-test/openvibe-module-socket/uoSocketClientServerBaseTest.cpp index 55baf01a152a7cbd3c2e9bcb4bd1898c77dece9f..845470e787827322381a3e51ae830cbac1b8fbb1 100755 --- a/unit-test/openvibe-module-socket/uoSocketClientServerBaseTest.cpp +++ b/unit-test/openvibe-module-socket/uoSocketClientServerBaseTest.cpp @@ -33,7 +33,7 @@ int uoSocketClientServerBaseTest(int argc, char* argv[]) const std::string name = argv[1]; char* end; const size_t port = strtol(argv[2], &end, 10); - + // basic tests on server and clients Socket::IConnectionServer* server = Socket::createConnectionServer(); @@ -68,7 +68,7 @@ int uoSocketClientServerBaseTest(int argc, char* argv[]) OVT_ASSERT(client->connect(name.c_str(), guessedPort) && client->isConnected(), "Failure to connect to server"); OVT_ASSERT(client->close() && !client->isConnected(), "Failure to disconnect"); OVT_ASSERT(server->close() && !server->isConnected(), "Failure to close connection"); - + // Release ressources server->release(); diff --git a/unit-test/openvibe-module-socket/uoSocketClientServerSyncCommunicationTest.cpp b/unit-test/openvibe-module-socket/uoSocketClientServerSyncCommunicationTest.cpp index 815684aff44c6c8062912f9da9435e91765bda82..2ce1aff3206f99e2f284795336e1050e9daa8f3c 100755 --- a/unit-test/openvibe-module-socket/uoSocketClientServerSyncCommunicationTest.cpp +++ b/unit-test/openvibe-module-socket/uoSocketClientServerSyncCommunicationTest.cpp @@ -31,62 +31,61 @@ #include "ovtAssert.h" -namespace +namespace { +std::condition_variable gServerStartedCondVar; +std::mutex gServerStartedMutex; +std::condition_variable gClientConnectedCondVar; +std::mutex gClientConnectedMutex; +std::vector<std::string> gReceivedData; +bool gServerStarted = false; +bool gClientConnected = false; + +// server callback run from a child thread +void onServerListening(const int port, const size_t packetCount) { - std::condition_variable gServerStartedCondVar; - std::mutex gServerStartedMutex; - std::condition_variable gClientConnectedCondVar; - std::mutex gClientConnectedMutex; - std::vector<std::string> gReceivedData; - bool gServerStarted = false; - bool gClientConnected = false; - - // server callback run from a child thread - void onServerListening(const int port, const size_t packetCount) - { - // only the server side modifies gReceivedData thus no need to handle race condition - gReceivedData.clear(); + // only the server side modifies gReceivedData thus no need to handle race condition + gReceivedData.clear(); - Socket::IConnection* clientConnection = nullptr; + Socket::IConnection* clientConnection = nullptr; - // create server - Socket::IConnectionServer* server = Socket::createConnectionServer(); - server->listen(port); + // create server + Socket::IConnectionServer* server = Socket::createConnectionServer(); + server->listen(port); - // keep the scope braces here, as it ensures mutex is released - { - std::lock_guard<std::mutex> lockOnServerStart(gServerStartedMutex); - gServerStarted = true; - } + // keep the scope braces here, as it ensures mutex is released + { + std::lock_guard<std::mutex> lockOnServerStart(gServerStartedMutex); + gServerStarted = true; + } - gServerStartedCondVar.notify_one(); + gServerStartedCondVar.notify_one(); - // connect clients - while (!clientConnection) { if (server->isReadyToReceive()) { clientConnection = server->accept(); } } + // connect clients + while (!clientConnection) { if (server->isReadyToReceive()) { clientConnection = server->accept(); } } - // keep the scope braces here, as it ensures mutex is released - { - std::lock_guard<std::mutex> lockOnClientConnected(gClientConnectedMutex); - gClientConnected = true; - } + // keep the scope braces here, as it ensures mutex is released + { + std::lock_guard<std::mutex> lockOnClientConnected(gClientConnectedMutex); + gClientConnected = true; + } - gClientConnectedCondVar.notify_one(); + gClientConnectedCondVar.notify_one(); - while (gReceivedData.size() < packetCount) + while (gReceivedData.size() < packetCount) + { + if (clientConnection->isReadyToReceive()) { - if (clientConnection->isReadyToReceive()) - { - size_t dataSize = 0; - char dataBuffer[64]; - clientConnection->receiveBufferBlocking(&dataSize, sizeof(dataSize)); - clientConnection->receiveBufferBlocking(dataBuffer, dataSize); - gReceivedData.push_back(std::string(dataBuffer, dataSize)); - } + size_t dataSize = 0; + char dataBuffer[64]; + clientConnection->receiveBufferBlocking(&dataSize, sizeof(dataSize)); + clientConnection->receiveBufferBlocking(dataBuffer, dataSize); + gReceivedData.push_back(std::string(dataBuffer, dataSize)); } - - server->release(); } -} // namespace + + server->release(); +} +} // namespace int uoSocketClientServerSyncCommunicationTest(int argc, char* argv[]) { diff --git a/unit-test/openvibe-module-system/CMakeLists.txt b/unit-test/openvibe-module-system/CMakeLists.txt index 16619850136fa444ce032c7735448506d53e0883..cec604c9fd14222230d0677269d1fc83a8e8785a 100755 --- a/unit-test/openvibe-module-system/CMakeLists.txt +++ b/unit-test/openvibe-module-system/CMakeLists.txt @@ -23,9 +23,7 @@ PROJECT(openvibe-module-system-test) # --------------------------------- # Target macros -# Defines target operating system -# Defines target architecture -# Defines target compiler +# Defines target operating system, architecture and compiler # --------------------------------- SET_BUILD_PLATFORM() @@ -58,7 +56,7 @@ ADD_EXECUTABLE(${PROJECT_NAME} ${Tests}) INCLUDE("FindOpenViBE") INCLUDE("FindOpenViBECommon") INCLUDE("FindOpenViBEModuleSystem") -SET_PROPERTY(TARGET ${PROJECT_NAME} PROPERTY FOLDER ${OVT_UNIT_TESTS_FOLDER}) +SET_PROPERTY(TARGET ${PROJECT_NAME} PROPERTY FOLDER ${TESTS_FOLDER}) TARGET_LINK_LIBRARIES(${PROJECT_NAME} ${OVT_UNIT_TOOLKIT_LIB} ${OV_LIBS} ${GTEST_BOTH_LIBRARIES}) # Add test without parameter to driver diff --git a/unit-test/openvibe-module-system/uoDynamicModuleTest.cpp b/unit-test/openvibe-module-system/uoDynamicModuleTest.cpp index 41fc5a1af6ad96dcec3e022708899ca1f0db843d..8b611f7c5cd5f76105c0ffe43294fbaa0ef35221 100755 --- a/unit-test/openvibe-module-system/uoDynamicModuleTest.cpp +++ b/unit-test/openvibe-module-system/uoDynamicModuleTest.cpp @@ -31,15 +31,14 @@ using namespace System; -namespace -{ +namespace { #if defined TARGET_OS_Windows - //const std::string LIB_PATH = OV_CMAKE_PATH_LIB; +//const std::string LIB_PATH = OV_CMAKE_PATH_LIB; - // Microsoft specific - const std::string EXISTING_MODULE_NAME = "NTDLL.dll"; +// Microsoft specific +const std::string EXISTING_MODULE_NAME = "NTDLL.dll"; - std::string existingModulePath; +std::string existingModulePath; #if defined _WIN64 #define CSIDL_SYSTEM_PLATFORM CSIDL_SYSTEM @@ -47,34 +46,30 @@ namespace #define CSIDL_SYSTEM_PLATFORM CSIDL_SYSTEMX86 #endif - std::string existingModulePathName; - const std::string NON_EXISTING_MODULE_NAME = "randomRandomRandom.dll"; - - const std::string NON_EXISTING_SYMBOL = "nonExistingSymbol"; - - const std::string EXISTING_ENVIRONMENT_PATH = "PATH"; - - const std::string EXISTING_REGISTRY_MODULE_NAME = EXISTING_MODULE_NAME; - const std::string SYMBOL_NAME_NTDLL = "toupper"; +std::string existingModulePathName; +const std::string NON_EXISTING_MODULE_NAME = "randomRandomRandom.dll"; +const std::string NON_EXISTING_SYMBOL = "nonExistingSymbol"; +const std::string EXISTING_ENVIRONMENT_PATH = "PATH"; +const std::string EXISTING_REGISTRY_MODULE_NAME = EXISTING_MODULE_NAME; +const std::string SYMBOL_NAME_NTDLL = "toupper"; - const HKEY EXISTING_REGISTRY_KEY = HKEY_LOCAL_MACHINE; // 0x80000002 - const HKEY NON_EXISTING_REGISTRY_KEY = HKEY(ULONG_PTR(LONG(0x800000FF))); +const HKEY EXISTING_REGISTRY_KEY = HKEY_LOCAL_MACHINE; // 0x80000002 +const HKEY NON_EXISTING_REGISTRY_KEY = HKEY(ULONG_PTR(LONG(0x800000FF))); - const std::string EXISTING_REGISTRY_PATH = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Installer"; // Present on all Windows versions - const std::string NON_EXISTING_REGISTRY_PATH = "SOFTWARE\\Random\\Random\\Random"; +const std::string EXISTING_REGISTRY_PATH = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Installer"; // Present on all Windows versions +const std::string NON_EXISTING_REGISTRY_PATH = "SOFTWARE\\Random\\Random\\Random"; - int (*toupperSymbol)(int c); - bool (*randomRandomRandomSymbol)(int number); +int (*toupperSymbol)(int c); +bool (*randomRandomRandomSymbol)(int number); #elif defined TARGET_OS_Linux || defined TARGET_OS_MacOS - static const std::string EXISTING_SYMBOL = "createCSVLib"; - static const std::string NON_EXISTING_SYMBOL = "nonExistingSymbol"; - - static const std::string LIB_PATH = OV_CMAKE_PATH_LIB; - static const std::string EXISTING_MODULE_NAME = "libopenvibe-module-csv.so"; - static const std::string existingModulePath = LIB_PATH + "/"; - static const std::string existingModulePathName = existingModulePath + EXISTING_MODULE_NAME; - static const std::string NON_EXISTING_MODULE_NAME = "randomRandomRandom.so"; +static const std::string EXISTING_SYMBOL = "createCSVLib"; +static const std::string NON_EXISTING_SYMBOL = "nonExistingSymbol"; +static const std::string LIB_PATH = OV_CMAKE_PATH_LIB; +static const std::string EXISTING_MODULE_NAME = "libopenvibe-module-csv.so"; +static const std::string existingModulePath = LIB_PATH + "/"; +static const std::string existingModulePathName = existingModulePath + EXISTING_MODULE_NAME; +static const std::string NON_EXISTING_MODULE_NAME = "randomRandomRandom.so"; #endif } // namespace diff --git a/unit-test/openvibe-module-xml/CMakeLists.txt b/unit-test/openvibe-module-xml/CMakeLists.txt index e006198a1db44afe85be425e33e347f8fa9cfdef..585c8d4fc3cf1317c4b1cd43e53e8bd3e0146724 100755 --- a/unit-test/openvibe-module-xml/CMakeLists.txt +++ b/unit-test/openvibe-module-xml/CMakeLists.txt @@ -28,6 +28,8 @@ FUNCTION(SETUP_TEST) INCLUDE("FindOpenViBEModuleFS") INCLUDE("FindThirdPartyBoost") INCLUDE("FindThirdPartyBoost_FileSystem") + + SET_PROPERTY(TARGET ${PROJECT_NAME} PROPERTY FOLDER ${TESTS_FOLDER}) # Place project in folder unit-test (for some IDE) TARGET_LINK_LIBRARIES(${PROJECT_NAME} ${GTEST_BOTH_LIBRARIES}) diff --git a/unit-test/openvibe-module-xml/uoXMLWriterTest.cpp b/unit-test/openvibe-module-xml/uoXMLWriterTest.cpp index 17c9f8b4cf92b4e6f95a5d39c3676bc41571f457..c549e0925131fb3238a1e7d96b2e2cd3fb9d1cc4 100755 --- a/unit-test/openvibe-module-xml/uoXMLWriterTest.cpp +++ b/unit-test/openvibe-module-xml/uoXMLWriterTest.cpp @@ -36,14 +36,7 @@ class CWriterCallBack : public XML::IWriterCallBack public: CWriterCallBack(const char* filename) { m_file = FS::Files::open(filename, "wb"); } - - ~CWriterCallBack() override - { - if (m_file) - { - std::fclose(m_file); // in case release is not called - } - } + ~CWriterCallBack() override { if (m_file) { std::fclose(m_file); } } // in case release is not called void write(const char* outputData) override { if (m_file) { std::fputs(outputData, m_file); } } diff --git a/unit-test/openvibe-plugin-stream-codecs/uoStreamedMatrixTest.cpp b/unit-test/openvibe-plugin-stream-codecs/uoStreamedMatrixTest.cpp index 48b82f5d8aba63e45da25f255c0cc6c0434ec113..e5b71ef79c743dcd99fbf51451d66a3e1dabd06f 100755 --- a/unit-test/openvibe-plugin-stream-codecs/uoStreamedMatrixTest.cpp +++ b/unit-test/openvibe-plugin-stream-codecs/uoStreamedMatrixTest.cpp @@ -12,130 +12,124 @@ using namespace OpenViBE; using namespace /*OpenViBE::*/Kernel; -namespace -{ - const char* kernelConfig = nullptr; - - class StreamedMatrixTest : public testing::Test - { - protected: +namespace { +const char* kernelConfig = nullptr; - StreamedMatrixTest() { } - ~StreamedMatrixTest() override { } - - void SetUp() override - { - m_kernelCtx.initialize(); - m_kernelCtx->getPluginManager().addPluginsFromFiles( - m_kernelCtx->getConfigurationManager().expand("${Path_Lib}/*openvibe-plugins-sdk-stream-codecs*")); +class StreamedMatrixTest : public testing::Test +{ +protected: - m_decoderId = OV_UndefinedIdentifier; - m_decoderId = m_kernelCtx->getAlgorithmManager().createAlgorithm(OVP_GD_ClassId_Algorithm_StreamedMatrixDecoder); - ASSERT_NE(OV_UndefinedIdentifier, m_decoderId); + StreamedMatrixTest() { } + ~StreamedMatrixTest() override { } - m_encoderId = OV_UndefinedIdentifier; - m_encoderId = m_kernelCtx->getAlgorithmManager().createAlgorithm(OVP_GD_ClassId_Algorithm_StreamedMatrixEncoder); - ASSERT_NE(OV_UndefinedIdentifier, m_encoderId); - } + void SetUp() override + { + m_kernelCtx.initialize(); + m_kernelCtx->getPluginManager().addPluginsFromFiles(m_kernelCtx->getConfigurationManager().expand("${Path_Lib}/*openvibe-plugins-sdk-stream-codecs*")); - void TearDown() override - { - ASSERT_TRUE(m_kernelCtx->getAlgorithmManager().releaseAlgorithm(m_decoderId)); - m_decoderId = OV_UndefinedIdentifier; - ASSERT_TRUE(m_kernelCtx->getAlgorithmManager().releaseAlgorithm(m_encoderId)); - m_encoderId = OV_UndefinedIdentifier; - m_kernelCtx.uninitialize(); - } + m_decoderId = OV_UndefinedIdentifier; + m_decoderId = m_kernelCtx->getAlgorithmManager().createAlgorithm(OVP_GD_ClassId_Algorithm_StreamedMatrixDecoder); + ASSERT_NE(OV_UndefinedIdentifier, m_decoderId); - CIdentifier m_decoderId; - CIdentifier m_encoderId; - OpenViBE::Test::ctx m_kernelCtx; - }; + m_encoderId = OV_UndefinedIdentifier; + m_encoderId = m_kernelCtx->getAlgorithmManager().createAlgorithm(OVP_GD_ClassId_Algorithm_StreamedMatrixEncoder); + ASSERT_NE(OV_UndefinedIdentifier, m_encoderId); + } - TEST_F(StreamedMatrixTest, test_init) + void TearDown() override { - auto& decoder = m_kernelCtx->getAlgorithmManager().getAlgorithm(m_decoderId); - auto& encoder = m_kernelCtx->getAlgorithmManager().getAlgorithm(m_encoderId); - EXPECT_TRUE(decoder.initialize()); - EXPECT_TRUE(encoder.initialize()); - EXPECT_TRUE(decoder.uninitialize()); - EXPECT_TRUE(encoder.uninitialize()); + ASSERT_TRUE(m_kernelCtx->getAlgorithmManager().releaseAlgorithm(m_decoderId)); + m_decoderId = OV_UndefinedIdentifier; + ASSERT_TRUE(m_kernelCtx->getAlgorithmManager().releaseAlgorithm(m_encoderId)); + m_encoderId = OV_UndefinedIdentifier; + m_kernelCtx.uninitialize(); } - TEST_F(StreamedMatrixTest, matrix_decoder_does_not_crash_when_given_an_empty_matrix) - { - auto& encoder = m_kernelCtx->getAlgorithmManager().getAlgorithm(m_encoderId); - auto& decoder = m_kernelCtx->getAlgorithmManager().getAlgorithm(m_decoderId); - EXPECT_TRUE(encoder.initialize()); - EXPECT_TRUE(decoder.initialize()); - CMatrix mat; - ASSERT_TRUE(mat.setDimensionCount(1)); - ASSERT_TRUE(mat.setDimensionSize(0, 0)); + CIdentifier m_decoderId; + CIdentifier m_encoderId; + OpenViBE::Test::ctx m_kernelCtx; +}; - TParameterHandler<const IMatrix*> iMatrix(encoder.getInputParameter(OVP_GD_Algorithm_StreamedMatrixEncoder_InputParameterId_Matrix)); - TParameterHandler<const IMemoryBuffer*> oBuffer( - encoder.getOutputParameter(OVP_GD_Algorithm_StreamedMatrixEncoder_OutputParameterId_EncodedMemoryBuffer)); - TParameterHandler<const IMemoryBuffer*> - iBuffer(decoder.getInputParameter(OVP_GD_Algorithm_StreamedMatrixDecoder_InputParameterId_MemoryBufferToDecode)); - TParameterHandler<const IMatrix*> oMatrix(decoder.getOutputParameter(OVP_GD_Algorithm_StreamedMatrixDecoder_OutputParameterId_Matrix)); +TEST_F(StreamedMatrixTest, test_init) +{ + auto& decoder = m_kernelCtx->getAlgorithmManager().getAlgorithm(m_decoderId); + auto& encoder = m_kernelCtx->getAlgorithmManager().getAlgorithm(m_encoderId); + EXPECT_TRUE(decoder.initialize()); + EXPECT_TRUE(encoder.initialize()); + EXPECT_TRUE(decoder.uninitialize()); + EXPECT_TRUE(encoder.uninitialize()); +} + +TEST_F(StreamedMatrixTest, matrix_decoder_does_not_crash_when_given_an_empty_matrix) +{ + auto& encoder = m_kernelCtx->getAlgorithmManager().getAlgorithm(m_encoderId); + auto& decoder = m_kernelCtx->getAlgorithmManager().getAlgorithm(m_decoderId); + EXPECT_TRUE(encoder.initialize()); + EXPECT_TRUE(decoder.initialize()); + CMatrix mat; + ASSERT_TRUE(mat.setDimensionCount(1)); + ASSERT_TRUE(mat.setDimensionSize(0, 0)); - iMatrix = &mat; - iBuffer.setReferenceTarget(oBuffer); + TParameterHandler<const IMatrix*> iMatrix(encoder.getInputParameter(OVP_GD_Algorithm_StreamedMatrixEncoder_InputParameterId_Matrix)); + TParameterHandler<const IMemoryBuffer*> oBuffer(encoder.getOutputParameter(OVP_GD_Algorithm_StreamedMatrixEncoder_OutputParameterId_EncodedMemoryBuffer)); + TParameterHandler<const IMemoryBuffer*> iBuffer(decoder.getInputParameter(OVP_GD_Algorithm_StreamedMatrixDecoder_InputParameterId_MemoryBufferToDecode)); + TParameterHandler<const IMatrix*> oMatrix(decoder.getOutputParameter(OVP_GD_Algorithm_StreamedMatrixDecoder_OutputParameterId_Matrix)); - encoder.process(OVP_GD_Algorithm_StreamedMatrixEncoder_InputTriggerId_EncodeHeader); - decoder.process(); + iMatrix = &mat; + iBuffer.setReferenceTarget(oBuffer); - EXPECT_TRUE(decoder.isOutputTriggerActive(OVP_GD_Algorithm_StreamedMatrixDecoder_OutputTriggerId_ReceivedHeader)); + encoder.process(OVP_GD_Algorithm_StreamedMatrixEncoder_InputTriggerId_EncodeHeader); + decoder.process(); - EXPECT_EQ(mat.getDimensionCount(), oMatrix->getDimensionCount()); + EXPECT_TRUE(decoder.isOutputTriggerActive(OVP_GD_Algorithm_StreamedMatrixDecoder_OutputTriggerId_ReceivedHeader)); - EXPECT_TRUE(encoder.uninitialize()); - EXPECT_TRUE(decoder.uninitialize()); - } + EXPECT_EQ(mat.getDimensionCount(), oMatrix->getDimensionCount()); - TEST_F(StreamedMatrixTest, matrix_encoded_and_then_decoded_is_identical_to_original) + EXPECT_TRUE(encoder.uninitialize()); + EXPECT_TRUE(decoder.uninitialize()); +} + +TEST_F(StreamedMatrixTest, matrix_encoded_and_then_decoded_is_identical_to_original) +{ + auto& encoder = m_kernelCtx->getAlgorithmManager().getAlgorithm(m_encoderId); + auto& decoder = m_kernelCtx->getAlgorithmManager().getAlgorithm(m_decoderId); + EXPECT_TRUE(encoder.initialize()); + EXPECT_TRUE(decoder.initialize()); + CMatrix mat; + ASSERT_TRUE(mat.setDimensionCount(2)); + ASSERT_TRUE(mat.setDimensionSize(0, 2)); + ASSERT_TRUE(mat.setDimensionSize(1, 3)); + size_t elemCount = 1; + for (size_t dim = 0; dim < mat.getDimensionCount(); ++dim) { - auto& encoder = m_kernelCtx->getAlgorithmManager().getAlgorithm(m_encoderId); - auto& decoder = m_kernelCtx->getAlgorithmManager().getAlgorithm(m_decoderId); - EXPECT_TRUE(encoder.initialize()); - EXPECT_TRUE(decoder.initialize()); - CMatrix mat; - ASSERT_TRUE(mat.setDimensionCount(2)); - ASSERT_TRUE(mat.setDimensionSize(0, 2)); - ASSERT_TRUE(mat.setDimensionSize(1, 3)); - size_t elemCount = 1; - for (size_t dim = 0; dim < mat.getDimensionCount(); ++dim) + const auto size = mat.getDimensionSize(dim); + for (size_t entry = 0; entry < size; ++entry) { - const auto size = mat.getDimensionSize(dim); - for (size_t entry = 0; entry < size; ++entry) - { - std::string label = std::to_string(dim) + ":" + std::to_string(entry); - mat.setDimensionLabel(0, 0, label.c_str()); - } - elemCount *= size; + std::string label = std::to_string(dim) + ":" + std::to_string(entry); + mat.setDimensionLabel(0, 0, label.c_str()); } - for (size_t i = 0; i < elemCount; ++i) { mat.getBuffer()[i] = double(i); } + elemCount *= size; + } + for (size_t i = 0; i < elemCount; ++i) { mat.getBuffer()[i] = double(i); } - TParameterHandler<const IMatrix*> iMatrix(encoder.getInputParameter(OVP_GD_Algorithm_StreamedMatrixEncoder_InputParameterId_Matrix)); - TParameterHandler<const IMemoryBuffer*> oBuffer( - encoder.getOutputParameter(OVP_GD_Algorithm_StreamedMatrixEncoder_OutputParameterId_EncodedMemoryBuffer)); - TParameterHandler<const IMemoryBuffer*> iBuffer( - decoder.getInputParameter(OVP_GD_Algorithm_StreamedMatrixDecoder_InputParameterId_MemoryBufferToDecode)); - TParameterHandler<const IMatrix*> oMatrix(decoder.getOutputParameter(OVP_GD_Algorithm_StreamedMatrixDecoder_OutputParameterId_Matrix)); + TParameterHandler<const IMatrix*> iMatrix(encoder.getInputParameter(OVP_GD_Algorithm_StreamedMatrixEncoder_InputParameterId_Matrix)); + TParameterHandler<const IMemoryBuffer*> oBuffer(encoder.getOutputParameter(OVP_GD_Algorithm_StreamedMatrixEncoder_OutputParameterId_EncodedMemoryBuffer)); + TParameterHandler<const IMemoryBuffer*> iBuffer(decoder.getInputParameter(OVP_GD_Algorithm_StreamedMatrixDecoder_InputParameterId_MemoryBufferToDecode)); + TParameterHandler<const IMatrix*> oMatrix(decoder.getOutputParameter(OVP_GD_Algorithm_StreamedMatrixDecoder_OutputParameterId_Matrix)); - iMatrix = &mat; - iBuffer.setReferenceTarget(oBuffer); + iMatrix = &mat; + iBuffer.setReferenceTarget(oBuffer); - encoder.process(OVP_GD_Algorithm_StreamedMatrixEncoder_InputTriggerId_EncodeHeader); - decoder.process(); + encoder.process(OVP_GD_Algorithm_StreamedMatrixEncoder_InputTriggerId_EncodeHeader); + decoder.process(); - EXPECT_TRUE(decoder.isOutputTriggerActive(OVP_GD_Algorithm_StreamedMatrixDecoder_OutputTriggerId_ReceivedHeader)); + EXPECT_TRUE(decoder.isOutputTriggerActive(OVP_GD_Algorithm_StreamedMatrixDecoder_OutputTriggerId_ReceivedHeader)); - EXPECT_EQ(mat.getDimensionCount(), oMatrix->getDimensionCount()); + EXPECT_EQ(mat.getDimensionCount(), oMatrix->getDimensionCount()); - EXPECT_TRUE(encoder.uninitialize()); - EXPECT_TRUE(decoder.uninitialize()); - } + EXPECT_TRUE(encoder.uninitialize()); + EXPECT_TRUE(decoder.uninitialize()); +} } // namespace int uoStreamedMatrixTest(int argc, char* argv[]) diff --git a/unit-test/openvibe-toolkit/CMakeLists.txt b/unit-test/openvibe-toolkit/CMakeLists.txt index f19cf3000bbf7e602b30a9b9f37391c5d6ee5833..de034a287d54e94345b711554869e08e1932fd1f 100755 --- a/unit-test/openvibe-toolkit/CMakeLists.txt +++ b/unit-test/openvibe-toolkit/CMakeLists.txt @@ -24,9 +24,7 @@ PROJECT(openvibe-toolkit-test) # --------------------------------- # Target macros -# Defines target operating system -# Defines target architecture -# Defines target compiler +# Defines target operating system, architecture and compiler # --------------------------------- SET_BUILD_PLATFORM() @@ -62,7 +60,7 @@ INCLUDE("FindOpenViBE") INCLUDE("FindOpenViBECommon") INCLUDE("FindOpenViBEToolkit") INCLUDE("FindOpenViBEModuleSystem") -SET_PROPERTY(TARGET ${PROJECT_NAME} PROPERTY FOLDER ${OVT_UNIT_TESTS_FOLDER}) +SET_PROPERTY(TARGET ${PROJECT_NAME} PROPERTY FOLDER ${TESTS_FOLDER}) TARGET_LINK_LIBRARIES(${PROJECT_NAME} ${OVT_UNIT_TOOLKIT_LIB} ${GTEST_BOTH_LIBRARIES} ${OV_LIBS}) # Add test without parameter to driver diff --git a/unit-test/openvibe-toolkit/uoMatrixToolkitTest.cpp b/unit-test/openvibe-toolkit/uoMatrixToolkitTest.cpp index dbb9916e86f54e84501d4798001e60d85eab1cc7..ec8710be969b1f77e6e544aad903bba09c5d923e 100755 --- a/unit-test/openvibe-toolkit/uoMatrixToolkitTest.cpp +++ b/unit-test/openvibe-toolkit/uoMatrixToolkitTest.cpp @@ -36,9 +36,7 @@ void fillMatrix(CMatrix& matrix) for (size_t j = 0; j < matrix.getDimensionSize(i); ++j) { std::stringstream dimensionLabel; - dimensionLabel << "Label " << j + 1 << " of Dimension " << i + 1; - matrix.setDimensionLabel(i, j, dimensionLabel.str().c_str()); } } diff --git a/unit-test/ov-base/CMakeLists.txt b/unit-test/ov-base/CMakeLists.txt index 57bef8201c28b00da3a30c5b5516a6aee383da12..9a3a2634eb8bc01bed1f6c8de87169b11d21d62d 100644 --- a/unit-test/ov-base/CMakeLists.txt +++ b/unit-test/ov-base/CMakeLists.txt @@ -11,7 +11,7 @@ ADD_EXECUTABLE(${PROJECT_NAME} ${SRC_FILES}) SET_BUILD_PLATFORM() # Default build Platform INCLUDE("FindOpenViBE") # Find OpenViBE base includes and library INCLUDE("FindOpenViBECommon") # Find OpenViBE Common includes and library -SET_PROPERTY(TARGET ${PROJECT_NAME} PROPERTY FOLDER ${OVT_UNIT_TESTS_FOLDER}) # Place project in folder unit-test (for some IDE) +SET_PROPERTY(TARGET ${PROJECT_NAME} PROPERTY FOLDER ${TESTS_FOLDER}) # Place project in folder unit-test (for some IDE) TARGET_LINK_LIBRARIES(${PROJECT_NAME} ${GTEST_BOTH_LIBRARIES}) # Add google Test diff --git a/unit-test/ov-base/CMatrixTest.hpp b/unit-test/ov-base/CMatrixTest.hpp index 22ab75e2ee922efeac9a99dae81dc569f27080b1..b222c00a569e4c393bc7dc3809e49a244bb032bf 100644 --- a/unit-test/ov-base/CMatrixTest.hpp +++ b/unit-test/ov-base/CMatrixTest.hpp @@ -32,6 +32,7 @@ protected: m_mat.setDimensionLabel(1, 1, "dim1e1"); } }; + //--------------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------------- diff --git a/unit-test/unit-toolkit/CMakeLists.txt b/unit-test/unit-toolkit/CMakeLists.txt index 9fac5a40302c91652c0b9e4e04a98b10b44017b7..8e7b7b83fbcc2d85db283a25e1bf8602e6158660 100755 --- a/unit-test/unit-toolkit/CMakeLists.txt +++ b/unit-test/unit-toolkit/CMakeLists.txt @@ -32,9 +32,7 @@ SET(PROJECT_VERSION ${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}.${PROJECT_ # --------------------------------- # Target macros -# Defines target operating system -# Defines target architecture -# Defines target compiler +# Defines target operating system, architecture and compiler # --------------------------------- SET_BUILD_PLATFORM() @@ -47,7 +45,11 @@ ADD_DEFINITIONS( -DPROJECT_VERSION="${PROJECT_VERSION}" ) INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}/include) FILE(GLOB_RECURSE SRC_FILES src/*.cpp include/*.h) ADD_LIBRARY(${PROJECT_NAME} ${SRC_FILES}) -SET_PROPERTY(TARGET ${PROJECT_NAME} PROPERTY FOLDER ${OVT_TOOLS_FOLDER}) + +SET_TARGET_PROPERTIES(${PROJECT_NAME} PROPERTIES + VERSION ${PROJECT_VERSION} + SOVERSION ${PROJECT_VERSION_MAJOR} + FOLDER ${TESTS_FOLDER}) INCLUDE("FindOpenViBE") INCLUDE("FindOpenViBECommon") diff --git a/unit-test/unit-toolkit/include/ovtAssert.h b/unit-test/unit-toolkit/include/ovtAssert.h index 48643b6133c66eb125e9ae20f2bd7269b842126c..4277e8d9e43eb2c7248902aae48b41ff97bfd7e6 100755 --- a/unit-test/unit-toolkit/include/ovtAssert.h +++ b/unit-test/unit-toolkit/include/ovtAssert.h @@ -23,17 +23,15 @@ #include <string> -namespace OpenViBE -{ - namespace Test - { - void printError(const char* expression, const char* message, const char* file, const int line); - void printError(const char* expression, const std::string& message, const char* file, const int line); - void printError(const char* expression, const std::ostream& message, const char* file, const int line); - void printExpressionPair(const char* str1, const char* str2); - std::string buildExpressionFromPair(const char* str1, const char* str2); - } -} +namespace OpenViBE { +namespace Test { +void printError(const char* expression, const char* message, const char* file, const int line); +void printError(const char* expression, const std::string& message, const char* file, const int line); +void printError(const char* expression, const std::ostream& message, const char* file, const int line); +void printExpressionPair(const char* str1, const char* str2); +std::string buildExpressionFromPair(const char* str1, const char* str2); +} // namespace Test +} // namespace OpenViBE /** * OVT_ASSERT_PRIV: Assess expression and diff --git a/unit-test/unit-toolkit/include/ovtTestFixture.h b/unit-test/unit-toolkit/include/ovtTestFixture.h index eb299d6162736125f224278e5969b8cedd716891..c1c15dcecdeee72f24f90f90ce836fbe61cec239 100755 --- a/unit-test/unit-toolkit/include/ovtTestFixture.h +++ b/unit-test/unit-toolkit/include/ovtTestFixture.h @@ -23,61 +23,59 @@ #include <memory> -namespace OpenViBE +namespace OpenViBE { +namespace Test { +/** +* \struct TestFixture +* \author cgarraud (INRIA) +* \date 2016-02-08 +* \brief Base abstract struct for test fixture +* +* A test fixture is used when an environment has to be set for a specific test. +* TestFixture implementation should not be used directly but through ScopedTest. +*/ +struct TestFixture { - namespace Test - { + virtual ~TestFixture() = default; + TestFixture() = default; + /** - * \struct TestFixture - * \author cgarraud (INRIA) - * \date 2016-02-08 - * \brief Base abstract struct for test fixture - * - * A test fixture is used when an environment has to be set for a specific test. - * TestFixture implementation should not be used directly but through ScopedTest. + * \brief Setup resources for the test */ - struct TestFixture - { - virtual ~TestFixture() = default; - TestFixture() = default; + virtual void setUp() = 0; - /** - * \brief Setup resources for the test - */ - virtual void setUp() = 0; - - /** - * \brief Release resources - */ - virtual void tearDown() = 0; + /** + * \brief Release resources + */ + virtual void tearDown() = 0; - private: +private: - TestFixture& operator=(const TestFixture&) = delete; - TestFixture(const TestFixture&) = delete; - }; + TestFixture& operator=(const TestFixture&) = delete; + TestFixture(const TestFixture&) = delete; +}; - /** - * \struct ScopedTest - * \author cgarraud (INRIA) - * \date 2016-02-08 - * \brief Class used to ensure RAII when using TestFixture - * - * A scoped object is a wrapper around a test fixture used to - * ensure RAII when running tests. - */ - template <typename T> - struct ScopedTest - { - template <typename... TArgs> - explicit ScopedTest(TArgs&&... args) : fixture(new T(std::forward<TArgs>(args)...)) { fixture->setUp(); } +/** +* \struct ScopedTest +* \author cgarraud (INRIA) +* \date 2016-02-08 +* \brief Class used to ensure RAII when using TestFixture +* +* A scoped object is a wrapper around a test fixture used to +* ensure RAII when running tests. +*/ +template <typename T> +struct ScopedTest +{ + template <typename... TArgs> + explicit ScopedTest(TArgs&&... args) : fixture(new T(std::forward<TArgs>(args)...)) { fixture->setUp(); } - ~ScopedTest() { fixture->tearDown(); } + ~ScopedTest() { fixture->tearDown(); } - const T* operator->() const { return fixture.get(); } - T* operator->() { return fixture.get(); } + const T* operator->() const { return fixture.get(); } + T* operator->() { return fixture.get(); } - std::unique_ptr<T> fixture; - }; - } // namespace Test -} // namespace OpenViBE + std::unique_ptr<T> fixture; +}; +} // namespace Test +} // namespace OpenViBE diff --git a/unit-test/unit-toolkit/include/ovtTestFixtureCommon.h b/unit-test/unit-toolkit/include/ovtTestFixtureCommon.h index 027a8df0d142d519e6b311fc74de13df5535f3ed..c0d1cc804d7dd2c68b408a16c0531c997483304c 100755 --- a/unit-test/unit-toolkit/include/ovtTestFixtureCommon.h +++ b/unit-test/unit-toolkit/include/ovtTestFixtureCommon.h @@ -28,25 +28,23 @@ #include "ovtTestFixture.h" // \note: This file contains fixture implementation shared by many unit tests -namespace OpenViBE +namespace OpenViBE { +namespace Test { +struct SKernelFixture final : TestFixture { - namespace Test - { - struct SKernelFixture final : TestFixture - { - SKernelFixture() = default; - explicit SKernelFixture(const std::string& configFile) : m_configFile(configFile) { } - - void setConfigFile(const std::string& configFile) { m_configFile = configFile; } - - void setUp() override; - void tearDown() override; - - Kernel::IKernelContext* context{ nullptr }; - - private: - std::string m_configFile; - CKernelLoader m_kernelLoader; - }; - } // namespace Test -} // namespace OpenViBE + SKernelFixture() = default; + explicit SKernelFixture(const std::string& configFile) : m_configFile(configFile) { } + + void setConfigFile(const std::string& configFile) { m_configFile = configFile; } + + void setUp() override; + void tearDown() override; + + Kernel::IKernelContext* context{ nullptr }; + +private: + std::string m_configFile; + CKernelLoader m_kernelLoader; +}; +} // namespace Test +} // namespace OpenViBE diff --git a/unit-test/unit-toolkit/src/ovtAssert.cpp b/unit-test/unit-toolkit/src/ovtAssert.cpp index a0952b997665f94746829e196f4182536f9b3da0..5f668b5402cfa18996a70ee9867f5f1f60492b73 100755 --- a/unit-test/unit-toolkit/src/ovtAssert.cpp +++ b/unit-test/unit-toolkit/src/ovtAssert.cpp @@ -23,44 +23,42 @@ #include "ovtAssert.h" -namespace OpenViBE +namespace OpenViBE { +namespace Test { +static void printErrorCore(const char* expression, const char* file, const int line) { - namespace Test - { - static void printErrorCore(const char* expression, const char* file, const int line) - { - std::cerr << "Failed to evaluate: " << expression << std::endl; - std::cerr << "File = " << file << std::endl; - std::cerr << "Line = " << line << std::endl; - } + std::cerr << "Failed to evaluate: " << expression << std::endl; + std::cerr << "File = " << file << std::endl; + std::cerr << "Line = " << line << std::endl; +} - void printError(const char* expression, const char* message, const char* file, const int line) - { - printErrorCore(expression, file, line); - std::cerr << "Error message: " << message << std::endl; - } +void printError(const char* expression, const char* message, const char* file, const int line) +{ + printErrorCore(expression, file, line); + std::cerr << "Error message: " << message << std::endl; +} - void printError(const char* expression, const std::string& message, const char* file, const int line) { printError(expression, message.c_str(), file, line); } +void printError(const char* expression, const std::string& message, const char* file, const int line) { printError(expression, message.c_str(), file, line); } - void printError(const char* expression, const std::ostream& message, const char* file, const int line) - { - printErrorCore(expression, file, line); - std::cerr << "Error message: " << message.rdbuf() << std::endl; - } +void printError(const char* expression, const std::ostream& message, const char* file, const int line) +{ + printErrorCore(expression, file, line); + std::cerr << "Error message: " << message.rdbuf() << std::endl; +} - void printExpressionPair(const char* str1, const char* str2) - { - std::cerr << "Expression 1 is : " << str1 << std::endl; - std::cerr << "Expression 2 is : " << str2 << std::endl; - } +void printExpressionPair(const char* str1, const char* str2) +{ + std::cerr << "Expression 1 is : " << str1 << std::endl; + std::cerr << "Expression 2 is : " << str2 << std::endl; +} - std::string buildExpressionFromPair(const char* str1, const char* str2) - { - std::string expression = "( " + std::string(str1); - expression += " = "; - expression += std::string(str2) + " )"; +std::string buildExpressionFromPair(const char* str1, const char* str2) +{ + std::string expression = "( " + std::string(str1); + expression += " = "; + expression += std::string(str2) + " )"; - return expression; - } - } // namespace Test -} // namespace OpenViBE + return expression; +} +} // namespace Test +} // namespace OpenViBE diff --git a/unit-test/unit-toolkit/src/ovtTestFixtureCommon.cpp b/unit-test/unit-toolkit/src/ovtTestFixtureCommon.cpp index 8b68e847811c71347b8a0f2d706139012c33f018..7641a95293dc741994933abe8991506532fa643e 100755 --- a/unit-test/unit-toolkit/src/ovtTestFixtureCommon.cpp +++ b/unit-test/unit-toolkit/src/ovtTestFixtureCommon.cpp @@ -29,71 +29,69 @@ using namespace OpenViBE; using namespace /*OpenViBE::*/Kernel; using namespace /*OpenViBE::*/Plugins; -namespace OpenViBE +namespace OpenViBE { +namespace Test { +void SKernelFixture::setUp() { - namespace Test - { - void SKernelFixture::setUp() - { #if defined TARGET_OS_Windows - const CString kernelFile = Directories::getLibDir() + "/openvibe-kernel.dll"; + const CString kernelFile = Directories::getLibDir() + "/openvibe-kernel.dll"; #elif defined TARGET_OS_Linux - const CString kernelFile = Directories::getLibDir() + "/libopenvibe-kernel.so"; + const CString kernelFile = Directories::getLibDir() + "/libopenvibe-kernel.so"; #elif defined TARGET_OS_MacOS - const CString kernelFile = Directories::getLibDir() + "/libopenvibe-kernel.dylib"; + const CString kernelFile = Directories::getLibDir() + "/libopenvibe-kernel.dylib"; #endif - CString error; + CString error; - if (!m_kernelLoader.load(kernelFile, &error)) - { - std::cerr << "ERROR: impossible to load kernel from file located at: " << kernelFile << std::endl; - std::cerr << "ERROR: kernel error: " << error << std::endl; - return; - } - - m_kernelLoader.initialize(); + if (!m_kernelLoader.load(kernelFile, &error)) + { + std::cerr << "ERROR: impossible to load kernel from file located at: " << kernelFile << std::endl; + std::cerr << "ERROR: kernel error: " << error << std::endl; + return; + } - IKernelDesc* kernelDesc = nullptr; - m_kernelLoader.getKernelDesc(kernelDesc); + m_kernelLoader.initialize(); - if (!kernelDesc) - { - std::cerr << "ERROR: impossible to retrieve kernel descriptor " << std::endl; - return; - } + IKernelDesc* kernelDesc = nullptr; + m_kernelLoader.getKernelDesc(kernelDesc); - CString configFile; + if (!kernelDesc) + { + std::cerr << "ERROR: impossible to retrieve kernel descriptor " << std::endl; + return; + } - if (!m_configFile.empty()) { configFile = m_configFile.c_str(); } - else { configFile = CString(Directories::getDataDir() + "/kernel/openvibe.conf"); } + CString configFile; + if (!m_configFile.empty()) { configFile = m_configFile.c_str(); } + else { configFile = CString(Directories::getDataDir() + "/kernel/openvibe.conf"); } - IKernelContext* ctx = kernelDesc->createKernel("test-kernel", configFile); - if (!ctx) - { - std::cerr << "ERROR: impossible to create kernel context " << std::endl; - return; - } + IKernelContext* ctx = kernelDesc->createKernel("test-kernel", configFile); - ctx->initialize(); - Toolkit::initialize(*ctx); - context = ctx; + if (!ctx) + { + std::cerr << "ERROR: impossible to create kernel context " << std::endl; + return; } - void SKernelFixture::tearDown() + ctx->initialize(); + Toolkit::initialize(*ctx); + context = ctx; +} + +void SKernelFixture::tearDown() +{ + if (context) { - if (context) - { - Toolkit::uninitialize(*context); - IKernelDesc* kernelDesc = nullptr; - m_kernelLoader.getKernelDesc(kernelDesc); - kernelDesc->releaseKernel(context); - context = nullptr; - } - - m_kernelLoader.uninitialize(); - m_kernelLoader.unload(); + Toolkit::uninitialize(*context); + IKernelDesc* kernelDesc = nullptr; + m_kernelLoader.getKernelDesc(kernelDesc); + kernelDesc->releaseKernel(context); + context = nullptr; } - } // namespace Test -} // namespace OpenViBE + + m_kernelLoader.uninitialize(); + m_kernelLoader.unload(); +} +} // namespace Test +} // namespace OpenViBE diff --git a/validation-test/CMakeLists.txt b/validation-test/CMakeLists.txt index d6c4da1cb64aa821b0cc411cd68abd68ea8a1c78..bdeafb8d3c81e370f29f9c72856ee97504692509 100755 --- a/validation-test/CMakeLists.txt +++ b/validation-test/CMakeLists.txt @@ -20,11 +20,6 @@ SET(OVT_VALIDATION_TEST_OUTPUT_DIR ${PROJECT_BINARY_DIR}/validation-test-output/ # Project configuration # ---------------------- -# Sort target into directories for better visualization in IDE -SET_PROPERTY(GLOBAL PROPERTY USE_FOLDERS ON) -SET(OVT_VALIDATION_TESTS_FOLDER validation-tests) -SET(OVT_TOOLS_FOLDER tools) - # Add python tools path SET(OVT_PYTHON_TOOL_DIR ${PROJECT_SOURCE_DIR}/python-toolkit/) diff --git a/validation-test/openvibe-classification-lda/CMakeLists.txt b/validation-test/openvibe-classification-lda/CMakeLists.txt index 51b1efbc44f9f78586ebf257e920762a5c9cad78..0ac8b9478578c6d11fd3ceeb2fc1d1a95fed7297 100755 --- a/validation-test/openvibe-classification-lda/CMakeLists.txt +++ b/validation-test/openvibe-classification-lda/CMakeLists.txt @@ -53,7 +53,7 @@ SET (LDA_TEST LDA) # This is just a way to have the test scripts available in the IDE FILE(GLOB_RECURSE script_files ${CMAKE_CURRENT_SOURCE_DIR}/*.mxs ${CMAKE_CURRENT_SOURCE_DIR}/*.xml ${CMAKE_CURRENT_SOURCE_DIR}/*.xml.in) ADD_CUSTOM_TARGET(${PROJECT_NAME} SOURCES ${script_files}) -SET_PROPERTY(TARGET ${PROJECT_NAME} PROPERTY FOLDER ${OVT_VALIDATION_TESTS_FOLDER}) +SET_PROPERTY(TARGET ${PROJECT_NAME} PROPERTY FOLDER ${VALIDATION_FOLDER}) # --------------------------- # Add test to test to be run diff --git a/validation-test/openvibe-file-io-csv/CMakeLists.txt b/validation-test/openvibe-file-io-csv/CMakeLists.txt index 01d43efc9e7453ebf94ffb0df907c957ce4a951d..108ca290de791a5bdd554b0cc46cd1316cb671e7 100755 --- a/validation-test/openvibe-file-io-csv/CMakeLists.txt +++ b/validation-test/openvibe-file-io-csv/CMakeLists.txt @@ -51,7 +51,7 @@ SET(TEST_SCENARIOS # This is just a way to have the test scripts available in the IDE FILE(GLOB_RECURSE script_files ${CMAKE_CURRENT_SOURCE_DIR}/*.mxs ${CMAKE_CURRENT_SOURCE_DIR}/*.xml ${CMAKE_CURRENT_SOURCE_DIR}/*.xml.in) ADD_CUSTOM_TARGET(${PROJECT_NAME} SOURCES ${script_files}) -SET_PROPERTY(TARGET ${PROJECT_NAME} PROPERTY FOLDER ${OVT_VALIDATION_TESTS_FOLDER}) +SET_PROPERTY(TARGET ${PROJECT_NAME} PROPERTY FOLDER ${VALIDATION_FOLDER}) # --------------------------- # Add test to test to be run diff --git a/validation-test/openvibe-file-io-openvibe/CMakeLists.txt b/validation-test/openvibe-file-io-openvibe/CMakeLists.txt index e0bf2c47b832bbbcf406e38442d839a23e9d0622..0cebb81b500d17744545dc1f7a9b96df04a10881 100755 --- a/validation-test/openvibe-file-io-openvibe/CMakeLists.txt +++ b/validation-test/openvibe-file-io-openvibe/CMakeLists.txt @@ -46,7 +46,7 @@ SET(TEST_SCENARIOS # This is just a way to have the test scripts available in the IDE FILE(GLOB_RECURSE script_files ${CMAKE_CURRENT_SOURCE_DIR}/*.mxs ${CMAKE_CURRENT_SOURCE_DIR}/*.xml.in) ADD_CUSTOM_TARGET(${PROJECT_NAME} SOURCES ${script_files}) -SET_PROPERTY(TARGET ${PROJECT_NAME} PROPERTY FOLDER ${OVT_VALIDATION_TESTS_FOLDER}) +SET_PROPERTY(TARGET ${PROJECT_NAME} PROPERTY FOLDER ${VALIDATION_FOLDER}) # --------------------------- # Add test to test to be run diff --git a/validation-test/openvibe-regularized-csp/CMakeLists.txt b/validation-test/openvibe-regularized-csp/CMakeLists.txt index 504cb1054c30542535f38bda06680e4696924760..32ec8b876b27cb3edf88b419eb4c9c6572578b5e 100755 --- a/validation-test/openvibe-regularized-csp/CMakeLists.txt +++ b/validation-test/openvibe-regularized-csp/CMakeLists.txt @@ -53,7 +53,7 @@ SET (REGULARIZED_CSP regularized-csp) # This is just a way to have the test scripts available in the IDE FILE(GLOB_RECURSE script_files ${CMAKE_CURRENT_SOURCE_DIR}/*.mxs ${CMAKE_CURRENT_SOURCE_DIR}/*.xml ${CMAKE_CURRENT_SOURCE_DIR}/*.xml.in) ADD_CUSTOM_TARGET(${PROJECT_NAME} SOURCES ${script_files}) -SET_PROPERTY(TARGET ${PROJECT_NAME} PROPERTY FOLDER ${OVT_VALIDATION_TESTS_FOLDER}) +SET_PROPERTY(TARGET ${PROJECT_NAME} PROPERTY FOLDER ${VALIDATION_FOLDER}) # --------------------------- # Add test to test to be run diff --git a/validation-test/openvibe-stimulation-timeout/CMakeLists.txt b/validation-test/openvibe-stimulation-timeout/CMakeLists.txt index 475385b8b27c4bb5f179937c48823d9c289d6d85..c2c8430d9ee6b42bf28565bd778bbef918d577b1 100755 --- a/validation-test/openvibe-stimulation-timeout/CMakeLists.txt +++ b/validation-test/openvibe-stimulation-timeout/CMakeLists.txt @@ -46,7 +46,7 @@ SET(TEST_SCENARIOS # This is just a way to have the test scripts available in the IDE FILE(GLOB_RECURSE script_files ${CMAKE_CURRENT_SOURCE_DIR}/*.mxs ${CMAKE_CURRENT_SOURCE_DIR}/*.xml ${CMAKE_CURRENT_SOURCE_DIR}/*.xml.in) ADD_CUSTOM_TARGET(${PROJECT_NAME} SOURCES ${script_files}) -SET_PROPERTY(TARGET ${PROJECT_NAME} PROPERTY FOLDER ${OVT_VALIDATION_TESTS_FOLDER}) +SET_PROPERTY(TARGET ${PROJECT_NAME} PROPERTY FOLDER ${VALIDATION_FOLDER}) # --------------------------- # Add test to test to be run