From 56f0aadcf280e9828dd975512a4a7c26df0c8c27 Mon Sep 17 00:00:00 2001 From: poei Date: Thu, 23 Feb 2023 21:39:38 +0330 Subject: [PATCH] refactor --- wolf/.clang-format | 33 +++ wolf/.clang-tidy | 63 +++-- wolf/CMakeLists.txt | 44 +--- wolf/DISABLE_ANALYSIS_BEGIN | 1 - wolf/DISABLE_ANALYSIS_END | 4 +- wolf/cmake/rust.cmake | 22 -- wolf/cmake/stream.cmake | 3 +- wolf/media/ffmpeg/w_av_frame.cpp | 94 +++---- wolf/media/ffmpeg/w_av_frame.hpp | 33 ++- wolf/media/ffmpeg/w_decoder.cpp | 28 +- wolf/media/test/avframe.hpp | 13 +- wolf/media/test/ffmpeg.hpp | 58 ++--- wolf/media/test/image.hpp | 11 +- wolf/media/test/openal.hpp | 5 +- wolf/stream/test/ffmpeg_stream.hpp | 83 ++---- wolf/stream/test/rist.hpp | 46 ++-- wolf/system/gamepad/w_gamepad_virtual.cpp | 58 +++-- wolf/system/gamepad/w_gamepad_virtual.hpp | 16 +- wolf/system/gamepad/w_gamepad_virtual_bus.hpp | 19 ++ .../system/gamepad/w_gamepad_virtual_pool.cpp | 55 ++-- .../system/gamepad/w_gamepad_virtual_pool.hpp | 2 +- wolf/system/getopt.h | 66 ++--- wolf/system/socket/w_tcp_server.cpp | 4 +- wolf/system/socket/w_ws_client.cpp | 3 +- wolf/system/socket/w_ws_server.cpp | 2 +- wolf/system/test/compress.hpp | 25 +- wolf/system/test/coroutine.hpp | 3 +- wolf/system/test/gamepad.hpp | 10 +- wolf/system/test/gametime.hpp | 4 +- wolf/system/test/log.hpp | 3 +- wolf/system/test/postgresql.hpp | 242 ++++++++---------- wolf/system/test/tcp.hpp | 41 ++- wolf/system/test/trace.hpp | 4 +- wolf/system/test/ws.hpp | 31 +-- wolf/system/w_gametime.cpp | 20 +- wolf/system/w_gametime.hpp | 22 +- wolf/system/w_leak_detector.cpp | 5 +- wolf/system/w_leak_detector.hpp | 6 +- wolf/system/w_process.cpp | 3 +- wolf/system/w_process.hpp | 6 +- wolf/system/w_ring_buffer_spsc.hpp | 25 +- wolf/system/w_trace.hpp | 70 +++-- wolf/tests.cpp | 6 +- wolf/wolf.cpp | 10 +- wolf/wolf.hpp | 20 +- 45 files changed, 603 insertions(+), 719 deletions(-) create mode 100644 wolf/.clang-format delete mode 100644 wolf/cmake/rust.cmake create mode 100644 wolf/system/gamepad/w_gamepad_virtual_bus.hpp diff --git a/wolf/.clang-format b/wolf/.clang-format new file mode 100644 index 000000000..c8838e98f --- /dev/null +++ b/wolf/.clang-format @@ -0,0 +1,33 @@ +# http://clang.llvm.org/docs/ClangFormatStyleOptions.html +BasedOnStyle: Google +# This defaults to 'Auto'. Explicitly set it for a while, so that +# 'vector >' in existing files gets formatted to +# 'vector>'. ('Auto' means that clang-format will only use +# 'int>>' if the file already contains at least one such instance.) +Standard: Cpp11 +SortIncludes: true +AllowShortIfStatementsOnASingleLine: false +AllowShortLoopsOnASingleLine: false +BreakStringLiterals: false +DerivePointerAlignment: true +PointerAlignment: Left +ColumnLimit: 100 +ForEachMacros: ['list_for_every_entry','list_for_every_entry_safe'] +IncludeBlocks: Regroup +IncludeCategories: + # This specific header must come last in kernel source files. Its + # matching rule must come first so the lower-priority rules don't match. + - Regex: '^' + Priority: 1000 + # C Header: , , etc + - Regex: '^(<((zircon/|lib/|fuchsia/|arpa/|net/|netinet/|sys/|fidl/)[a-zA-Z0-9_/\.-]+\.h|[a-zA-Z0-9_-]+\.h)>)' + Priority: 1 + # Cpp Header: and + - Regex: '^(<(experimental/)*[a-zA-Z0-9_-]+>)' + Priority: 2 + # Libraries: + - Regex: '^(<[a-zA-Z0-9_/-]+\.h>)' + Priority: 3 + # Local headers: "foo/bar.h" + - Regex: '^("[.a-zA-Z0-9_/-]+\.h")' + Priority: 4 \ No newline at end of file diff --git a/wolf/.clang-tidy b/wolf/.clang-tidy index 74921febd..d3c649b46 100644 --- a/wolf/.clang-tidy +++ b/wolf/.clang-tidy @@ -1,22 +1,52 @@ --- -Checks: '*,boost-*,bugprone-*,cert-*,clang-analyzer-*,concurrency-*,cppcoreguidelines-*,modernize-*,performance-*,portability-*,readability-*,-llvmlibc-restrict-system-libc-headers,-llvmlibc-*,-fuchsia-trailing-return,-llvm-header-guard,-clang-diagnostic-pragma-once-outside-header,-modernize-use-trailing-return-type,-clang-diagnostic-c++98-compat,-hicpp-use-auto,-modernize-use-auto, -fuchsia-default-arguments-calls' -WarningsAsErrors: true -HeaderFilterRegex: '' +Checks: > + -*, + bugprone-*, + clang-diagnostic-*, + -clang-diagnostic-unused-command-line-argument, + google-*, + -google-runtime-references, + misc-*, + -misc-noexcept*, + -misc-unused-parameters, + -misc-const-correctness, + modernize-*, + -modernize-avoid-c-arrays, + -modernize-deprecated-headers, + -modernize-raw-string-literal, + -modernize-return-braced-init-list, + -modernize-use-auto, + -modernize-use-equals-delete, + -modernize-use-nodiscard, + -modernize-use-trailing-return-type, + performance-*, + readability-*, + -readability-function-cognitive-complexity, + -readability-identifier-length, + -readability-implicit-bool-conversion, + -readability-isolate-declaration, + -readability-magic-numbers, + -readability-qualified-auto, + -readability-uppercase-literal-suffix, + -readability-identifier-length, + -readability-named-parameter, +WarningsAsErrors: false AnalyzeTemporaryDtors: false +FormatStyle: file CheckOptions: - - key: cert-dcl16-c.NewSuffixes - value: 'L;LL;LU;LLU' - - key: cert-oop54-cpp.WarnOnlyIfThisHasSuspiciousField - value: '0' - - key: cppcoreguidelines-explicit-virtual-functions.IgnoreDestructors - value: '1' - - key: cppcoreguidelines-non-private-member-variables-in-classes.IgnoreClassesWithAllMemberVariablesBeingPublic - value: '1' + - key: bugprone-signed-char-misuse.CharTypdefsToIgnore + value: 'int8_t' + - key: bugprone-assert-side-effect.AssertMacros + value: 'FXL_DCHECK' + - key: google-readability-braces-around-statements.ShortStatementLines + value: '2' - key: google-readability-function-size.StatementThreshold value: '800' - key: google-readability-namespace-comments.ShortNamespaceLines value: '10' - key: google-readability-namespace-comments.SpacesBeforeComments + value: '2' + - key: misc-non-private-member-variables-in-classes.IgnoreClassesWithAllMemberVariablesBeingPublic value: '1' - key: modernize-loop-convert.MaxCopySize value: '16' @@ -28,15 +58,12 @@ CheckOptions: value: llvm - key: modernize-replace-auto-ptr.IncludeStyle value: llvm - - key: modernize-use-bool-literals.IgnoreMacros - value: '0' - - key: modernize-use-default-member-init.IgnoreMacros - value: '0' - key: modernize-use-default-member-init.UseAssignment value: '1' + - key: modernize-use-emplace.IgnoreImplicitConstructors + value: '1' - key: modernize-use-nullptr.NullMacros value: 'NULL' - key: readability-braces-around-statements.ShortStatementLines - value: '0' -... - + value: '2' +... \ No newline at end of file diff --git a/wolf/CMakeLists.txt b/wolf/CMakeLists.txt index 50bf2e8af..d5687b795 100644 --- a/wolf/CMakeLists.txt +++ b/wolf/CMakeLists.txt @@ -10,10 +10,7 @@ set(TEST_PROJECT_NAME "${PROJECT_NAME}_tests") message("CXX Compiler ID is ${CMAKE_CXX_COMPILER_ID}") # set the options and enviroment variables -set(WEBRTC_SRC $ENV{WEBRTC_ROOT} CACHE STRING "path to the root folder of webrtc folder") - -# set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/${PROJECT_NAME}) -# set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/${PROJECT_NAME}) +#set(WEBRTC_SRC $ENV{WEBRTC_ROOT} CACHE STRING "path to the root folder of webrtc folder") # check the OS if(CMAKE_SIZEOF_VOID_P EQUAL 8) @@ -96,11 +93,8 @@ option(WOLF_SYSTEM_SOCKET "Enable TCP/UDP protocol over socket" OFF) option(WOLF_SYSTEM_STACKTRACE "Enable boost stacktrace" OFF) option(WOLF_SYSTEM_POSTGRESQL "Enable postgresql database client" OFF) -#option(WOLF_SYSTEM_WASM3 "Enable WebAssembly interpreter" OFF) -#option(WOLF_SYSTEM_ZLIB "Enable zlib for compression" OFF) - # machine learing modules -option(WOLF_ML_OCR "Enable machine learning referee ocr" ON) +option(WOLF_ML_OCR "Enable machine learning referee ocr" OFF) option(WOLF_ML_NUDITY_DETECTION "Enable machine learning nudity detection" OFF) #option(WOLF_ENABLE_LTO "Enable cross language linking time optimization" OFF) @@ -121,36 +115,17 @@ if(ENABLE_LTO) endif() endif() -# media modules -# -# option(WOLF_MEDIA_IMAGE "Enable WebP/BMP/JPG/PNG formats" OFF) -# - -# stream modules -# option(WOLF_STREAM_KAFKA_CLIENT "Enable Kafka API connector" OFF) - -# option(WOLF_STREAM_RTSP_CLIENT "Enable RTSP for client" OFF) -# option(WOLF_STREAM_RTSP_SERVER "Enable RTSP for server" OFF) -#option(WOLF_STREAM_WEBRTC "Enable native webRTC" OFF) - -# system modules -# option(WOLF_SYSTEM_AVX2 "Enable avx2" OFF) -# option(WOLF_SYSTEM_AVX512 "Enable avx512" OFF) -# option(WOLF_SYSTEM_BROTLI "Enable brotli compression" OFF) -# option(WOLF_SYSTEM_RAFT "Enable raft algorithm" OFF) - -# set C/CXX ios standards +# set C/CXX standards set(CMAKE_C_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_EXTENSIONS ON) set(CMAKE_THREAD_PREFER_PTHREAD TRUE) set(THREADS_PREFER_PTHREAD_FLAG TRUE) -#set(CMAKE_BUILD_TYPE "${default_build_type}" CACHE STRING "Choose the type of build." FORCE) +#set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "Debug" "Release" "MinSizeRel" "RelWithDebInfo") if ("${CMAKE_BUILD_TYPE}" STREQUAL "") set(CMAKE_BUILD_TYPE "Debug") endif() -#set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "Debug" "Release" "MinSizeRel" "RelWithDebInfo") # set C++ flags based on compiler if (CMAKE_CXX_COMPILER_ID STREQUAL "Clang" OR CMAKE_CXX_COMPILER_ID STREQUAL "AppleClang") @@ -190,11 +165,12 @@ endif() # include cmakes include(cmake/boost.cmake) include(cmake/media.cmake) -include(cmake/rust.cmake) include(cmake/system.cmake) include(cmake/stream.cmake) include(cmake/ml.cmake) +# disable build testing +set(BUILD_TESTING OFF CACHE BOOL "BUILD_TESTING") if (WOLF_ENABLE_ASAN) set(ENABLE_ASAN TRUE) @@ -208,9 +184,9 @@ endif() # https://devblogs.microsoft.com/cppblog/visual-studio-code-c-december-2021-update-clang-tidy/ # can be enabled with .CLANG-TIDY from Visual Studio # https://devblogs.microsoft.com/cppblog/code-analysis-with-clang-tidy-in-visual-studio/ -#set(CMAKE_CXX_CLANG_TIDY -# clang-tidy; -# -format-style=file;) +set(CMAKE_CXX_CLANG_TIDY + clang-tidy; + -format-style=file;) # add definitions @@ -311,8 +287,6 @@ source_group("media/ffmpeg" FILES ${WOLF_MEDIA_FFMPEG_SRC}) source_group("media" FILES ${WOLF_MEDIA_OPENAL_SRC} ${WOLF_MEDIA_STB_SRC}) source_group("ml/referee_ocr" FILES ${WOLF_ML_OCR_SRC}) -# file(COPY ${CMAKE_BINARY_DIR}/bin/${CMAKE_BUILD_TYPE} DESTINATION ${CMAKE_BINARY_DIR}/${PROJECT_NAME}/${CMAKE_BUILD_TYPE}) - # add compile options if (NOT WIN32) target_compile_options(${PROJECT_NAME} PRIVATE -std=c++2b -fPIC) diff --git a/wolf/DISABLE_ANALYSIS_BEGIN b/wolf/DISABLE_ANALYSIS_BEGIN index 5859ce9d9..b95597074 100644 --- a/wolf/DISABLE_ANALYSIS_BEGIN +++ b/wolf/DISABLE_ANALYSIS_BEGIN @@ -1,4 +1,3 @@ -// NOLINTBEGIN #ifdef _MSC_VER #pragma warning(push) #pragma warning (disable:ALL_CODE_ANALYSIS_WARNINGS) diff --git a/wolf/DISABLE_ANALYSIS_END b/wolf/DISABLE_ANALYSIS_END index c579e8255..c528772b3 100644 --- a/wolf/DISABLE_ANALYSIS_END +++ b/wolf/DISABLE_ANALYSIS_END @@ -1,4 +1,4 @@ -// NOLINTEND #ifdef _MSC_VER #pragma warning(pop) -#endif \ No newline at end of file +#endif +// NOLINTEND \ No newline at end of file diff --git a/wolf/cmake/rust.cmake b/wolf/cmake/rust.cmake deleted file mode 100644 index d92df6ebe..000000000 --- a/wolf/cmake/rust.cmake +++ /dev/null @@ -1,22 +0,0 @@ -if (FALSE) - -# corrosion for linking to wolf rust library -FetchContent_Declare( - corrosion - GIT_REPOSITORY https://github.com/corrosion-rs/corrosion.git - GIT_TAG master -) -set(FETCHCONTENT_QUIET OFF) -FetchContent_MakeAvailable(corrosion) -corrosion_import_crate(MANIFEST_PATH ${CMAKE_CURRENT_SOURCE_DIR}/rust/Cargo.toml) - -set_target_properties( - _cargo-build_wolf_rs - cargo-build_wolf_rs - cargo-clean - cargo-clean_wolf_rs - cargo-prebuild - cargo-prebuild_wolf_rs - PROPERTIES FOLDER "rust") - -endif() \ No newline at end of file diff --git a/wolf/cmake/stream.cmake b/wolf/cmake/stream.cmake index 7c72c1c9f..f12061a3e 100644 --- a/wolf/cmake/stream.cmake +++ b/wolf/cmake/stream.cmake @@ -14,8 +14,7 @@ if (WOLF_STREAM_GRPC) GIT_TAG master ) - set(ABSL_BUILD_TESTING OFF CACHE BOOL "BUILD_TESTING") - set(BUILD_TESTING OFF CACHE BOOL "BUILD_TESTING") + set(ABSL_BUILD_TESTING OFF CACHE BOOL "ABSL_BUILD_TESTING") set(gRPC_BUILD_CSHARP_EXT OFF CACHE BOOL "GRPC_BUILD_CSHARP_EXT") set(gRPC_BUILD_GRPC_CPP_PLUGIN ON CACHE BOOL "gRPC_BUILD_GRPC_CPP_PLUGIN") diff --git a/wolf/media/ffmpeg/w_av_frame.cpp b/wolf/media/ffmpeg/w_av_frame.cpp index 8add38b5e..a90820fa7 100644 --- a/wolf/media/ffmpeg/w_av_frame.cpp +++ b/wolf/media/ffmpeg/w_av_frame.cpp @@ -29,7 +29,7 @@ int w_av_config::get_required_buffer_size() noexcept { w_av_frame::w_av_frame(_In_ const w_av_config &p_config) noexcept : _config(p_config), _av_frame(nullptr), _moved_data(nullptr) {} -w_av_frame::w_av_frame(w_av_frame &&p_other) noexcept { +w_av_frame::w_av_frame(_Inout_ w_av_frame &&p_other) noexcept { _move(std::move(p_other)); } @@ -62,20 +62,17 @@ void w_av_frame::_release() noexcept { } } -boost::leaf::result w_av_frame::init() noexcept { return set(nullptr); } - -boost::leaf::result w_av_frame::set(_Inout_ uint8_t **p_data) noexcept { +boost::leaf::result w_av_frame::init() noexcept { return set(); } +boost::leaf::result w_av_frame::set(_Inout_ std::optional p_data) noexcept { const auto _width = this->_config.width; const auto _height = this->_config.height; const auto _alignment = this->_config.alignment; - const auto _channels = this->_config.channels; const auto _sample_rate = this->_config.sample_rate; // check for width and height - if ((_width <= 0 || _height <= 0) && (_channels <= 0 || _sample_rate <= 0)) { - return W_FAILURE(std::errc::invalid_argument, - "width or height of w_av_frame is zero"); + if ((_width <= 0 || _height <= 0) && (_sample_rate <= 0)) { + return W_FAILURE(std::errc::invalid_argument, "width or height of w_av_frame is zero"); } if (this->_av_frame == nullptr) { @@ -86,25 +83,24 @@ boost::leaf::result w_av_frame::set(_Inout_ uint8_t **p_data) noexcept { _av_frame_nn->format = gsl::narrow_cast(this->_config.format); _av_frame_nn->width = this->_config.width; _av_frame_nn->height = this->_config.height; - _av_frame_nn->channels = this->_config.channels; + _av_frame_nn->ch_layout = this->_config.channel_layout; _av_frame_nn->sample_rate = this->_config.sample_rate; } const auto _av_frame_nn = gsl::narrow_cast(this->_av_frame); // move the owenership of data to buffer - if (p_data == nullptr) { + if (p_data.has_value()) { + this->_moved_data = std::exchange(*p_data.value(), nullptr); + } else { const auto _buffer_size = this->_config.get_required_buffer_size(); this->_moved_data = gsl::owner(malloc(_buffer_size)); - } else { - this->_moved_data = std::exchange(*p_data, nullptr); } - std::ignore = - av_image_fill_arrays(_av_frame_nn->data, _av_frame_nn->linesize, - gsl::narrow_cast(this->_moved_data), - this->_config.format, _av_frame_nn->width, - _av_frame_nn->height, _alignment); + std::ignore = av_image_fill_arrays(_av_frame_nn->data, _av_frame_nn->linesize, + gsl::narrow_cast(this->_moved_data), + this->_config.format, _av_frame_nn->width, + _av_frame_nn->height, _alignment); return 0; } @@ -125,7 +121,7 @@ w_av_frame::convert_video(_In_ const w_av_config &p_dst_config) { // create buffer and dst frame w_av_frame _dst_frame(p_dst_config); - _dst_frame.set(nullptr); + _dst_frame.set(); const auto _dst_avframe_nn = gsl::narrow_cast(_dst_frame._av_frame); @@ -157,9 +153,7 @@ w_av_frame::convert_video(_In_ const w_av_config &p_dst_config) { return _dst_frame; } -boost::leaf::result -w_av_frame::convert_audio(_In_ const w_av_config &p_dst_config) { - +boost::leaf::result w_av_frame::convert_audio(_In_ w_av_config &p_dst_config) { auto _ret = 0; SwrContext *swr = nullptr; w_av_frame _dst_frame = {}; @@ -175,22 +169,19 @@ w_av_frame::convert_audio(_In_ const w_av_config &p_dst_config) { } }); - swr = swr_alloc_set_opts( - swr, p_dst_config.channel_layout, p_dst_config.sample_fmts, - p_dst_config.sample_rate, this->_av_frame->channel_layout, - gsl::narrow_cast(this->_av_frame->format), - this->_av_frame->sample_rate, 0, NULL); + swr_alloc_set_opts2(&swr, &p_dst_config.channel_layout, p_dst_config.sample_fmts, + p_dst_config.sample_rate, &this->_av_frame->ch_layout, + gsl::narrow_cast(this->_av_frame->format), + this->_av_frame->sample_rate, 0, nullptr); if (swr == nullptr) { _ret = -1; - return W_FAILURE(std::errc::operation_canceled, - "could not create audio SwrContext"); + return W_FAILURE(std::errc::operation_canceled, "could not create audio SwrContext"); } _ret = swr_init(swr); if (_ret < 0) { - return W_FAILURE(std::errc::operation_canceled, - "could not initialize audio SwrContext"); + return W_FAILURE(std::errc::operation_canceled, "could not initialize audio SwrContext"); } // create buffer and dst frame @@ -198,42 +189,37 @@ w_av_frame::convert_audio(_In_ const w_av_config &p_dst_config) { _dst_frame.set(nullptr); // get number of samples - _dst_frame._av_frame->nb_samples = av_rescale_rnd( - swr_get_delay(swr, - gsl::narrow_cast(this->_av_frame->sample_rate)) + - this->_av_frame->nb_samples, - gsl::narrow_cast(p_dst_config.sample_rate), - gsl::narrow_cast(this->_av_frame->sample_rate), AV_ROUND_UP); - - _ret = av_samples_alloc( - gsl::narrow_cast(&_dst_frame._av_frame->data[0]), - &_dst_frame._av_frame->linesize[0], _dst_frame._av_frame->channels, - _dst_frame._av_frame->nb_samples, - gsl::narrow_cast(p_dst_config.sample_fmts), 1); + auto _sample_rate = gsl::narrow_cast(this->_av_frame->sample_rate); + auto _delay = swr_get_delay(swr, _sample_rate); + _dst_frame._av_frame->nb_samples = + av_rescale_rnd(_delay + _sample_rate, gsl::narrow_cast(p_dst_config.sample_rate), + _sample_rate, AV_ROUND_UP); + + _ret = av_samples_alloc(gsl::narrow_cast(&_dst_frame._av_frame->data[0]), + &_dst_frame._av_frame->linesize[0], + _dst_frame._av_frame->ch_layout.nb_channels, + _dst_frame._av_frame->nb_samples, + gsl::narrow_cast(p_dst_config.sample_fmts), 1); if (_ret < 0) { return W_FAILURE(std::errc::operation_canceled, "could not allocate memory for buffer of audio"); } /* convert to destination format */ - _ret = swr_convert( - swr, gsl::narrow_cast(&_dst_frame._av_frame->data[0]), - _dst_frame._av_frame->nb_samples, - (const uint8_t **)(&this->_av_frame->data[0]), - this->_av_frame->nb_samples); + _ret = swr_convert(swr, gsl::narrow_cast(&_dst_frame._av_frame->data[0]), + _dst_frame._av_frame->nb_samples, + (const uint8_t **)(&this->_av_frame->data[0]), this->_av_frame->nb_samples); if (_ret < 0) { - return W_FAILURE(std::errc::operation_canceled, - "error while audio converting\n"); + return W_FAILURE(std::errc::operation_canceled, "error while audio converting\n"); } - const auto _buffer_size = av_samples_get_buffer_size( - &_dst_frame._av_frame->linesize[0], _dst_frame._av_frame->channels, _ret, - p_dst_config.sample_fmts, 1); + const auto _buffer_size = av_samples_get_buffer_size(&_dst_frame._av_frame->linesize[0], + _dst_frame._av_frame->ch_layout.nb_channels, + _ret, p_dst_config.sample_fmts, 1); if (_buffer_size < 0) { _ret = -1; - return W_FAILURE(std::errc::operation_canceled, - "could not get sample buffer size\n"); + return W_FAILURE(std::errc::operation_canceled, "could not get sample buffer size\n"); } return _dst_frame; diff --git a/wolf/media/ffmpeg/w_av_frame.hpp b/wolf/media/ffmpeg/w_av_frame.hpp index 87411d55c..6d22c0499 100644 --- a/wolf/media/ffmpeg/w_av_frame.hpp +++ b/wolf/media/ffmpeg/w_av_frame.hpp @@ -19,7 +19,21 @@ extern "C" { namespace wolf::media::ffmpeg { -struct w_av_config { +class w_av_config { + public: + W_API w_av_config(_In_ AVPixelFormat p_format = AVPixelFormat::AV_PIX_FMT_NONE, + _In_ int p_width = 0, _In_ int p_height = 0) noexcept + : format(p_format), width(p_width), height(p_height) { + av_channel_layout_default(&this->channel_layout, 2); + } + + W_API ~w_av_config() noexcept { av_channel_layout_uninit(&this->channel_layout); } + + /** + * @returns the required buffer size for frame + */ + W_API int get_required_buffer_size() noexcept; + // the format of av frame AVPixelFormat format = AVPixelFormat::AV_PIX_FMT_NONE; // the width of av frame @@ -28,19 +42,12 @@ struct w_av_config { int height = 0; // data alignment int alignment = 1; - // the number of audio channels - int channels = 0; // the sample rate of the audio - int sample_rate = 0; + int sample_rate = 44100; // the sample format of the audio - AVSampleFormat sample_fmts; + AVSampleFormat sample_fmts = AV_SAMPLE_FMT_S16; // the channel layout of the audio - int channel_layout; - - /** - * @returns the required buffer size for frame - */ - W_API int get_required_buffer_size() noexcept; + AVChannelLayout channel_layout; }; class w_decoder; @@ -86,7 +93,7 @@ class w_av_frame { * @param p_alignment, the alignment * @returns zero on success */ - W_API boost::leaf::result set(_Inout_ uint8_t **p_data) noexcept; + W_API boost::leaf::result set(_Inout_ std::optional p_data = {}) noexcept; /** * set the AVFrame's pts @@ -116,7 +123,7 @@ class w_av_frame { */ W_API boost::leaf::result - convert_audio(_In_ const w_av_config &p_dst_config); + convert_audio(_In_ w_av_config &p_dst_config); /** * @returns av_config diff --git a/wolf/media/ffmpeg/w_decoder.cpp b/wolf/media/ffmpeg/w_decoder.cpp index 362ceb7f9..9b833fd6d 100644 --- a/wolf/media/ffmpeg/w_decoder.cpp +++ b/wolf/media/ffmpeg/w_decoder.cpp @@ -4,14 +4,13 @@ using w_decoder = wolf::media::ffmpeg::w_decoder; -boost::leaf::result w_decoder::_decode(_In_ AVPacket *p_packet, - _Inout_ w_av_frame &p_frame) { +boost::leaf::result w_decoder::_decode(_In_ AVPacket *p_packet, _Inout_ w_av_frame &p_frame) { // start decoding auto _ret = avcodec_send_packet(this->ctx.codec_ctx, p_packet); if (_ret < 0) { - return W_FAILURE(std::errc::operation_canceled, - "could not parse packet for decoding because of " + - w_ffmpeg_ctx::get_av_error_str(_ret)); + return W_FAILURE( + std::errc::operation_canceled, + "could not parse packet for decoding because of " + w_ffmpeg_ctx::get_av_error_str(_ret)); } for (;;) { @@ -20,9 +19,9 @@ boost::leaf::result w_decoder::_decode(_In_ AVPacket *p_packet, break; } if (_ret < 0) { - return W_FAILURE(std::errc::operation_canceled, - "error happened during the encoding because " + - w_ffmpeg_ctx::get_av_error_str(_ret)); + return W_FAILURE( + std::errc::operation_canceled, + "error happened during the encoding because " + w_ffmpeg_ctx::get_av_error_str(_ret)); } } return 0; @@ -35,22 +34,21 @@ boost::leaf::result w_decoder::decode(_In_ const w_av_packet &p_packet, _dst_packet.init(); for (;;) { - const auto _bytes = av_parser_parse2( - this->ctx.parser, this->ctx.codec_ctx, &_dst_packet._packet->data, - &_dst_packet._packet->size, p_packet._packet->data, - p_packet._packet->size, AV_NOPTS_VALUE, AV_NOPTS_VALUE, 0); + const auto _bytes = + av_parser_parse2(this->ctx.parser, this->ctx.codec_ctx, &_dst_packet._packet->data, + &_dst_packet._packet->size, p_packet._packet->data, p_packet._packet->size, + AV_NOPTS_VALUE, AV_NOPTS_VALUE, 0); if (_bytes == 0) { break; } if (_dst_packet._packet->size == 0) { - // try decode the inputed packet + // try decode the inputed packet BOOST_LEAF_CHECK(_decode(p_packet._packet, p_frame)); } else { if (_bytes < 0) { - return W_FAILURE(std::errc::operation_canceled, - "could not parse packet for decoding"); + return W_FAILURE(std::errc::operation_canceled, "could not parse packet for decoding"); } p_packet._packet->data += _bytes; p_packet._packet->size -= _bytes; diff --git a/wolf/media/test/avframe.hpp b/wolf/media/test/avframe.hpp index 06f5ce592..615f374dd 100644 --- a/wolf/media/test/avframe.hpp +++ b/wolf/media/test/avframe.hpp @@ -22,24 +22,21 @@ BOOST_AUTO_TEST_CASE(avframe_test) { using w_av_config = wolf::media::ffmpeg::w_av_config; // create av frame from img - const auto _current_dir = - std::filesystem::current_path().append("../../content/texture/rgb.png"); - auto _src_frame_res = w_av_frame::load_from_img_file( - _current_dir, AVPixelFormat::AV_PIX_FMT_RGBA); + const auto _current_dir = std::filesystem::current_path().append("../../content/texture/rgb.png"); + auto _src_frame_res = + w_av_frame::load_from_img_file(_current_dir, AVPixelFormat::AV_PIX_FMT_RGBA); BOOST_REQUIRE(_src_frame_res.has_error() == false); BOOST_REQUIRE(_src_frame_res.has_value() == true); auto _src_frame = &_src_frame_res.value(); const auto _config = _src_frame->get_config(); - w_av_config _dst_config = {AVPixelFormat::AV_PIX_FMT_BGRA, _config.width, - _config.height}; + w_av_config _dst_config = {AVPixelFormat::AV_PIX_FMT_BGRA, _config.width, _config.height}; auto _dst_frame_res = _src_frame->convert_video(_dst_config); BOOST_REQUIRE(_dst_frame_res.has_error() == false); BOOST_REQUIRE(_dst_frame_res.has_value() == true); - const auto _new_path = - std::filesystem::current_path().append("/rgb_converted.png"); + const auto _new_path = std::filesystem::current_path().append("/rgb_converted.png"); const auto _dst_frame = &_dst_frame_res.value(); auto _ret = _dst_frame->save_to_img_file(_new_path); BOOST_REQUIRE(_ret.has_error() == false); diff --git a/wolf/media/test/ffmpeg.hpp b/wolf/media/test/ffmpeg.hpp index 7a7431739..c4c31c5e0 100644 --- a/wolf/media/test/ffmpeg.hpp +++ b/wolf/media/test/ffmpeg.hpp @@ -21,26 +21,22 @@ using w_av_packet = wolf::media::ffmpeg::w_av_packet; using w_ffmpeg = wolf::media::ffmpeg::w_ffmpeg; static boost::leaf::result< - std::tuple> -s_encode(_In_ const std::string &p_name, - _In_ std::variant &p_codec_id, - _In_ const w_av_codec_opt &p_codec_options, - _In_ const std::vector &p_av_set_options, - _In_ const bool p_flush = true) { + std::tuple> s_encode( + _In_ const std::string &p_name, _In_ std::variant &p_codec_id, + _In_ const w_av_codec_opt &p_codec_options, + _In_ const std::vector &p_av_set_options, _In_ const bool p_flush = true) { // namespaces using w_encoder = wolf::media::ffmpeg::w_encoder; // create av frame from img - const auto _current_dir = - std::filesystem::current_path().append("../../content/texture/rgb.png"); + const auto _current_dir = std::filesystem::current_path().append("../../content/texture/rgb.png"); BOOST_LEAF_AUTO(_src_frame, - w_av_frame::load_from_img_file( - _current_dir, AVPixelFormat::AV_PIX_FMT_RGBA)); + w_av_frame::load_from_img_file(_current_dir, AVPixelFormat::AV_PIX_FMT_RGBA)); // source & destination configs const auto _src_config = _src_frame.get_config(); - const auto _dst_config = w_av_config{AVPixelFormat::AV_PIX_FMT_YUV420P, - _src_config.width, _src_config.height}; + const auto _dst_config = + w_av_config{AVPixelFormat::AV_PIX_FMT_YUV420P, _src_config.width, _src_config.height}; // convert source frame to yuv frame BOOST_LEAF_AUTO(_yuv_frame, _src_frame.convert_video(_dst_config)); @@ -49,12 +45,12 @@ s_encode(_In_ const std::string &p_name, boost::leaf::result _encoder_res; if (p_codec_id.index() == 0) { auto _codec_id = std::get<0>(p_codec_id); - _encoder_res = w_ffmpeg::create_encoder(_dst_config, _codec_id, - p_codec_options, p_av_set_options); + _encoder_res = + w_ffmpeg::create_encoder(_dst_config, _codec_id, p_codec_options, p_av_set_options); } else { const auto _codec_id = std::get<1>(p_codec_id); - _encoder_res = w_ffmpeg::create_encoder(_dst_config, _codec_id, - p_codec_options, p_av_set_options); + _encoder_res = + w_ffmpeg::create_encoder(_dst_config, _codec_id, p_codec_options, p_av_set_options); } // check encoder @@ -65,11 +61,9 @@ s_encode(_In_ const std::string &p_name, const auto _encoded_path = std::filesystem::current_path().append("/" + p_name + "_yuv_encoded.png"); - BOOST_LEAF_AUTO(final_encoded_result, - _yuv_frame.save_to_img_file(_encoded_path)); + BOOST_LEAF_AUTO(final_encoded_result, _yuv_frame.save_to_img_file(_encoded_path)); - return std::make_tuple(std::move(_packet), std::move(_src_config), - std::move(_dst_config)); + return std::make_tuple(std::move(_packet), std::move(_src_config), std::move(_dst_config)); } static boost::leaf::result s_decode( @@ -143,12 +137,10 @@ BOOST_AUTO_TEST_CASE(av1_encode_decode_test) { }; std::variant _encode_codec_id("libsvtav1"); - BOOST_LEAF_AUTO(_encoded_tuple, - s_encode(_name, _encode_codec_id, _codec_opt, _opts)); + BOOST_LEAF_AUTO(_encoded_tuple, s_encode(_name, _encode_codec_id, _codec_opt, _opts)); std::variant _decode_codec_id("libdav1d"); - BOOST_LEAF_CHECK( - s_decode(_encoded_tuple, _name, _decode_codec_id, _codec_opt, {})); + BOOST_LEAF_CHECK(s_decode(_encoded_tuple, _name, _decode_codec_id, _codec_opt, {})); return {}; }, @@ -185,13 +177,10 @@ BOOST_AUTO_TEST_CASE(vp9_encode_decode_test) { // for more info read https://trac.ffmpeg.org/wiki/Encode/VP9 const auto _opts = std::vector(); - std::variant _codec_id( - AVCodecID::AV_CODEC_ID_VP9); - BOOST_LEAF_AUTO(_encoded_tuple, - s_encode(_name, _codec_id, _codec_opt, _opts)); + std::variant _codec_id(AVCodecID::AV_CODEC_ID_VP9); + BOOST_LEAF_AUTO(_encoded_tuple, s_encode(_name, _codec_id, _codec_opt, _opts)); - BOOST_LEAF_CHECK( - s_decode(_encoded_tuple, _name, _codec_id, _codec_opt, {})); + BOOST_LEAF_CHECK(s_decode(_encoded_tuple, _name, _codec_id, _codec_opt, {})); return {}; }, @@ -230,13 +219,10 @@ BOOST_AUTO_TEST_CASE(x264_encode_decode_test) { w_av_set_opt{"profile", "main"}, w_av_set_opt{"preset", "veryfast"}, w_av_set_opt{"tune", "zerolatency"}, w_av_set_opt{"crf", 22}}; - std::variant _codec_id( - AVCodecID::AV_CODEC_ID_H264); - BOOST_LEAF_AUTO(_encoded_tuple, - s_encode(_name, _codec_id, _codec_opt, _opts)); + std::variant _codec_id(AVCodecID::AV_CODEC_ID_H264); + BOOST_LEAF_AUTO(_encoded_tuple, s_encode(_name, _codec_id, _codec_opt, _opts)); - BOOST_LEAF_CHECK( - s_decode(_encoded_tuple, _name, _codec_id, _codec_opt, {}, true)); + BOOST_LEAF_CHECK(s_decode(_encoded_tuple, _name, _codec_id, _codec_opt, {}, true)); return {}; }, diff --git a/wolf/media/test/image.hpp b/wolf/media/test/image.hpp index 2218b1a2a..b8f0252da 100644 --- a/wolf/media/test/image.hpp +++ b/wolf/media/test/image.hpp @@ -22,19 +22,16 @@ BOOST_AUTO_TEST_CASE(image_load_save_test) { using w_image = wolf::media::w_image; using w_image_data = wolf::media::w_image_data; - auto _rgb_file = std::filesystem::current_path().append( - "../../content/texture/rgb.png"); + auto _rgb_file = std::filesystem::current_path().append("../../content/texture/rgb.png"); auto _src_image_res = w_image::load(_rgb_file, 0); - // POOYA: don't use BOOST_LEAF_AUTO directly, because CodeCov might break + // POOYA: don't use BOOST_LEAF_AUTO directly, because CodeCov might break if (!_src_image_res.has_error()) { BOOST_LEAF_AUTO(_src_image, std::move(_src_image_res)); - const auto _bmp_path = - std::filesystem::current_path().append("/rgb_bmp.png"); + const auto _bmp_path = std::filesystem::current_path().append("/rgb_bmp.png"); BOOST_LEAF_CHECK(w_image::save_bmp(_bmp_path, _src_image)); constexpr auto _quality = 90; - const auto _jpg_path = - std::filesystem::current_path().append("/rgb_jpg.png"); + const auto _jpg_path = std::filesystem::current_path().append("/rgb_jpg.png"); BOOST_LEAF_CHECK(w_image::save_jpg(_jpg_path, _src_image, _quality)); } diff --git a/wolf/media/test/openal.hpp b/wolf/media/test/openal.hpp index c78e86343..99d08ddd3 100644 --- a/wolf/media/test/openal.hpp +++ b/wolf/media/test/openal.hpp @@ -22,8 +22,7 @@ BOOST_AUTO_TEST_CASE(openal_play_wav) { auto a = w_openal(); a.init(w_openal_config{}); - auto _current_dir = - std::filesystem::current_path().append("../../content/audio/sine.wav"); + auto _current_dir = std::filesystem::current_path().append("../../content/audio/sine.wav"); std::cout << _current_dir.string(); BOOST_REQUIRE(std::filesystem::exists(_current_dir) == true); @@ -34,7 +33,7 @@ BOOST_AUTO_TEST_CASE(openal_play_wav) { // else {current_dir.join(file_name)}; // make sure constructor works. later update with wav header. - //auto openal = w_openal{ + // auto openal = w_openal{ // w_openal_config{ // .format = AL_FORMAT_STEREO16, // .sample_rate = 48000, diff --git a/wolf/stream/test/ffmpeg_stream.hpp b/wolf/stream/test/ffmpeg_stream.hpp index 7648c32a2..29e8919ca 100644 --- a/wolf/stream/test/ffmpeg_stream.hpp +++ b/wolf/stream/test/ffmpeg_stream.hpp @@ -22,8 +22,7 @@ BOOST_AUTO_TEST_CASE(ffmpeg_stream_test) { using w_av_set_opt = wolf::media::ffmpeg::w_av_set_opt; const auto _opt = std::vector(); - constexpr auto _url = - "srt://127.0.0.1:554?mode=caller&transtype=live&timeout=5000000"; + constexpr auto _url = "srt://127.0.0.1:554?mode=caller&transtype=live&timeout=5000000"; boost::leaf::try_handle_all( [&]() -> boost::leaf::result { @@ -47,14 +46,13 @@ BOOST_AUTO_TEST_CASE(ffmpeg_stream_test) { wolf::media::ffmpeg::w_av_frame _av_audio_frame = {}; wolf::media::ffmpeg::w_av_config _audio_config = {}; wolf::media::w_openal_config _openal_config = {}; - //wolf::media::w_openal _openal = {}; + // wolf::media::w_openal _openal = {}; auto _width = 0; auto _height = 0; - auto _on_frame_cb = [&](const w_av_packet &p_packet, - const std::vector &p_streams, - const int p_video_stream_index, - const int p_audio_stream_index) -> bool { + auto _on_frame_cb = + [&](const w_av_packet &p_packet, const std::vector &p_streams, + const int p_video_stream_index, const int p_audio_stream_index) -> bool { const auto _stream_index = p_packet.get_stream_index(); if (_stream_index == p_video_stream_index) { std::cout << "got video frame" << std::endl; @@ -65,19 +63,9 @@ BOOST_AUTO_TEST_CASE(ffmpeg_stream_test) { _height = p_streams[p_video_stream_index]->codecpar->height; const auto _codec_id = _codec_param->codec_id; - const auto _fmt = - gsl::narrow_cast(_codec_param->format); - - const auto _config = w_av_config{ - // the format of av frame - _fmt, - // the width of av frame - _width, - // the height of av frame - _height, - // data alignment - 1, - }; + const auto _fmt = gsl::narrow_cast(_codec_param->format); + + const auto _config = w_av_config(_fmt, _width, _height); const auto _codec_opt = w_av_codec_opt{ _codec_param->bit_rate, /*bitrate*/ @@ -89,10 +77,9 @@ BOOST_AUTO_TEST_CASE(ffmpeg_stream_test) { -1, /*thread_count*/ }; - auto _decoder_res = - w_ffmpeg::create_decoder(_config, _codec_id, _codec_opt); + auto _decoder_res = w_ffmpeg::create_decoder(_config, _codec_id, _codec_opt); if (_decoder_res.has_error()) { - return false; // close it + return false; // close it } _video_decoder = std::move(_decoder_res.value()); @@ -102,7 +89,7 @@ BOOST_AUTO_TEST_CASE(ffmpeg_stream_test) { auto _decoded_frame_res = _av_video_frame.init(); if (_decoded_frame_res.has_error()) { std::cout << "could not initialize decoder" << std::endl; - return false; // close it + return false; // close it } _video_initialized = true; @@ -112,25 +99,15 @@ BOOST_AUTO_TEST_CASE(ffmpeg_stream_test) { if (_res.has_error()) { std::cout << "could not decode" << std::endl; } else { - const auto _dst_config = w_av_config{ - // the format of av frame - AVPixelFormat::AV_PIX_FMT_RGBA, - // the width of av frame - _width, - // the height of av frame - _height, - // data alignment - 1, - }; + const auto _dst_config = w_av_config(AVPixelFormat::AV_PIX_FMT_RGBA, _width, _height); auto _rgba_frame = _av_video_frame.convert_video(_dst_config); if (_rgba_frame.has_error()) { - std::cout << "could not convert av video frame to rgb frame" - << std::endl; + std::cout << "could not convert av video frame to rgb frame" << std::endl; } else { const auto _path = std::filesystem::current_path().append( "/" + std::to_string(_index++) + "_rist_decoded.png"); - // _rgba_frame.value().save_to_img_file(_path); + // _rgba_frame.value().save_to_img_file(_path); std::cout << "rgb frame created" << std::endl; } } @@ -146,14 +123,13 @@ BOOST_AUTO_TEST_CASE(ffmpeg_stream_test) { const auto _codec_opt = w_av_codec_opt{}; - auto _decoder_res = w_ffmpeg::create_decoder( - _audio_config, _codec_id, _codec_opt); + auto _decoder_res = w_ffmpeg::create_decoder(_audio_config, _codec_id, _codec_opt); if (_decoder_res.has_error()) { - return false; // close it + return false; // close it } - _audio_config.sample_fmts = gsl::narrow_cast( - *_decoder_res->ctx.codec->sample_fmts); + _audio_config.sample_fmts = + gsl::narrow_cast(*_decoder_res->ctx.codec->sample_fmts); _audio_decoder = std::move(_decoder_res.value()); // create destination avframe for decoder @@ -161,18 +137,18 @@ BOOST_AUTO_TEST_CASE(ffmpeg_stream_test) { auto _decoded_frame_res = _av_audio_frame.init(); if (_decoded_frame_res.has_error()) { std::cout << "could not initialize decoder" << std::endl; - return false; // close it + return false; // close it } - _openal_config = {AL_FORMAT_STEREO16, _audio_config.sample_rate, - 25, _audio_config.channels}; + _openal_config = {AL_FORMAT_STEREO16, _audio_config.sample_rate, 25, + _audio_config.channels}; - //auto _ret = _openal.init(_openal_config); + // auto _ret = _openal.init(_openal_config); - //if (_ret.has_error()) { - // std::cout << "could not initialize openal" << std::endl; - // return false; // close it - //} + // if (_ret.has_error()) { + // std::cout << "could not initialize openal" << std::endl; + // return false; // close it + // } _audio_initialized = true; } @@ -182,13 +158,10 @@ BOOST_AUTO_TEST_CASE(ffmpeg_stream_test) { std::cout << "could not decode" << std::endl; } else { auto _frame = _av_audio_frame.get(); - std::cout << "audio size: " - << gsl::narrow_cast(*std::get<1>(_frame)) + std::cout << "audio size: " << gsl::narrow_cast(*std::get<1>(_frame)) << std::endl; auto _dst_config = _audio_config; - _dst_config.sample_fmts = AV_SAMPLE_FMT_S16; - _dst_config.channel_layout = AV_CH_LAYOUT_STEREO; auto _audio_frame = _av_audio_frame.convert_audio(_dst_config); if (_audio_frame.has_error()) { @@ -200,7 +173,7 @@ BOOST_AUTO_TEST_CASE(ffmpeg_stream_test) { auto _data = std::get<0>(_content); auto _size = std::get<1>(_content); - if (_data && *_data && _size) { + if (_data && *_data && _size) { /*const auto _ret = _openal.update( gsl::narrow_cast(*_data), *_size); if (_ret.has_error()) { diff --git a/wolf/stream/test/rist.hpp b/wolf/stream/test/rist.hpp index 057409b7d..44bf48a92 100644 --- a/wolf/stream/test/rist.hpp +++ b/wolf/stream/test/rist.hpp @@ -27,9 +27,8 @@ BOOST_AUTO_TEST_CASE(rist_data_block_test) { _data_block.set(_block); auto _new_block = _data_block.get(); - const auto new_msg = std::string_view( - gsl::narrow_cast(std::get<0>(_new_block)), - std::get<1>(_new_block)); + const auto new_msg = std::string_view(gsl::narrow_cast(std::get<0>(_new_block)), + std::get<1>(_new_block)); BOOST_REQUIRE(new_msg == "hello"); } @@ -49,15 +48,14 @@ BOOST_AUTO_TEST_CASE(rist_sender_receiver_test) { constexpr auto _mode = rist_profile::RIST_PROFILE_MAIN; constexpr auto _loss = 0; - std::thread thread_sender([&]() { - boost::leaf::try_handle_all( - [&]() -> boost::leaf::result { - // create a rist sender - auto _sender = w_rist(rist_ctx_mode::RIST_SENDER_MODE, _mode, - _loss, - rist_log_level::RIST_LOG_DEBUG); - auto _ret = _sender.init(); - BOOST_REQUIRE(_ret.has_error() == false); + std::thread thread_sender([&]() { + boost::leaf::try_handle_all( + [&]() -> boost::leaf::result { + // create a rist sender + auto _sender = + w_rist(rist_ctx_mode::RIST_SENDER_MODE, _mode, _loss, rist_log_level::RIST_LOG_DEBUG); + auto _ret = _sender.init(); + BOOST_REQUIRE(_ret.has_error() == false); constexpr auto _url = "rist://" @@ -71,11 +69,8 @@ BOOST_AUTO_TEST_CASE(rist_sender_receiver_test) { static std::once_flag _once_flag; for (;;) { - - std::string _msg = - "hello from RIST stream: #" + std::to_string(_index++); - const auto _block = - std::make_tuple((void *)_msg.data(), _msg.size()); + std::string _msg = "hello from RIST stream: #" + std::to_string(_index++); + const auto _block = std::make_tuple((void *)_msg.data(), _msg.size()); auto _data_block = w_rist_data_block(); _data_block.set(_block); @@ -84,8 +79,7 @@ BOOST_AUTO_TEST_CASE(rist_sender_receiver_test) { BOOST_REQUIRE(_sent.has_error() == false); const auto t1 = std::chrono::high_resolution_clock::now(); - if (std::chrono::duration_cast(t1 - t0) > - _timeout_in_sec) { + if (std::chrono::duration_cast(t1 - t0) > _timeout_in_sec) { break; } std::this_thread::sleep_for(std::chrono::duration(1ms)); @@ -106,15 +100,14 @@ BOOST_AUTO_TEST_CASE(rist_sender_receiver_test) { std::thread thread_receiver([&]() { std::this_thread::sleep_for(std::chrono::duration(1s)); - auto _receiver = w_rist(rist_ctx_mode::RIST_RECEIVER_MODE, _mode, _loss, - rist_log_level::RIST_LOG_DEBUG); + auto _receiver = + w_rist(rist_ctx_mode::RIST_RECEIVER_MODE, _mode, _loss, rist_log_level::RIST_LOG_DEBUG); auto _ret = _receiver.init(); BOOST_REQUIRE(_ret.has_error() == false); - _receiver.on_receiver_data_callback = - [](_In_ const w_rist_data_block &p_data_block) { - std::cout << p_data_block.to_string() << std::endl; - }; + _receiver.on_receiver_data_callback = [](_In_ const w_rist_data_block &p_data_block) { + std::cout << p_data_block.to_string() << std::endl; + }; constexpr auto url = "rist://@" @@ -127,8 +120,7 @@ BOOST_AUTO_TEST_CASE(rist_sender_receiver_test) { const auto t0 = std::chrono::high_resolution_clock::now(); for (;;) { const auto t1 = std::chrono::high_resolution_clock::now(); - if (std::chrono::duration_cast(t1 - t0) > - _timeout_in_sec) { + if (std::chrono::duration_cast(t1 - t0) > _timeout_in_sec) { break; } std::this_thread::sleep_for(std::chrono::duration(1ms)); diff --git a/wolf/system/gamepad/w_gamepad_virtual.cpp b/wolf/system/gamepad/w_gamepad_virtual.cpp index 98e6c2892..05616e89b 100644 --- a/wolf/system/gamepad/w_gamepad_virtual.cpp +++ b/wolf/system/gamepad/w_gamepad_virtual.cpp @@ -4,9 +4,9 @@ using w_gamepad_virtual = wolf::system::gamepad::w_gamepad_virtual; -w_gamepad_virtual::w_gamepad_virtual(_In_ PVIGEM_CLIENT p_vigem, - _In_ PVIGEM_TARGET p_target) noexcept - : _vigem(p_vigem), _target(p_target) {} +w_gamepad_virtual::w_gamepad_virtual( + _In_ std::shared_ptr p_vigem_bus) noexcept + : _bus(std::move(p_vigem_bus)) {} w_gamepad_virtual::~w_gamepad_virtual() { _release(); } @@ -14,8 +14,7 @@ w_gamepad_virtual::w_gamepad_virtual(_Inout_ w_gamepad_virtual &&p_other) noexce _move(std::move(p_other)); } -w_gamepad_virtual & -w_gamepad_virtual::operator=(_Inout_ w_gamepad_virtual &&p_other) noexcept { +w_gamepad_virtual &w_gamepad_virtual::operator=(_Inout_ w_gamepad_virtual &&p_other) noexcept { _move(std::move(p_other)); return *this; } @@ -26,33 +25,62 @@ void w_gamepad_virtual::_move(_Inout_ w_gamepad_virtual &&p_other) noexcept { _release(); - this->_last_error = p_other._last_error; + this->_bus = std::move(p_other._bus); this->_target = std::exchange(p_other._target, nullptr); - this->_vigem = std::exchange(p_other._vigem, nullptr); + this->_last_error = p_other._last_error; +} + +boost::leaf::result w_gamepad_virtual::init() noexcept { + std::shared_lock _lock(this->_bus->mutex); + + if (this->_bus->driver_handle == nullptr) { + return W_FAILURE(VIGEM_ERROR::VIGEM_ERROR_BUS_INVALID_HANDLE, + "invalid ViGem bus while creating ViGem target controller"); + } + + // allocate handle to identify new pad + this->_target = vigem_target_x360_alloc(); + if (this->_target == nullptr) { + return W_FAILURE(VIGEM_ERROR::VIGEM_ERROR_TARGET_NOT_PLUGGED_IN, + "could not allocate memory while creating ViGem target controller"); + } + + // add client to the bus, this equals a plug-in event + auto _ret = vigem_target_add(this->_bus->driver_handle, this->_target); + if (_ret == VIGEM_ERROR::VIGEM_ERROR_NONE) { + return _ret; + } + return W_FAILURE(_ret, "could not add ViGem target controller to the bus"); } boost::leaf::result w_gamepad_virtual::clear_state() noexcept { + std::shared_lock _lock(this->_bus->mutex); + // xinput state - XINPUT_STATE _state = {0}; + XUSB_REPORT _state = {0}; // update x360 gamepad - const auto _ret = vigem_target_x360_update( - this->_vigem, this->_target, *reinterpret_cast(&_state)); - return _ret; + return vigem_target_x360_update(this->_bus->driver_handle, this->_target, _state); } boost::leaf::result w_gamepad_virtual::send_input(_In_ XINPUT_STATE &p_xinput) noexcept { + std::shared_lock _lock(this->_bus->mutex); + // update x360 gamepad - const auto _ret = vigem_target_x360_update( - this->_vigem, this->_target, + const auto _ret = vigem_target_x360_update(this->_bus->driver_handle, this->_target, *reinterpret_cast(&p_xinput.Gamepad)); return _ret; } void w_gamepad_virtual::_release() noexcept { + if (this->_bus == nullptr) + return; + + std::shared_lock _lock(this->_bus->mutex); + if (this->_target != nullptr) { - if (this->_vigem != nullptr) { - vigem_target_remove(this->_vigem, this->_target); + if (this->_bus->driver_handle != nullptr) { + vigem_target_remove(this->_bus->driver_handle, this->_target); } vigem_target_free(this->_target); } diff --git a/wolf/system/gamepad/w_gamepad_virtual.hpp b/wolf/system/gamepad/w_gamepad_virtual.hpp index b05bbae0d..eb5e7a2b7 100644 --- a/wolf/system/gamepad/w_gamepad_virtual.hpp +++ b/wolf/system/gamepad/w_gamepad_virtual.hpp @@ -9,16 +9,16 @@ #include #include -#include #include #include +#include "w_gamepad_virtual_bus.hpp" +#include namespace wolf::system::gamepad { struct w_gamepad_virtual { public: // default constructor - W_API w_gamepad_virtual(_In_ PVIGEM_CLIENT p_vigem, - _In_ PVIGEM_TARGET p_target) noexcept; + W_API w_gamepad_virtual(_In_ std::shared_ptr p_vigem_bus) noexcept; // destructor W_API virtual ~w_gamepad_virtual() noexcept; @@ -30,6 +30,12 @@ struct w_gamepad_virtual { W_API w_gamepad_virtual & operator=(_Inout_ w_gamepad_virtual &&p_other) noexcept; + /** + * initialize the gamepad + * @returns VIGEM_ERROR + */ + W_API boost::leaf::result init() noexcept; + /** * clear the state of this gamepad * @returns VIGEM_ERROR @@ -53,9 +59,9 @@ struct w_gamepad_virtual { void _move(_Inout_ w_gamepad_virtual &&p_other) noexcept; void _release() noexcept; - VIGEM_ERROR _last_error = VIGEM_ERROR::VIGEM_ERROR_NONE; - PVIGEM_CLIENT _vigem = nullptr; + std::shared_ptr _bus; PVIGEM_TARGET _target = nullptr; + VIGEM_ERROR _last_error = VIGEM_ERROR::VIGEM_ERROR_NONE; }; } // namespace wolf::system::gamepad diff --git a/wolf/system/gamepad/w_gamepad_virtual_bus.hpp b/wolf/system/gamepad/w_gamepad_virtual_bus.hpp new file mode 100644 index 000000000..10623a80d --- /dev/null +++ b/wolf/system/gamepad/w_gamepad_virtual_bus.hpp @@ -0,0 +1,19 @@ +/* + Project: Wolf Engine. Copyright © 2014-2023 Pooya Eimandar + https://github.com/WolfEngine/WolfEngine +*/ +#if defined(WOLF_SYSTEM_GAMEPAD_VIRTUAL) && !defined(EMSCRIPTEN) + +#pragma once + +#include "w_gamepad_virtual.hpp" +#include + +namespace wolf::system::gamepad { +struct w_gamepad_virtual_bus { + std::shared_mutex mutex = {}; + PVIGEM_CLIENT driver_handle = nullptr; +}; +} // namespace wolf::system::gamepad + +#endif // defined(WOLF_SYSTEM_VIRTUAL_GAMEPAD) && !defined(EMSCRIPTEN) diff --git a/wolf/system/gamepad/w_gamepad_virtual_pool.cpp b/wolf/system/gamepad/w_gamepad_virtual_pool.cpp index 11ba5d5ea..45f48d0e6 100644 --- a/wolf/system/gamepad/w_gamepad_virtual_pool.cpp +++ b/wolf/system/gamepad/w_gamepad_virtual_pool.cpp @@ -1,25 +1,28 @@ #if defined(WOLF_SYSTEM_GAMEPAD_VIRTUAL) && !defined(EMSCRIPTEN) #include "w_gamepad_virtual_pool.hpp" +#include using w_gamepad_virtual = wolf::system::gamepad::w_gamepad_virtual; using w_gamepad_virtual_pool = wolf::system::gamepad::w_gamepad_virtual_pool; +using w_gamepad_virtual_bus = wolf::system::gamepad::w_gamepad_virtual_bus; -static PVIGEM_CLIENT s_driver_handle = nullptr; +static auto s_bus = std::make_shared(); boost::leaf::result w_gamepad_virtual_pool::init() noexcept { + std::unique_lock lock(s_bus->mutex); + // check for driver handle memory - if (s_driver_handle == nullptr) { + if (s_bus->driver_handle == nullptr) { // allocate memory for bus driver - s_driver_handle = vigem_alloc(); - if (s_driver_handle == nullptr) { - return W_FAILURE(std::errc::not_enough_memory, - "could not allocate memory for ViGem client"); + s_bus->driver_handle = vigem_alloc(); + if (s_bus->driver_handle == nullptr) { + return W_FAILURE(std::errc::not_enough_memory, "could not allocate memory for ViGem client"); } } // connect to vigem - const auto _ret = vigem_connect(s_driver_handle); + const auto _ret = vigem_connect(s_bus->driver_handle); if (_ret != VIGEM_ERROR_NONE) { // release it fini(); @@ -29,37 +32,19 @@ boost::leaf::result w_gamepad_virtual_pool::init() noexcept { return _ret; } -boost::leaf::result -w_gamepad_virtual_pool::create() noexcept { - if (s_driver_handle == nullptr) { - return W_FAILURE(std::errc::host_unreachable, - "could not allocate memory for ViGem client"); - } - - // allocate handle to identify new pad - auto _handle = vigem_target_x360_alloc(); - if (_handle == nullptr) { - return W_FAILURE(std::errc::not_enough_memory, - "could not allocate memory for ViGem target client"); - } - - // add client to the bus, this equals a plug-in event - const auto _ret = vigem_target_add(s_driver_handle, _handle); - if (_ret != VIGEM_ERROR_NONE) { - return W_FAILURE( - std::errc::not_enough_memory, - "could not create ViGEm target device to bus driver because: " + - vigem_error_to_string(_ret)); - } - - return w_gamepad_virtual(s_driver_handle, _handle); +boost::leaf::result w_gamepad_virtual_pool::add() noexcept { + auto _gamepad = w_gamepad_virtual(s_bus); + BOOST_LEAF_AUTO(init_res, _gamepad.init()); + return _gamepad; } void w_gamepad_virtual_pool::fini() noexcept { - if (s_driver_handle) { - vigem_disconnect(s_driver_handle); - vigem_free(s_driver_handle); - s_driver_handle = nullptr; + std::unique_lock lock(s_bus->mutex); + + if (s_bus->driver_handle) { + vigem_disconnect(s_bus->driver_handle); + vigem_free(s_bus->driver_handle); + s_bus->driver_handle = nullptr; } } diff --git a/wolf/system/gamepad/w_gamepad_virtual_pool.hpp b/wolf/system/gamepad/w_gamepad_virtual_pool.hpp index a08e8c8a8..e39aefe65 100644 --- a/wolf/system/gamepad/w_gamepad_virtual_pool.hpp +++ b/wolf/system/gamepad/w_gamepad_virtual_pool.hpp @@ -22,7 +22,7 @@ class w_gamepad_virtual_pool { * add a gamepad to the ViGEm bus * @returns a tuple which contains index of gamepad and VIGEM_ERROR */ - W_API static boost::leaf::result create() noexcept; + W_API static boost::leaf::result add() noexcept; /** * convert a ViGEm error to string diff --git a/wolf/system/getopt.h b/wolf/system/getopt.h index 32b66601a..ceb5f3877 100644 --- a/wolf/system/getopt.h +++ b/wolf/system/getopt.h @@ -285,15 +285,14 @@ enum /* permitted values for its `has_arg' field... */ * Returns -1 if short_too is set and the option does not match long_options. */ static int parse_long_options(char *const *nargv, const char *options, - const struct option *long_options, int *idx, - int short_too) { + const struct option *long_options, int *idx, int short_too) { char *current_argv, *has_equal; size_t current_argv_len; int i, ambiguous, match; -#define IDENTICAL_INTERPRETATION(_x, _y) \ - (long_options[(_x)].has_arg == long_options[(_y)].has_arg && \ - long_options[(_x)].flag == long_options[(_y)].flag && \ +#define IDENTICAL_INTERPRETATION(_x, _y) \ + (long_options[(_x)].has_arg == long_options[(_y)].has_arg && \ + long_options[(_x)].flag == long_options[(_y)].flag && \ long_options[(_x)].val == long_options[(_y)].val) current_argv = (char *)place; @@ -311,8 +310,7 @@ static int parse_long_options(char *const *nargv, const char *options, for (i = 0; long_options[i].name; i++) { /* find matching long option */ - if (strncmp(current_argv, long_options[i].name, - current_argv_len)) + if (strncmp(current_argv, long_options[i].name, current_argv_len)) continue; if (strlen(long_options[i].name) == current_argv_len) { @@ -336,17 +334,14 @@ static int parse_long_options(char *const *nargv, const char *options, if (ambiguous) { /* ambiguous abbreviation */ if (PRINT_ERROR) - warnx(ambig, (int)current_argv_len, - current_argv); + warnx(ambig, (int)current_argv_len, current_argv); optopt = 0; return (BADCH); } if (match != -1) { /* option found */ - if (long_options[match].has_arg == no_argument && - has_equal) { + if (long_options[match].has_arg == no_argument && has_equal) { if (PRINT_ERROR) - warnx(noarg, (int)current_argv_len, - current_argv); + warnx(noarg, (int)current_argv_len, current_argv); /* * XXX: GNU sets optopt to val regardless of * flag @@ -361,8 +356,7 @@ static int parse_long_options(char *const *nargv, const char *options, long_options[match].has_arg == optional_argument) { if (has_equal) optarg = has_equal; - else if (long_options[match].has_arg == - required_argument) { + else if (long_options[match].has_arg == required_argument) { /* * optional argument doesn't use next * nargv @@ -370,8 +364,7 @@ static int parse_long_options(char *const *nargv, const char *options, optarg = nargv[optind++]; } } - if ((long_options[match].has_arg == - required_argument) && + if ((long_options[match].has_arg == required_argument) && (optarg == NULL)) { /* * Missing argument; leading ':' indicates no @@ -415,8 +408,7 @@ static int parse_long_options(char *const *nargv, const char *options, * Parse argc/argv argument vector. Called by user level routines. */ static int getopt_internal(int nargc, char *const *nargv, const char *options, - const struct option *long_options, int *idx, - int flags) { + const struct option *long_options, int *idx, int flags) { char *oli; /* option letter list index */ int optchar, short_too; static int posixly_correct = -1; @@ -457,8 +449,7 @@ static int getopt_internal(int nargc, char *const *nargv, const char *options, place = EMSG; if (nonopt_end != -1) { /* do permutation, if we have to */ - permute_args(nonopt_start, nonopt_end, - optind, nargv); + permute_args(nonopt_start, nonopt_end, optind, nargv); optind -= nonopt_end - nonopt_start; } else if (nonopt_start != -1) { /* @@ -471,8 +462,7 @@ static int getopt_internal(int nargc, char *const *nargv, const char *options, return (-1); } if (*(place = nargv[optind]) != '-' || - (place[1] == '\0' && - strchr(options, '-') == NULL)) { + (place[1] == '\0' && strchr(options, '-') == NULL)) { place = EMSG; /* found non-option */ if (flags & FLAG_ALLARGS) { /* @@ -494,10 +484,8 @@ static int getopt_internal(int nargc, char *const *nargv, const char *options, if (nonopt_start == -1) nonopt_start = optind; else if (nonopt_end != -1) { - permute_args(nonopt_start, nonopt_end, - optind, nargv); - nonopt_start = optind - (nonopt_end - - nonopt_start); + permute_args(nonopt_start, nonopt_end, optind, nargv); + nonopt_start = optind - (nonopt_end - nonopt_start); nonopt_end = -1; } optind++; @@ -510,8 +498,7 @@ static int getopt_internal(int nargc, char *const *nargv, const char *options, /* * If we have "-" do nothing, if "--" we are done. */ - if (place[1] != '\0' && *++place == '-' && - place[1] == '\0') { + if (place[1] != '\0' && *++place == '-' && place[1] == '\0') { optind++; place = EMSG; /* @@ -519,8 +506,7 @@ static int getopt_internal(int nargc, char *const *nargv, const char *options, * non-options, we have to permute. */ if (nonopt_end != -1) { - permute_args(nonopt_start, nonopt_end, - optind, nargv); + permute_args(nonopt_start, nonopt_end, optind, nargv); optind -= nonopt_end - nonopt_start; } nonopt_start = nonopt_end = -1; @@ -539,12 +525,10 @@ static int getopt_internal(int nargc, char *const *nargv, const char *options, short_too = 0; if (*place == '-') place++; /* --foo long option */ - else if (*place != ':' && - strchr(options, *place) != NULL) + else if (*place != ':' && strchr(options, *place) != NULL) short_too = 1; /* could be short option too */ - optchar = parse_long_options( - nargv, options, long_options, idx, short_too); + optchar = parse_long_options(nargv, options, long_options, idx, short_too); if (optchar != -1) { place = EMSG; return (optchar); @@ -581,8 +565,7 @@ static int getopt_internal(int nargc, char *const *nargv, const char *options, return (BADARG); } else /* white space */ place = nargv[optind]; - optchar = parse_long_options(nargv, options, - long_options, idx, 0); + optchar = parse_long_options(nargv, options, long_options, idx, 0); place = EMSG; return (optchar); } @@ -616,9 +599,7 @@ static int getopt_internal(int nargc, char *const *nargv, const char *options, */ int getopt_long(int nargc, char *const *nargv, const char *options, const struct option *long_options, int *idx) { - - return (getopt_internal(nargc, nargv, options, long_options, - idx, FLAG_PERMUTE)); + return (getopt_internal(nargc, nargv, options, long_options, idx, FLAG_PERMUTE)); } /* @@ -627,9 +608,8 @@ int getopt_long(int nargc, char *const *nargv, const char *options, */ int getopt_long_only(int nargc, char *const *nargv, const char *options, const struct option *long_options, int *idx) { - - return (getopt_internal(nargc, nargv, options, long_options, - idx, FLAG_PERMUTE | FLAG_LONGONLY)); + return (getopt_internal(nargc, nargv, options, long_options, idx, + FLAG_PERMUTE | FLAG_LONGONLY)); } // extern int getopt_long(int nargc, char * const *nargv, const char *options, diff --git a/wolf/system/socket/w_tcp_server.cpp b/wolf/system/socket/w_tcp_server.cpp index 95a8ba692..b9004f67e 100644 --- a/wolf/system/socket/w_tcp_server.cpp +++ b/wolf/system/socket/w_tcp_server.cpp @@ -38,8 +38,8 @@ static boost::asio::awaitable on_handle_session( const boost::asio::io_context &p_io_context, tcp::socket &p_socket, const std::string &p_conn_id, time_point &p_deadline, steady_clock::duration p_timeout, - const w_session_on_data_callback &p_on_data_callback, - const w_session_on_error_callback &p_on_error_callback) noexcept { + const w_session_on_data_callback p_on_data_callback, + const w_session_on_error_callback p_on_error_callback) noexcept { w_buffer _buffer = {}; #ifdef __clang__ diff --git a/wolf/system/socket/w_ws_client.cpp b/wolf/system/socket/w_ws_client.cpp index f6e31d831..8b223676d 100644 --- a/wolf/system/socket/w_ws_client.cpp +++ b/wolf/system/socket/w_ws_client.cpp @@ -87,10 +87,11 @@ w_ws_client::async_read(_Inout_ w_buffer &p_mut_buffer) { boost::beast::flat_buffer _buffer = {}; co_await this->_ws->async_read(_buffer); - // an extra copy just for having stable ABI + // an extra copy just for having a stable ABI const auto _size = std::min(_buffer.cdata().size(), p_mut_buffer.buf.size()); std::memcpy(p_mut_buffer.buf.data(), static_cast(_buffer.cdata().data()), _size); + co_return _size; } boost::asio::awaitable diff --git a/wolf/system/socket/w_ws_server.cpp b/wolf/system/socket/w_ws_server.cpp index f1b4f4d1f..cd902512c 100644 --- a/wolf/system/socket/w_ws_server.cpp +++ b/wolf/system/socket/w_ws_server.cpp @@ -13,7 +13,7 @@ using tcp = boost::asio::ip::tcp; static boost::asio::awaitable s_session(_In_ const boost::asio::io_context &p_io_context, _In_ w_ws_stream &&p_ws, - _In_ const std::string &p_conn_id, + _In_ const std::string p_conn_id, _In_ w_session_ws_on_data_callback p_on_data_callback, _In_ w_session_on_error_callback p_on_error_callback) { diff --git a/wolf/system/test/compress.hpp b/wolf/system/test/compress.hpp index 591af5dcb..f9627a98d 100644 --- a/wolf/system/test/compress.hpp +++ b/wolf/system/test/compress.hpp @@ -29,24 +29,20 @@ BOOST_AUTO_TEST_CASE(compress_lz4_test) { "HELLO WOLF\r\nHELLO WOLF!*&%!HELLO WOLF!07*&%!\r\nThe quick " "brown fox jumps over the lazy dog!"; - const auto _bytes = std::span( - reinterpret_cast(_mock_compression_data), - strlen(_mock_compression_data)); + const auto _bytes = std::span(reinterpret_cast(_mock_compression_data), + strlen(_mock_compression_data)); const auto _bytes_len = _bytes.size(); constexpr auto _max_retry = 10; BOOST_LEAF_AUTO(_compress_default, lz4::compress_default(_bytes)); - BOOST_LEAF_AUTO(_decompress_default, - lz4::decompress(_compress_default, _max_retry)); + BOOST_LEAF_AUTO(_decompress_default, lz4::decompress(_compress_default, _max_retry)); BOOST_REQUIRE_EQUAL(_decompress_default.size(), _bytes_len); constexpr auto _acceleration = 1000; - BOOST_LEAF_AUTO(_compress_fast, - lz4::compress_fast(_bytes, _acceleration)); + BOOST_LEAF_AUTO(_compress_fast, lz4::compress_fast(_bytes, _acceleration)); - BOOST_LEAF_AUTO(_decompress_fast, - lz4::decompress(_compress_fast, _max_retry)); + BOOST_LEAF_AUTO(_decompress_fast, lz4::decompress(_compress_fast, _max_retry)); BOOST_REQUIRE_EQUAL(_decompress_fast.size(), _bytes_len); return {}; @@ -80,20 +76,17 @@ BOOST_AUTO_TEST_CASE(compress_lzma_test) { "HELLO WOLF\r\nHELLO WOLF!*&%!HELLO WOLF!07*&%!\r\nThe quick " "brown fox jumps over the lazy dog!"; - const auto _bytes = std::span( - reinterpret_cast(_mock_compression_data), - strlen(_mock_compression_data)); + const auto _bytes = std::span(reinterpret_cast(_mock_compression_data), + strlen(_mock_compression_data)); const auto _bytes_len = _bytes.size(); BOOST_LEAF_AUTO(_compress_lzm1, lzma::compress_lzma1(_bytes, 7)); - BOOST_LEAF_AUTO(_decompress_lzm1, - lzma::decompress_lzma1(_compress_lzm1)); + BOOST_LEAF_AUTO(_decompress_lzm1, lzma::decompress_lzma1(_compress_lzm1)); BOOST_LEAF_AUTO(_compress_lzm2, lzma::compress_lzma2(_bytes, 7)); - BOOST_LEAF_AUTO(_decompress_lzm2, - lzma::decompress_lzma2(_compress_lzm2)); + BOOST_LEAF_AUTO(_decompress_lzm2, lzma::decompress_lzma2(_compress_lzm2)); return {}; }, diff --git a/wolf/system/test/coroutine.hpp b/wolf/system/test/coroutine.hpp index 2a81b4cb7..9c7ae15f2 100644 --- a/wolf/system/test/coroutine.hpp +++ b/wolf/system/test/coroutine.hpp @@ -29,8 +29,7 @@ BOOST_AUTO_TEST_CASE(coroutine_test) { [&]() -> boost::asio::awaitable { using namespace boost::asio::experimental::awaitable_operators; - auto _coro = [](_In_ bool p_abort) noexcept - -> boost::asio::awaitable { + auto _coro = [](_In_ bool p_abort) noexcept -> boost::asio::awaitable { if (p_abort) { co_return std::errc::connection_aborted; } diff --git a/wolf/system/test/gamepad.hpp b/wolf/system/test/gamepad.hpp index f84f6902a..8b62f8b51 100644 --- a/wolf/system/test/gamepad.hpp +++ b/wolf/system/test/gamepad.hpp @@ -5,8 +5,6 @@ #ifdef WOLF_TEST -#pragma once - #include #include #include @@ -40,10 +38,10 @@ BOOST_AUTO_TEST_CASE(gamepad_virtual_test) { boost::leaf::try_handle_all( [&]() -> boost::leaf::result { // create 4 gamepads and destroy them at the end of their lifetime - BOOST_LEAF_AUTO(_gamepad_1, w_gamepad_virtual_pool::create()); - BOOST_LEAF_AUTO(_gamepad_2, w_gamepad_virtual_pool::create()); - BOOST_LEAF_AUTO(_gamepad_3, w_gamepad_virtual_pool::create()); - BOOST_LEAF_AUTO(_gamepad_4, w_gamepad_virtual_pool::create()); + BOOST_LEAF_AUTO(_gamepad_1, w_gamepad_virtual_pool::add()); + BOOST_LEAF_AUTO(_gamepad_2, w_gamepad_virtual_pool::add()); + BOOST_LEAF_AUTO(_gamepad_3, w_gamepad_virtual_pool::add()); + BOOST_LEAF_AUTO(_gamepad_4, w_gamepad_virtual_pool::add()); return {}; }, diff --git a/wolf/system/test/gametime.hpp b/wolf/system/test/gametime.hpp index 1c4a63582..b01abaca5 100644 --- a/wolf/system/test/gametime.hpp +++ b/wolf/system/test/gametime.hpp @@ -24,7 +24,7 @@ BOOST_AUTO_TEST_CASE(gametime_fixed_time_test) { bool _ticked = false; constexpr double _stop_after_secs = 3.0; - constexpr double _target_elapsed_secs = 1.0 / 50.0; // 50 fps + constexpr double _target_elapsed_secs = 1.0 / 50.0; // 50 fps auto _gametime = w_gametime(); _gametime.reset(); @@ -52,7 +52,7 @@ BOOST_AUTO_TEST_CASE(gametime_unfixed_time_test) { std::cout << "gametime_unfixed_time_test is running" << std::endl; constexpr double _stop_after_secs = 5.0; - constexpr double _target_elapsed_secs = 1.0 / 50.0; // 50 fps + constexpr double _target_elapsed_secs = 1.0 / 50.0; // 50 fps auto _gametime = w_gametime(); _gametime.reset(); diff --git a/wolf/system/test/log.hpp b/wolf/system/test/log.hpp index dd1515b0b..0692f0b66 100644 --- a/wolf/system/test/log.hpp +++ b/wolf/system/test/log.hpp @@ -90,8 +90,7 @@ BOOST_AUTO_TEST_CASE(log_stress_test) { const auto time_2 = std::chrono::high_resolution_clock::now(); const auto _delta = - std::chrono::duration_cast(time_2 - time_1) - .count(); + std::chrono::duration_cast(time_2 - time_1).count(); if (_delta > _max_delta_in_sec) { break; } diff --git a/wolf/system/test/postgresql.hpp b/wolf/system/test/postgresql.hpp index b761f2690..38ea9f911 100644 --- a/wolf/system/test/postgresql.hpp +++ b/wolf/system/test/postgresql.hpp @@ -15,68 +15,58 @@ using wolf::system::pgdb::w_pgdb_record; #define POSTGRESQL_SERVER_ADDRESS "172.26.218.210" -BOOST_AUTO_TEST_CASE(postgresql_client_connection) -{ - // example: connect to database by url string. - boost::leaf::try_handle_all( - []() -> boost::leaf::result { - constexpr auto conn_info_str = "postgresql://root@" POSTGRESQL_SERVER_ADDRESS ":26257/defaultdb"; - auto conn = w_pgdb_conection::make(conn_info_str); - - BOOST_LEAF_CHECK(conn); - - return {}; - }, - [](const w_trace &p_trace) { - std::cout << "got error :" << p_trace << std::endl; - BOOST_REQUIRE(false); - }, - [] { - std::cout << "got an error!" << std::endl; - BOOST_ERROR(false); - } - ); - - // example: connect to database by parameter pairs. - boost::leaf::try_handle_all( - []() -> boost::leaf::result { - auto conn = w_pgdb_conection::make( - std::pair{"host", POSTGRESQL_SERVER_ADDRESS}, - std::pair{"port", "26257"}, - std::pair{"user", "root"}, - std::pair{"password", ""}, - std::pair{"dbname", "defaultdb"} - ); - BOOST_LEAF_CHECK(conn); - - return {}; - }, - [](const w_trace &p_trace) { - std::cout << "got error :" << p_trace << std::endl; - BOOST_REQUIRE(false); - }, - [] { - std::cout << "got an error!" << std::endl; - BOOST_ERROR(false); - } - ); +BOOST_AUTO_TEST_CASE(postgresql_client_connection) { + // example: connect to database by url string. + boost::leaf::try_handle_all( + []() -> boost::leaf::result { + constexpr auto conn_info_str = + "postgresql://root@" POSTGRESQL_SERVER_ADDRESS ":26257/defaultdb"; + auto conn = w_pgdb_conection::make(conn_info_str); + + BOOST_LEAF_CHECK(conn); + + return {}; + }, + [](const w_trace &p_trace) { + std::cout << "got error :" << p_trace << std::endl; + BOOST_REQUIRE(false); + }, + [] { + std::cout << "got an error!" << std::endl; + BOOST_ERROR(false); + }); + + // example: connect to database by parameter pairs. + boost::leaf::try_handle_all( + []() -> boost::leaf::result { + auto conn = w_pgdb_conection::make( + std::pair{"host", POSTGRESQL_SERVER_ADDRESS}, std::pair{"port", "26257"}, + std::pair{"user", "root"}, std::pair{"password", ""}, std::pair{"dbname", "defaultdb"}); + BOOST_LEAF_CHECK(conn); + + return {}; + }, + [](const w_trace &p_trace) { + std::cout << "got error :" << p_trace << std::endl; + BOOST_REQUIRE(false); + }, + [] { + std::cout << "got an error!" << std::endl; + BOOST_ERROR(false); + }); } -BOOST_AUTO_TEST_CASE(postgresql_client_commands_and_queries) -{ +BOOST_AUTO_TEST_CASE(postgresql_client_commands_and_queries) { struct User { - std::string name = ""; - int age = 0; + std::string name = ""; + int age = 0; }; - constexpr auto conn_info_str = "postgresql://root@" POSTGRESQL_SERVER_ADDRESS ":26257/defaultdb"; + constexpr auto conn_info_str = + "postgresql://root@" POSTGRESQL_SERVER_ADDRESS ":26257/defaultdb"; - const User users[] = { - User{ .name = "Lizard", .age = 12 }, - User{ .name = "Haxorer", .age = 15 }, - User{ .name = "BlueRose", .age = 16 }, - User{ .name = "Cthulhu", .age = 18 } - }; + const User users[] = {User{.name = "Lizard", .age = 12}, User{.name = "Haxorer", .age = 15}, + User{.name = "BlueRose", .age = 16}, User{.name = "Cthulhu", .age = 18}}; auto conn = w_pgdb_conection::make(conn_info_str); @@ -85,81 +75,73 @@ BOOST_AUTO_TEST_CASE(postgresql_client_commands_and_queries) // example: create a table to operate on boost::leaf::try_handle_all( [&]() -> boost::leaf::result { - auto res = conn->execute( - "CREATE TABLE IF NOT EXISTS Users(" - " id SERIAL NOT NULL PRIMARY KEY," - " name STRING UNIQUE NOT NULL," - " age INT NOT NULL" - ");" - ); - BOOST_LEAF_CHECK(res); + auto res = conn->execute( + "CREATE TABLE IF NOT EXISTS Users(" + " id SERIAL NOT NULL PRIMARY KEY," + " name STRING UNIQUE NOT NULL," + " age INT NOT NULL" + ");"); + BOOST_LEAF_CHECK(res); - res->done(); + res->done(); - // clean up before insertions. - BOOST_LEAF_CHECK(conn->execute("DELETE FROM Users;")); + // clean up before insertions. + BOOST_LEAF_CHECK(conn->execute("DELETE FROM Users;")); - return {}; + return {}; }, [](const w_trace &p_trace) { - std::cout << "got error :" << p_trace << std::endl; - BOOST_REQUIRE(false); + std::cout << "got error :" << p_trace << std::endl; + BOOST_REQUIRE(false); }, [] { - std::cout << "got an error!" << std::endl; - BOOST_ERROR(false); - } - ); + std::cout << "got an error!" << std::endl; + BOOST_ERROR(false); + }); // example: inserts boost::leaf::try_handle_all( [&]() -> boost::leaf::result { - BOOST_REQUIRE(std::size(users) > 0); - - for (const auto& user : users) { - auto res = conn->execute( - "INSERT INTO Users(name, age) VALUES($1, $2);", - user.name, - user.age - ); - BOOST_LEAF_ASSERT(res); - } - - // make sure error on uniqe name is caught. - auto res = conn->execute( - "INSERT INTO Users(name, age) VALUES($1, $2);", - users[0].name, - users[0].age - ); - BOOST_REQUIRE(!res); + BOOST_REQUIRE(std::size(users) > 0); - return {}; + for (const auto &user : users) { + auto res = + conn->execute("INSERT INTO Users(name, age) VALUES($1, $2);", user.name, user.age); + BOOST_LEAF_ASSERT(res); + } + + // make sure error on uniqe name is caught. + auto res = conn->execute("INSERT INTO Users(name, age) VALUES($1, $2);", users[0].name, + users[0].age); + BOOST_REQUIRE(!res); + + return {}; }, [](const w_trace &p_trace) { - std::cout << "got error :" << p_trace << std::endl; - BOOST_REQUIRE(false); + std::cout << "got error :" << p_trace << std::endl; + BOOST_REQUIRE(false); }, [] { - std::cout << "got an error!" << std::endl; - BOOST_ERROR(false); - } - ); + std::cout << "got an error!" << std::endl; + BOOST_ERROR(false); + }); // example: query, multiple rows, buffered (first fetches all then iterates) boost::leaf::try_handle_all( - [&]() -> boost::leaf::result { - auto res = conn->stream_query("SELECT name, age FROM Users;"); - BOOST_LEAF_CHECK(res); + [&]() -> boost::leaf::result { + auto res = conn->stream_query("SELECT name, age FROM Users;"); + BOOST_LEAF_CHECK(res); - BOOST_CHECK(!res->is_empty()); + BOOST_CHECK(!res->is_empty()); - BOOST_REQUIRE(res->field_count() == 2); - BOOST_REQUIRE(res->size() == std::size(users)); + BOOST_REQUIRE(res->field_count() == 2); + BOOST_REQUIRE(res->size() == std::size(users)); - BOOST_CHECK(res->field_name_at(0) == std::string("name")); - BOOST_CHECK(res->field_name_at(1) == std::string("age")); + BOOST_CHECK(res->field_name_at(0) == std::string("name")); + BOOST_CHECK(res->field_name_at(1) == std::string("age")); - BOOST_LEAF_CHECK(res->on_each([&, counter=0](w_pgdb_record record) mutable -> boost::leaf::result { + BOOST_LEAF_CHECK(res->on_each( + [&, counter = 0](w_pgdb_record record) mutable -> boost::leaf::result { User user; BOOST_REQUIRE(counter < std::size(users)); @@ -172,46 +154,44 @@ BOOST_AUTO_TEST_CASE(postgresql_client_commands_and_queries) ++counter; return {}; - })); + })); - return {}; + return {}; }, [](const w_trace &p_trace) { - std::cout << "got error :" << p_trace << std::endl; - BOOST_REQUIRE(false); + std::cout << "got error :" << p_trace << std::endl; + BOOST_REQUIRE(false); }, [] { - std::cout << "got an error!" << std::endl; - BOOST_ERROR(false); - } - ); + std::cout << "got an error!" << std::endl; + BOOST_ERROR(false); + }); // example: query, single result boost::leaf::try_handle_all( [&]() -> boost::leaf::result { - auto res = conn->query("SELECT version();"); - BOOST_LEAF_CHECK(res); + auto res = conn->query("SELECT version();"); + BOOST_LEAF_CHECK(res); - BOOST_LEAF_CHECK(res->on_single([](w_pgdb_record record) -> boost::leaf::result { - auto version_str = record.at(0); - BOOST_REQUIRE(version_str); + BOOST_LEAF_CHECK(res->on_single([](w_pgdb_record record) -> boost::leaf::result { + auto version_str = record.at(0); + BOOST_REQUIRE(version_str); - std::cout << "postgresql test: database version is:" << version_str << std::endl; - - return {}; - })); + std::cout << "postgresql test: database version is:" << version_str << std::endl; return {}; + })); + + return {}; }, [](const w_trace &p_trace) { - std::cout << "got error :" << p_trace << std::endl; - BOOST_REQUIRE(false); + std::cout << "got error :" << p_trace << std::endl; + BOOST_REQUIRE(false); }, [] { - std::cout << "got an error!" << std::endl; - BOOST_ERROR(false); - } - ); + std::cout << "got an error!" << std::endl; + BOOST_ERROR(false); + }); } #endif // WOLF_TEST diff --git a/wolf/system/test/tcp.hpp b/wolf/system/test/tcp.hpp index 830833e8b..090de601b 100644 --- a/wolf/system/test/tcp.hpp +++ b/wolf/system/test/tcp.hpp @@ -39,15 +39,13 @@ BOOST_AUTO_TEST_CASE(tcp_server_timeout_test) { _io, std::move(_endpoint), std::move(timeout), std::move(_opts), [](const std::string &p_conn_id, w_buffer &p_mut_data) -> auto{ std::cout << "tcp server just got: /'" << p_mut_data.to_string() << "/'" - << " and " << p_mut_data.used_bytes - << " bytes from connection id: " << p_conn_id << std::endl; + << " and " << p_mut_data.used_bytes << " bytes from connection id: " << p_conn_id + << std::endl; return boost::system::errc::connection_aborted; }, - [](const std::string &p_conn_id, - const boost::system::system_error &p_error) { - std::cout << "timeout for connection: " << p_conn_id << " because of " - << p_error.what() << "error code: " << p_error.code() - << std::endl; + [](const std::string &p_conn_id, const boost::system::system_error &p_error) { + std::cout << "timeout for connection: " << p_conn_id << " because of " << p_error.what() + << "error code: " << p_error.code() << std::endl; }); _io.run(); @@ -131,9 +129,8 @@ BOOST_AUTO_TEST_CASE(tcp_read_write_test) { auto _timer = w_timer(_io); _timer.expires_after(_timeout); - auto _resolve_res = - co_await (_timer.async_wait(boost::asio::use_awaitable) || - _client.async_resolve("127.0.0.1", 8080)); + auto _resolve_res = co_await (_timer.async_wait(boost::asio::use_awaitable) || + _client.async_resolve("127.0.0.1", 8080)); // expect resolve BOOST_REQUIRE(_resolve_res.index() == 1); @@ -142,9 +139,8 @@ BOOST_AUTO_TEST_CASE(tcp_read_write_test) { const auto _endpoint = _endpoints.cbegin()->endpoint(); - auto _conn_res = - co_await (_timer.async_wait(boost::asio::use_awaitable) || - _client.async_connect(_endpoint, _opts)); + auto _conn_res = co_await (_timer.async_wait(boost::asio::use_awaitable) || + _client.async_connect(_endpoint, _opts)); // expect the connection BOOST_REQUIRE(_conn_res.index() == 1); @@ -164,8 +160,8 @@ BOOST_AUTO_TEST_CASE(tcp_read_write_test) { BOOST_REQUIRE(_res.index() == 1); _recv_buffer.used_bytes = std::get<1>(_res); - BOOST_REQUIRE(_recv_buffer.used_bytes == 10); // hello-back - BOOST_REQUIRE(_recv_buffer.to_string() == "hello-back"); // hello-back + BOOST_REQUIRE(_recv_buffer.used_bytes == 10); // hello-back + BOOST_REQUIRE(_recv_buffer.to_string() == "hello-back"); // hello-back } _send_buffer.from_string("exit"); @@ -185,8 +181,7 @@ BOOST_AUTO_TEST_CASE(tcp_read_write_test) { // command from client w_tcp_server::run( _io, std::move(_endpoint), _timeout, std::move(_opts), - [](_In_ const std::string &p_conn_id, - _Inout_ w_buffer &p_mut_data) -> auto{ + [](_In_ const std::string &p_conn_id, _Inout_ w_buffer &p_mut_data) -> auto{ // close on overflow if (p_mut_data.used_bytes > 1025) { return boost::system::errc::connection_aborted; @@ -194,8 +189,8 @@ BOOST_AUTO_TEST_CASE(tcp_read_write_test) { auto _reply = std::string(p_mut_data.buf.data(), p_mut_data.used_bytes); - std::cout << "tcp server just got: \"" << _reply - << "\" from connection id: " << p_conn_id << std::endl; + std::cout << "tcp server just got: \"" << _reply << "\" from connection id: " << p_conn_id + << std::endl; if (_reply == "exit") { return boost::system::errc::connection_aborted; @@ -204,11 +199,9 @@ BOOST_AUTO_TEST_CASE(tcp_read_write_test) { p_mut_data.from_string(_reply); return boost::system::errc::success; }, - [&](const std::string &p_conn_id, - const boost::system::system_error &p_error) { - std::cout << "error happened for connection: " << p_conn_id - << " because of " << p_error.what() - << " error code: " << p_error.code() << std::endl; + [&](const std::string &p_conn_id, const boost::system::system_error &p_error) { + std::cout << "error happened for connection: " << p_conn_id << " because of " + << p_error.what() << " error code: " << p_error.code() << std::endl; _io.stop(); }); diff --git a/wolf/system/test/trace.hpp b/wolf/system/test/trace.hpp index 01cd857f7..194655888 100644 --- a/wolf/system/test/trace.hpp +++ b/wolf/system/test/trace.hpp @@ -20,9 +20,7 @@ BOOST_AUTO_TEST_CASE(trace_test) { return W_FAILURE(std::errc::bad_message, "error from function 1"); }; - const auto _function_2 = [&]() noexcept -> boost::leaf::result { - return _function_1(); - }; + const auto _function_2 = [&]() noexcept -> boost::leaf::result { return _function_1(); }; // how to use w_trace boost::leaf::try_handle_all( diff --git a/wolf/system/test/ws.hpp b/wolf/system/test/ws.hpp index c6c0b769e..2ed9e2ac8 100644 --- a/wolf/system/test/ws.hpp +++ b/wolf/system/test/ws.hpp @@ -36,28 +36,24 @@ BOOST_AUTO_TEST_CASE(ws_server_timeout_test) { _io.stop(); }); - const auto _timeout = - boost::beast::websocket::stream_base::timeout{// handshake_timeout - 5s, - // idle_timeout - 5s, - // keep_alive_pings - false}; + const auto _timeout = boost::beast::websocket::stream_base::timeout{// handshake_timeout + 5s, + // idle_timeout + 5s, + // keep_alive_pings + false}; w_ws_server::run( _io, std::move(_endpoint), _timeout, std::move(_opts), [](const std::string &p_conn_id, _Inout_ w_buffer &p_buffer, _Inout_ bool &p_is_binary) -> auto{ - std::cout << "websocket server just got: /'" << p_buffer.to_string() - << "/' and " << p_buffer.used_bytes - << " bytes from connection id: " << p_conn_id << std::endl; + std::cout << "websocket server just got: /'" << p_buffer.to_string() << "/' and " + << p_buffer.used_bytes << " bytes from connection id: " << p_conn_id << std::endl; return boost::beast::websocket::close_code::normal; }, - [](const std::string &p_conn_id, - const boost::system::system_error &p_error) { - std::cout << "connection just got an error: " << p_conn_id - << " because of " << p_error.what() - << " error code: " << p_error.code() << std::endl; + [](const std::string &p_conn_id, const boost::system::system_error &p_error) { + std::cout << "connection just got an error: " << p_conn_id << " because of " + << p_error.what() << " error code: " << p_error.code() << std::endl; }); _io.run(); @@ -88,9 +84,8 @@ BOOST_AUTO_TEST_CASE(ws_client_timeout_test) { _timer.expires_after(std::chrono::nanoseconds(1)); // run a coroutine - const auto _ret = - co_await (_timer.async_wait(boost::asio::use_awaitable) || - _client.async_resolve(_endpoint)); + const auto _ret = co_await (_timer.async_wait(boost::asio::use_awaitable) || + _client.async_resolve(_endpoint)); // expect timeout BOOST_REQUIRE(_ret.index() == 0); diff --git a/wolf/system/w_gametime.cpp b/wolf/system/w_gametime.cpp index 673fd1e9f..6fe4acbf2 100644 --- a/wolf/system/w_gametime.cpp +++ b/wolf/system/w_gametime.cpp @@ -10,27 +10,17 @@ void w_gametime::reset() noexcept { this->_secs_counter = 0.0; } -double w_gametime::get_elapsed_secs() const noexcept { - return this->_elapsed_secs; -} +double w_gametime::get_elapsed_secs() const noexcept { return this->_elapsed_secs; } -double w_gametime::get_total_secs() const noexcept { - return this->_total_secs; -} +double w_gametime::get_total_secs() const noexcept { return this->_total_secs; } -uint32_t w_gametime::get_frames_count() const noexcept { - return this->_frames_count; -} +uint32_t w_gametime::get_frames_count() const noexcept { return this->_frames_count; } uint32_t w_gametime::get_fps() const noexcept { return this->_fps; } -bool w_gametime::get_is_fixed_time_step() const noexcept { - return this->_fixed_time_step; -} +bool w_gametime::get_is_fixed_time_step() const noexcept { return this->_fixed_time_step; } -void w_gametime::set_fixed_time_step(bool p_value) noexcept { - this->_fixed_time_step = p_value; -} +void w_gametime::set_fixed_time_step(bool p_value) noexcept { this->_fixed_time_step = p_value; } void w_gametime::set_target_elapsed_secs(double p_value) noexcept { this->_target_elapsed_secs = p_value; diff --git a/wolf/system/w_gametime.hpp b/wolf/system/w_gametime.hpp index df40d96a5..210e7465c 100644 --- a/wolf/system/w_gametime.hpp +++ b/wolf/system/w_gametime.hpp @@ -10,11 +10,11 @@ #include namespace wolf::system { -constexpr auto MAX_DELTA_TIME_IN_SECS = 60000.0; // 60 minutes +constexpr auto MAX_DELTA_TIME_IN_SECS = 60000.0; // 60 minutes constexpr auto TARGET_ELAPSED_SECS = 1.0 / 60.0; class w_gametime { -public: + public: // default constructor W_API w_gametime() noexcept = default; @@ -43,14 +43,13 @@ class w_gametime { W_API void set_target_elapsed_secs(double p_value) noexcept; - template W_API void tick(F &&p_tick_function) { + template + W_API void tick(F &&p_tick_function) { using namespace std::chrono; // Query the current time. const auto current_time = steady_clock::now(); - auto delta = - duration(current_time - this->_last_time).count() / - 1000.000; + auto delta = duration(current_time - this->_last_time).count() / 1000.000; this->_last_time = current_time; this->_secs_counter += delta; @@ -73,8 +72,7 @@ class w_gametime { zero to leave things running smoothly. */ constexpr auto quarter_of_one_milli_in_sec = 0.0004; - if (std::abs(delta - this->_target_elapsed_secs) < - quarter_of_one_milli_in_sec) { + if (std::abs(delta - this->_target_elapsed_secs) < quarter_of_one_milli_in_sec) { delta = this->_target_elapsed_secs; } @@ -85,7 +83,6 @@ class w_gametime { #pragma unroll #endif while (this->_left_over_ticks >= this->_target_elapsed_secs) { - this->_total_secs += this->_target_elapsed_secs; this->_left_over_ticks -= this->_target_elapsed_secs; @@ -116,7 +113,7 @@ class w_gametime { tick([] {}); } -private: + private: // copy constructor. w_gametime(const w_gametime &) = delete; // copy assignment operator. @@ -134,7 +131,6 @@ class w_gametime { uint32_t _frames_count = 0; uint32_t _frames_this_sec = 0; - std::chrono::steady_clock::time_point _last_time = { - std::chrono::steady_clock::now()}; + std::chrono::steady_clock::time_point _last_time = {std::chrono::steady_clock::now()}; }; -} // namespace wolf::system \ No newline at end of file +} // namespace wolf::system \ No newline at end of file diff --git a/wolf/system/w_leak_detector.cpp b/wolf/system/w_leak_detector.cpp index ec1056035..57da8b7db 100644 --- a/wolf/system/w_leak_detector.cpp +++ b/wolf/system/w_leak_detector.cpp @@ -22,8 +22,7 @@ w_leak_detector::~w_leak_detector() noexcept { _CrtMemState _new_mem_state; _CrtMemCheckpoint(&_new_mem_state); - const auto _dif = - _CrtMemDifference(&_diff_mem, &this->_mem_state, &_new_mem_state); + const auto _dif = _CrtMemDifference(&_diff_mem, &this->_mem_state, &_new_mem_state); if (_dif > 0) { _CrtMemDumpStatistics(&_diff_mem); _CrtMemDumpAllObjectsSince(&this->_mem_state); @@ -32,7 +31,7 @@ w_leak_detector::~w_leak_detector() noexcept { assert(false); std::terminate(); } - } catch (...) // const std::exception& p_ex) + } catch (...) // const std::exception& p_ex) { // write to the log file // "~w_leak_detector thrown an exception:" << p_ex.what(); diff --git a/wolf/system/w_leak_detector.hpp b/wolf/system/w_leak_detector.hpp index 4a203e42d..c4e7fb981 100644 --- a/wolf/system/w_leak_detector.hpp +++ b/wolf/system/w_leak_detector.hpp @@ -13,13 +13,13 @@ namespace wolf::system { class w_leak_detector { -public: + public: // default constructor W_API w_leak_detector() noexcept; // destructor W_API virtual ~w_leak_detector() noexcept; -private: + private: // move constructor w_leak_detector(w_leak_detector &&p_src) noexcept = delete; // move assignment operator. @@ -33,4 +33,4 @@ class w_leak_detector { _CrtMemState _mem_state; #endif }; -} // namespace wolf::system \ No newline at end of file +} // namespace wolf::system \ No newline at end of file diff --git a/wolf/system/w_process.cpp b/wolf/system/w_process.cpp index 8e455ce67..1df7ab056 100644 --- a/wolf/system/w_process.cpp +++ b/wolf/system/w_process.cpp @@ -19,8 +19,7 @@ boost::leaf::result w_process::current_exe_path() { const auto _ret = GetLastError(); if (_ret != S_OK) { - return W_FAILURE(_ret, "GetModuleFileNameW failed because:" + - get_last_win_error(_ret)); + return W_FAILURE(_ret, "GetModuleFileNameW failed because:" + get_last_win_error(_ret)); } auto _path = path(_buffer.data(), path::auto_format).parent_path(); diff --git a/wolf/system/w_process.hpp b/wolf/system/w_process.hpp index ea7e0b195..95899ae67 100644 --- a/wolf/system/w_process.hpp +++ b/wolf/system/w_process.hpp @@ -8,7 +8,7 @@ namespace wolf::system { class w_process { -public: + public: // default constructor W_API w_process() noexcept = default; // destructor @@ -30,10 +30,10 @@ class w_process { */ W_API static boost::leaf::result current_exe_path(); -private: + private: // copy constructor. w_process(const w_process &) = delete; // copy assignment operator. w_process &operator=(const w_process &) = delete; }; -} // namespace wolf::system +} // namespace wolf::system diff --git a/wolf/system/w_ring_buffer_spsc.hpp b/wolf/system/w_ring_buffer_spsc.hpp index af387e87a..1af74073c 100644 --- a/wolf/system/w_ring_buffer_spsc.hpp +++ b/wolf/system/w_ring_buffer_spsc.hpp @@ -20,7 +20,7 @@ namespace wolf::system { template requires std::is_integral_v class w_ring_buffer_spsc { -public: + public: using value_type = std::remove_cvref_t; w_ring_buffer_spsc() noexcept = default; @@ -38,8 +38,7 @@ class w_ring_buffer_spsc { _size = size; _buffer = std::make_unique(size); if (!_buffer) { - return W_FAILURE(std::errc::not_enough_memory, - "could not allocate ring buffer memory"); + return W_FAILURE(std::errc::not_enough_memory, "could not allocate ring buffer memory"); } return 0; @@ -95,7 +94,7 @@ class w_ring_buffer_spsc { head = more; } - _head_offset = head; // update real head offset... + _head_offset = head; // update real head offset... return amount; } @@ -130,26 +129,24 @@ class w_ring_buffer_spsc { tail = more; } - _tail_offset = tail; // update real tail offset... + _tail_offset = tail; // update real tail offset... return amount; } -private: + private: // copy conclassor. w_ring_buffer_spsc(const w_ring_buffer_spsc &) = delete; // copy assignment operator. w_ring_buffer_spsc &operator=(const w_ring_buffer_spsc &) = delete; - std::size_t _size = 0; //< total/maximum size that buffer can hold. + std::size_t _size = 0; //< total/maximum size that buffer can hold. std::unique_ptr _buffer{nullptr}; - alignas(std::hardware_destructive_interference_size) - std::atomic _head_offset = - 0; //< starting point of valid data in circular buffer. + alignas(std::hardware_destructive_interference_size) std::atomic _head_offset = + 0; //< starting point of valid data in circular buffer. - alignas(std::hardware_destructive_interference_size) std::atomic< - std::size_t> _tail_offset = - 0; //< end point of valid data in circular buffer. (tail-1 = last byte) + alignas(std::hardware_destructive_interference_size) std::atomic _tail_offset = + 0; //< end point of valid data in circular buffer. (tail-1 = last byte) }; -} // namespace wolf::system +} // namespace wolf::system diff --git a/wolf/system/w_trace.hpp b/wolf/system/w_trace.hpp index 5271b67b8..af4a125dc 100644 --- a/wolf/system/w_trace.hpp +++ b/wolf/system/w_trace.hpp @@ -7,19 +7,19 @@ #include #include +#include #include #include #include class w_trace { -public: + public: struct stack { - friend std::ostream &operator<<(std::ostream &p_os, - stack const &p_trace) noexcept { + friend std::ostream &operator<<(std::ostream &p_os, stack const &p_trace) noexcept { try { p_os << "|tid:" << p_trace.thread_id << "|code:" << p_trace.err_code - << "|msg:" << p_trace.err_msg << "|src:" << p_trace.source_file - << "(" << p_trace.source_file_line << ")" << std::endl; + << "|msg:" << p_trace.err_msg << "|src:" << p_trace.source_file << "(" + << p_trace.source_file_line << ")" << std::endl; } catch (...) { } return p_os; @@ -40,41 +40,35 @@ class w_trace { } } - w_trace(_In_ int64_t p_err_code, _In_ std::string p_err_msg, - _In_ const char *p_source_file, + w_trace(_In_ int64_t p_err_code, _In_ std::string p_err_msg, _In_ const char *p_source_file, _In_ uint32_t p_source_file_line) noexcept { try { this->_stacks.emplace_front(stack{std::this_thread::get_id(), p_err_code, - std::move(p_err_msg), p_source_file, - p_source_file_line}); + std::move(p_err_msg), p_source_file, p_source_file_line}); } catch (...) { } } - w_trace(_In_ std::errc p_err_code, _In_ std::string p_err_msg, - _In_ const char *p_source_file, + w_trace(_In_ std::errc p_err_code, _In_ std::string p_err_msg, _In_ const char *p_source_file, _In_ uint32_t p_source_file_line) noexcept { try { - this->_stacks.emplace_front(stack{ - std::this_thread::get_id(), gsl::narrow_cast(p_err_code), - std::move(p_err_msg), p_source_file, p_source_file_line}); + this->_stacks.emplace_front(stack{std::this_thread::get_id(), + gsl::narrow_cast(p_err_code), std::move(p_err_msg), + p_source_file, p_source_file_line}); } catch (...) { } } - void push(_In_ int64_t p_err_code, _In_ std::string p_err_msg, - _In_ const char *p_source_file, + void push(_In_ int64_t p_err_code, _In_ std::string p_err_msg, _In_ const char *p_source_file, _In_ uint32_t p_source_file_line) noexcept { try { this->_stacks.emplace_front(stack{std::this_thread::get_id(), p_err_code, - std::move(p_err_msg), p_source_file, - p_source_file_line}); + std::move(p_err_msg), p_source_file, p_source_file_line}); } catch (...) { } } - friend std::ostream &operator<<(std::ostream &p_os, - w_trace const &p_trace) noexcept { + friend std::ostream &operator<<(std::ostream &p_os, w_trace const &p_trace) noexcept { try { for (const auto &index : p_trace._stacks) { p_os << index; @@ -84,7 +78,7 @@ class w_trace { return p_os; } -private: + private: std::deque _stacks = {}; }; @@ -93,7 +87,7 @@ template requires std::movable #endif constexpr inline boost::leaf::result W_SUCCESS(T &p_param) noexcept { - return boost::leaf::result(std::move(p_param)); + return boost::leaf::result(std::move(p_param)); } #define W_FAILURE(p_code, p_msg) boost::leaf::new_error(w_trace(p_code, p_msg, __FILE__, __LINE__)) @@ -101,29 +95,27 @@ constexpr inline boost::leaf::result W_SUCCESS(T &p_param) noexcept { #ifdef WIN32 inline std::string get_last_win_error(_In_ DWORD p_error_id) { - if (p_error_id == 0) { + if (p_error_id == 0) { return {}; - } + } - LPSTR _msg_buffer = nullptr; + LPSTR _msg_buffer = nullptr; - // Ask Win32 to give us the string version of that message ID. - // The parameters we pass in, tell Win32 to create the buffer that holds the - // message for us (because we don't yet know how long the message string - // will be). - const auto _size = FormatMessageA( - FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS, - nullptr, p_error_id, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), - (LPSTR)&_msg_buffer, 0, NULL); + // Ask Win32 to give us the string version of that message ID. + // The parameters we pass in, tell Win32 to create the buffer that holds the + // message for us (because we don't yet know how long the message string + // will be). + const auto _size = FormatMessageA( + FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, + nullptr, p_error_id, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&_msg_buffer, 0, NULL); - // Copy the error message into a std::string. - std::string _message(_msg_buffer, _size); + // Copy the error message into a std::string. + std::string _message(_msg_buffer, _size); - // Free the Win32's string's buffer. - LocalFree(_msg_buffer); + // Free the Win32's string's buffer. + LocalFree(_msg_buffer); - return _message; + return _message; } #endif diff --git a/wolf/tests.cpp b/wolf/tests.cpp index ba8c24cb9..69dd68ce6 100644 --- a/wolf/tests.cpp +++ b/wolf/tests.cpp @@ -8,7 +8,7 @@ #include #define BOOST_TEST_MODULE wolf -#include +#include // NOLINT #include BOOST_AUTO_TEST_CASE(wolf_test) { @@ -29,19 +29,19 @@ BOOST_AUTO_TEST_CASE(wolf_test) { #include #include #include +//#include #include #include #include #include #include -#include #pragma endregion #pragma region stream tests //#include -#include +//#include #pragma endregion diff --git a/wolf/wolf.cpp b/wolf/wolf.cpp index a3d5ee063..c025baa8a 100644 --- a/wolf/wolf.cpp +++ b/wolf/wolf.cpp @@ -30,10 +30,9 @@ static void w_signal_handler(int p_signum) { #ifdef __clang__ #pragma unroll -#endif // __clang__ +#endif // __clang__ for (const auto &trace : boost::stacktrace::stacktrace()) { - _traces << "name: " << trace.name() - << " source_file: " << trace.source_file() << "(" + _traces << "name: " << trace.name() << " source_file: " << trace.source_file() << "(" << std::to_string(trace.source_line()) << ")\r\n"; } @@ -64,8 +63,7 @@ std::string wolf::w_init() { // for debugging constexpr auto WOLF_DEBUG_VERSION = 0; - auto _version = - wolf::format("v{}.{}.{}.{}", WOLF_MAJOR_VERSION, WOLF_MINOR_VERSION, - WOLF_PATCH_VERSION, WOLF_DEBUG_VERSION); + auto _version = wolf::format("v{}.{}.{}.{}", WOLF_MAJOR_VERSION, WOLF_MINOR_VERSION, + WOLF_PATCH_VERSION, WOLF_DEBUG_VERSION); return _version; } diff --git a/wolf/wolf.hpp b/wolf/wolf.hpp index f9e9fbf2f..a4cdc8681 100644 --- a/wolf/wolf.hpp +++ b/wolf/wolf.hpp @@ -61,13 +61,11 @@ constexpr auto W_MAX_BUFFER_SIZE = 1024; #define DEFER auto _ = std::shared_ptr(nullptr, [&](...) struct w_buffer { - w_buffer() noexcept = default; - explicit w_buffer(const std::string_view &p_str) { from_string(p_str); } + explicit w_buffer(const std::string_view p_str) { from_string(p_str); } - w_buffer(std::array &&p_array, - const size_t &p_used_bytes) noexcept { + w_buffer(std::array &&p_array, const size_t p_used_bytes) noexcept { this->buf = std::move(p_array); this->used_bytes = p_used_bytes; } @@ -78,9 +76,7 @@ struct w_buffer { std::copy(p_str.cbegin(), p_str.cbegin() + this->used_bytes, buf.begin()); } - std::string to_string() { - return std::string(this->buf.data(), this->used_bytes); - } + std::string to_string() { return std::string(this->buf.data(), this->used_bytes); } std::array buf = {0}; size_t used_bytes = 0; @@ -138,15 +134,13 @@ W_API std::string w_init(); */ #ifdef _MSC_VER template -W_API std::string format(_In_ const std::string_view p_fmt, - _In_ Args &&...p_args) { +W_API std::string format(_In_ const std::string_view p_fmt, _In_ Args &&...p_args) { return std::vformat(p_fmt, std::make_format_args(p_args...)); } #else template -W_API std::string format(_In_ const fmt::v9::format_string p_fmt, - _In_ Args &&...p_args) { +W_API std::string format(_In_ const fmt::v9::format_string p_fmt, _In_ Args &&...p_args) { return fmt::v9::vformat(p_fmt, fmt::v9::make_format_args(p_args...)); } -#endif // _MSC_VER -} // namespace wolf +#endif // _MSC_VER +} // namespace wolf