diff --git a/.github/workflows/ci-freebsd.yml b/.github/workflows/ci-freebsd.yml index b3a25b3a2..d2c72e5f8 100644 --- a/.github/workflows/ci-freebsd.yml +++ b/.github/workflows/ci-freebsd.yml @@ -210,6 +210,7 @@ jobs: - name: Test id: test + timeout-minutes: 5 shell: freebsd {0} run: | set -e @@ -218,11 +219,10 @@ jobs: export DISPLAY=:1 Xvfb ${DISPLAY} -screen 0 1024x768x24 & XVFB_PID=$! + trap 'kill "${XVFB_PID}" 2>/dev/null || true; wait "${XVFB_PID}" 2>/dev/null || true' EXIT ./test_sunshine --gtest_color=yes --gtest_output=xml:test_results.xml - kill ${XVFB_PID} - - name: Generate gcov report id: test_report # any except canceled or skipped diff --git a/src/audio.cpp b/src/audio.cpp index 28a3d810d..62d4cabbc 100644 --- a/src/audio.cpp +++ b/src/audio.cpp @@ -3,6 +3,7 @@ * @brief Definitions for audio capture and encoding. */ // standard includes +#include #include // lib includes @@ -48,7 +49,7 @@ namespace audio { /** * @brief Opus stream layouts and bitrates advertised to clients. */ - opus_stream_config_t stream_configs[MAX_STREAM_CONFIG] { + const std::array stream_configs {{ { SAMPLE_RATE, 2, @@ -97,7 +98,7 @@ namespace audio { platf::speaker::map_surround71.data(), 2048000, }, - }; + }}; /** * @brief Encode captured PCM samples into Opus packets on the audio worker thread. @@ -352,6 +353,6 @@ namespace audio { stream.channelCount = params.channelCount; stream.streams = params.streams; stream.coupledStreams = params.coupledStreams; - stream.mapping = params.mapping; + stream.mapping = params.mapping.data(); } } // namespace audio diff --git a/src/audio.h b/src/audio.h index e0e919a54..f21417283 100644 --- a/src/audio.h +++ b/src/audio.h @@ -9,6 +9,7 @@ #include "thread_safe.h" #include "utility.h" +#include #include namespace audio { @@ -44,10 +45,13 @@ namespace audio { int channelCount; ///< Number of audio channels in the Opus layout. int streams; ///< Number of Opus streams in the custom layout. int coupledStreams; ///< Number of stereo-coupled Opus streams. - std::uint8_t mapping[8]; ///< Channel mapping table for up to eight speakers. + std::array mapping; ///< Channel mapping table for up to eight speakers. }; - extern opus_stream_config_t stream_configs[MAX_STREAM_CONFIG]; + /** + * @brief Opus layouts and bitrates advertised for each supported stream mode. + */ + extern const std::array stream_configs; /** * @brief Audio capture and encoder settings for a stream. diff --git a/src/cbs.cpp b/src/cbs.cpp index 03f5f04e2..d933d870a 100644 --- a/src/cbs.cpp +++ b/src/cbs.cpp @@ -2,6 +2,7 @@ * @file src/cbs.cpp * @brief Definitions for FFmpeg Coded Bitstream API. */ +#include extern "C" { // lib includes #include @@ -89,16 +90,16 @@ namespace cbs { cbs::frag_t frag; auto err = ff_cbs_insert_unit_content(&frag, -1, nal, uh, nullptr); if (err < 0) { - char err_str[AV_ERROR_MAX_STRING_SIZE] {0}; - BOOST_LOG(error) << "Could not insert NAL unit SPS: "sv << av_make_error_string(err_str, AV_ERROR_MAX_STRING_SIZE, err); + std::array err_str {0}; + BOOST_LOG(error) << "Could not insert NAL unit SPS: "sv << av_make_error_string(err_str.data(), AV_ERROR_MAX_STRING_SIZE, err); return {}; } err = ff_cbs_write_fragment_data(cbs_ctx.get(), &frag); if (err < 0) { - char err_str[AV_ERROR_MAX_STRING_SIZE] {0}; - BOOST_LOG(error) << "Could not write fragment data: "sv << av_make_error_string(err_str, AV_ERROR_MAX_STRING_SIZE, err); + std::array err_str {0}; + BOOST_LOG(error) << "Could not write fragment data: "sv << av_make_error_string(err_str.data(), AV_ERROR_MAX_STRING_SIZE, err); return {}; } @@ -138,8 +139,8 @@ namespace cbs { int err = ff_cbs_read_packet(ctx.get(), &frag, packet); if (err < 0) { - char err_str[AV_ERROR_MAX_STRING_SIZE] {0}; - BOOST_LOG(error) << "Couldn't read packet: "sv << av_make_error_string(err_str, AV_ERROR_MAX_STRING_SIZE, err); + std::array err_str {0}; + BOOST_LOG(error) << "Couldn't read packet: "sv << av_make_error_string(err_str.data(), AV_ERROR_MAX_STRING_SIZE, err); return {}; } @@ -197,8 +198,8 @@ namespace cbs { int err = ff_cbs_read_packet(ctx.get(), &frag, packet); if (err < 0) { - char err_str[AV_ERROR_MAX_STRING_SIZE] {0}; - BOOST_LOG(error) << "Couldn't read packet: "sv << av_make_error_string(err_str, AV_ERROR_MAX_STRING_SIZE, err); + std::array err_str {0}; + BOOST_LOG(error) << "Couldn't read packet: "sv << av_make_error_string(err_str.data(), AV_ERROR_MAX_STRING_SIZE, err); return {}; } @@ -276,8 +277,8 @@ namespace cbs { int err = ff_cbs_read_packet(ctx.get(), &frag, packet); if (err < 0) { - char err_str[AV_ERROR_MAX_STRING_SIZE] {0}; - BOOST_LOG(error) << "Couldn't read packet: "sv << av_make_error_string(err_str, AV_ERROR_MAX_STRING_SIZE, err); + std::array err_str {0}; + BOOST_LOG(error) << "Couldn't read packet: "sv << av_make_error_string(err_str.data(), AV_ERROR_MAX_STRING_SIZE, err); return false; } diff --git a/src/config.cpp b/src/config.cpp index d63a28740..6c3362386 100644 --- a/src/config.cpp +++ b/src/config.cpp @@ -4,6 +4,7 @@ */ // standard includes #include +#include #include #include #include @@ -2086,14 +2087,14 @@ namespace config { if (shortcut_launch) { if (!service_ctrl::is_service_running()) { // If the service isn't running, relaunch ourselves as admin to start it - WCHAR executable[MAX_PATH]; - GetModuleFileNameW(nullptr, executable, ARRAYSIZE(executable)); + std::array executable; + GetModuleFileNameW(nullptr, executable.data(), executable.size()); SHELLEXECUTEINFOW shell_exec_info {}; shell_exec_info.cbSize = sizeof(shell_exec_info); shell_exec_info.fMask = SEE_MASK_NOASYNC | SEE_MASK_NO_CONSOLE | SEE_MASK_NOCLOSEPROCESS; shell_exec_info.lpVerb = L"runas"; - shell_exec_info.lpFile = executable; + shell_exec_info.lpFile = executable.data(); shell_exec_info.lpParameters = L"--shortcut-admin"; shell_exec_info.nShow = SW_NORMAL; if (!ShellExecuteExW(&shell_exec_info)) { diff --git a/src/logging.cpp b/src/logging.cpp index 814c168eb..39a3f0071 100644 --- a/src/logging.cpp +++ b/src/logging.cpp @@ -3,6 +3,7 @@ * @brief Definitions for logging related functions. */ // standard includes +#include #include #include #include @@ -204,22 +205,22 @@ namespace logging { } av_log_set_callback([](void *ptr, int level, const char *fmt, va_list vl) { static int print_prefix = 1; - char buffer[1024]; + std::array buffer; - av_log_format_line(ptr, level, fmt, vl, buffer, sizeof(buffer), &print_prefix); + av_log_format_line(ptr, level, fmt, vl, buffer.data(), buffer.size(), &print_prefix); if (level <= AV_LOG_ERROR) { // We print AV_LOG_FATAL at the error level. FFmpeg prints things as fatal that // are expected in some cases, such as lack of codec support or similar things. - BOOST_LOG(error) << buffer; + BOOST_LOG(error) << buffer.data(); } else if (level <= AV_LOG_WARNING) { - BOOST_LOG(warning) << buffer; + BOOST_LOG(warning) << buffer.data(); } else if (level <= AV_LOG_INFO) { - BOOST_LOG(info) << buffer; + BOOST_LOG(info) << buffer.data(); } else if (level <= AV_LOG_VERBOSE) { // AV_LOG_VERBOSE is less verbose than AV_LOG_DEBUG - BOOST_LOG(debug) << buffer; + BOOST_LOG(debug) << buffer.data(); } else { - BOOST_LOG(verbose) << buffer; + BOOST_LOG(verbose) << buffer.data(); } }); } diff --git a/src/nvhttp.cpp b/src/nvhttp.cpp index 98f59f902..196a30868 100644 --- a/src/nvhttp.cpp +++ b/src/nvhttp.cpp @@ -7,6 +7,7 @@ // standard includes #include +#include #include #include #include @@ -521,8 +522,8 @@ namespace nvhttp { launch_session->client_name = last_verified_client_name; // Generate the unique identifiers for this connection that we will send later during RTSP handshake - unsigned char raw_payload[8]; - RAND_bytes(raw_payload, sizeof(raw_payload)); + std::array raw_payload; + RAND_bytes(raw_payload.data(), raw_payload.size()); launch_session->av_ping_payload = util::hex_vec(raw_payload); RAND_bytes((unsigned char *) &launch_session->control_connect_data, sizeof(launch_session->control_connect_data)); @@ -1651,11 +1652,11 @@ namespace nvhttp { int verified = 0; auto fg = util::fail_guard([&]() { - char subject_name[256]; + std::array subject_name; - X509_NAME_oneline(X509_get_subject_name(x509.get()), subject_name, sizeof(subject_name)); + X509_NAME_oneline(X509_get_subject_name(x509.get()), subject_name.data(), subject_name.size()); - BOOST_LOG(debug) << subject_name << " -- "sv << (verified ? "verified"sv : "denied"sv); + BOOST_LOG(debug) << subject_name.data() << " -- "sv << (verified ? "verified"sv : "denied"sv); }); std::lock_guard lock {client_auth_mutex()}; diff --git a/src/platform/common.h b/src/platform/common.h index 52925cba8..adb97f352 100644 --- a/src/platform/common.h +++ b/src/platform/common.h @@ -898,14 +898,14 @@ namespace platf { * @brief Convert a socket address to a printable IP address. * * @param ip_addr Socket address to format. - * @return Value converted from sockaddr. + * @return Printable address, or an empty string for an unsupported address family. */ std::string from_sockaddr(const sockaddr *const); /** * @brief Convert a socket address to a port and printable IP address. * * @param ip_addr Socket address to format. - * @return Value converted from sockaddr ex. + * @return Port in network byte order and printable address, or zero and an empty string for an unsupported family. */ std::pair from_sockaddr_ex(const sockaddr *const); diff --git a/src/platform/linux/cuda.cpp b/src/platform/linux/cuda.cpp index 0cacea470..a87e98798 100644 --- a/src/platform/linux/cuda.cpp +++ b/src/platform/linux/cuda.cpp @@ -3,6 +3,7 @@ * @brief Definitions for CUDA encoding. */ // standard includes +#include #include #include #include @@ -422,8 +423,8 @@ namespace cuda { // TODO: Support more than one CUDA device file = std::move(open_drm_fd_for_cuda_device(0)); if (file.el < 0) { - char string[1024]; - BOOST_LOG(error) << "Couldn't open DRM FD for CUDA device: "sv << strerror_r(errno, string, sizeof(string)); + std::array string; + BOOST_LOG(error) << "Couldn't open DRM FD for CUDA device: "sv << strerror_r(errno, string.data(), string.size()); return -1; } @@ -822,8 +823,8 @@ namespace cuda { // Set privateData to allow NvFBC on consumer NVIDIA GPUs. // Based on https://github.com/keylase/nvidia-patch/blob/3193b4b1cea91527bf09ea9b8db5aade6a3f3c0a/win/nvfbcwrp/nvfbcwrp_main.cpp#L23-L25 . - const unsigned int MAGIC_PRIVATE_DATA[4] = {0xAEF57AC5, 0x401D1A39, 0x1B856BBE, 0x9ED0CEBA}; - params.privateData = MAGIC_PRIVATE_DATA; + const std::array MAGIC_PRIVATE_DATA = {0xAEF57AC5, 0x401D1A39, 0x1B856BBE, 0x9ED0CEBA}; + params.privateData = MAGIC_PRIVATE_DATA.data(); params.privateDataSize = sizeof(MAGIC_PRIVATE_DATA); handle_t handle; diff --git a/src/platform/linux/graphics.cpp b/src/platform/linux/graphics.cpp index 1ada5a0c9..74a4c8b24 100644 --- a/src/platform/linux/graphics.cpp +++ b/src/platform/linux/graphics.cpp @@ -3,6 +3,7 @@ * @brief Definitions for graphics related functions. */ // standard includes +#include #include #include #include @@ -85,7 +86,7 @@ namespace gl { ctx.GenTextures(textures.size(), textures.begin()); - float color[] = {0.0f, 0.0f, 0.0f, 1.0f}; + std::array color = {0.0f, 0.0f, 0.0f, 1.0f}; for (auto tex : textures) { gl::ctx.BindTexture(GL_TEXTURE_2D, tex); @@ -93,7 +94,7 @@ namespace gl { gl::ctx.TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); // y gl::ctx.TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); gl::ctx.TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - gl::ctx.TexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, color); + gl::ctx.TexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, color.data()); } return textures; @@ -548,7 +549,7 @@ namespace egl { BOOST_LOG(debug) << "EGL: ["sv << vendor << "]: version ["sv << version << ']'; BOOST_LOG(debug) << "API's supported: ["sv << apis << ']'; - const char *extensions[] { + std::array extensions { "EGL_KHR_create_context", "EGL_KHR_surfaceless_context", "EGL_EXT_image_dma_buf_import", @@ -571,7 +572,7 @@ namespace egl { std::optional make_ctx(display_t::pointer display) { bool nice_warning = false; - constexpr int conf_attr[] { + constexpr std::array conf_attr { EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT, EGL_NONE @@ -579,7 +580,7 @@ namespace egl { int count; EGLConfig conf; - if (!eglChooseConfig(display, conf_attr, &conf, 1, &count)) { + if (!eglChooseConfig(display, conf_attr.data(), &conf, 1, &count)) { BOOST_LOG(error) << "Couldn't set config attributes: ["sv << util::hex(eglGetError()).to_string_view() << ']'; return std::nullopt; } @@ -817,8 +818,8 @@ namespace egl { GLenum attachment = GL_COLOR_ATTACHMENT0; gl::ctx.DrawBuffers(1, &attachment); - const GLuint rgb_black[] = {0, 0, 0, 0}; - gl::ctx.ClearBufferuiv(GL_COLOR, 0, rgb_black); + const std::array rgb_black = {0, 0, 0, 0}; + gl::ctx.ClearBufferuiv(GL_COLOR, 0, rgb_black.data()); gl_drain_errors; @@ -826,8 +827,8 @@ namespace egl { } // Constants for clear black color Y, U, V. U & V are same so: - const float y_black[] = {0.0f, 0.0f, 0.0f, 0.0f}; ///< Y black. - const float uv_black[] = {0.5f, 0.5f, 0.5f, 0.5f}; ///< Uv black. + const std::array y_black = {0.0f, 0.0f, 0.0f, 0.0f}; ///< Y black. + const std::array uv_black = {0.5f, 0.5f, 0.5f, 0.5f}; ///< Uv black. /** * @brief Bind NV12 target framebuffers to their Y and UV plane textures. @@ -840,7 +841,7 @@ namespace egl { for (size_t x = 0; x < attachments.size(); ++x) { gl::ctx.BindFramebuffer(GL_FRAMEBUFFER, nv12->buf[x]); gl::ctx.DrawBuffers(1, &attachments[x]); - gl::ctx.ClearBufferfv(GL_COLOR, 0, x == 0 ? y_black : uv_black); + gl::ctx.ClearBufferfv(GL_COLOR, 0, x == 0 ? y_black.data() : uv_black.data()); } gl::ctx.BindFramebuffer(GL_FRAMEBUFFER, 0); @@ -859,7 +860,7 @@ namespace egl { for (size_t x = 0; x < attachments.size(); ++x) { gl::ctx.BindFramebuffer(GL_FRAMEBUFFER, yuv444->buf[x]); gl::ctx.DrawBuffers(1, &attachments[x]); - gl::ctx.ClearBufferfv(GL_COLOR, 0, x == 0 ? y_black : uv_black); + gl::ctx.ClearBufferfv(GL_COLOR, 0, x == 0 ? y_black.data() : uv_black.data()); } gl::ctx.BindFramebuffer(GL_FRAMEBUFFER, 0); @@ -1069,7 +1070,7 @@ namespace egl { void sws_t::apply_colorspace(const video::sunshine_colorspace_t &colorspace, bool is_yuv444) { auto color_p = video::color_vectors_from_colorspace(colorspace, true); - std::string_view members[] { + std::array members { util::view(color_p->color_vec_y), util::view(color_p->color_vec_u), util::view(color_p->color_vec_v), @@ -1077,7 +1078,7 @@ namespace egl { util::view(color_p->range_uv), }; - color_matrix.update(members, sizeof(members) / sizeof(decltype(members[0]))); + color_matrix.update(members.data(), members.size()); int planesCount = is_yuv444 ? 3 : 2; @@ -1486,14 +1487,14 @@ namespace egl { int sws_t::convert_nv12(gl::frame_buf_t &fb) { gl::ctx.BindTexture(GL_TEXTURE_2D, loaded_texture); - GLenum attachments[] { + std::array attachments { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 }; - int attachmentsCount = sizeof(attachments) / sizeof(decltype(attachments[0])); + int attachmentsCount = attachments.size(); - int drawBuffers = draw_programs_to_buffers(attachments, fb, attachmentsCount, false); + int drawBuffers = draw_programs_to_buffers(attachments.data(), fb, attachmentsCount, false); if (drawBuffers < 0) { return -1; } @@ -1508,15 +1509,15 @@ namespace egl { int sws_t::convert_yuv444(gl::frame_buf_t &fb) { gl::ctx.BindTexture(GL_TEXTURE_2D, loaded_texture); - GLenum attachments[] { + std::array attachments { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2 }; - int attachmentsCount = sizeof(attachments) / sizeof(decltype(attachments[0])); + int attachmentsCount = attachments.size(); - int drawBuffers = draw_programs_to_buffers(attachments, fb, attachmentsCount, true); + int drawBuffers = draw_programs_to_buffers(attachments.data(), fb, attachmentsCount, true); if (drawBuffers < 0) { return -1; } diff --git a/src/platform/linux/graphics.h b/src/platform/linux/graphics.h index 60c0a1dfc..fbcdc728a 100644 --- a/src/platform/linux/graphics.h +++ b/src/platform/linux/graphics.h @@ -5,6 +5,7 @@ #pragma once // standard includes +#include #include #include @@ -496,11 +497,11 @@ namespace egl { struct surface_descriptor_t { int width; ///< Frame or display width in pixels. int height; ///< Frame or display height in pixels. - int fds[4]; ///< DMA-BUF file descriptors for up to four planes. + std::array fds; ///< DMA-BUF file descriptors for up to four planes. std::uint32_t fourcc; ///< DRM fourcc pixel format for the buffer. std::uint64_t modifier; ///< DRM format modifier describing the buffer layout. - std::uint32_t pitches[4]; ///< Row stride in bytes for each DMA-BUF plane. - std::uint32_t offsets[4]; ///< Byte offset to the first pixel for each DMA-BUF plane. + std::array pitches; ///< Row stride in bytes for each DMA-BUF plane. + std::array offsets; ///< Byte offset to the first pixel for each DMA-BUF plane. }; /** diff --git a/src/platform/linux/kmsgrab.cpp b/src/platform/linux/kmsgrab.cpp index 15eb07e63..988f5c964 100644 --- a/src/platform/linux/kmsgrab.cpp +++ b/src/platform/linux/kmsgrab.cpp @@ -3,6 +3,7 @@ * @brief Definitions for KMS screen capture. */ // standard includes +#include #include #include #include @@ -239,9 +240,9 @@ namespace platf { height {fb->height} { pixel_format = DRM_FORMAT_XRGB8888; modifier = DRM_FORMAT_MOD_INVALID; - std::fill_n(handles, 4, 0); - std::fill_n(pitches, 4, 0); - std::fill_n(offsets, 4, 0); + handles.fill(0); + pitches.fill(0); + offsets.fill(0); handles[0] = fb->handle; pitches[0] = fb->pitch; } @@ -261,9 +262,9 @@ namespace platf { pixel_format = fb2->pixel_format; modifier = (fb2->flags & DRM_MODE_FB_MODIFIERS) ? fb2->modifier : DRM_FORMAT_MOD_INVALID; - memcpy(handles, fb2->handles, sizeof(handles)); - memcpy(pitches, fb2->pitches, sizeof(pitches)); - memcpy(offsets, fb2->offsets, sizeof(offsets)); + std::copy_n(fb2->handles, handles.size(), handles.begin()); + std::copy_n(fb2->pitches, pitches.size(), pitches.begin()); + std::copy_n(fb2->offsets, offsets.size(), offsets.begin()); } ~wrapper_fb() { @@ -291,9 +292,9 @@ namespace platf { uint32_t height; ///< Framebuffer height in pixels. uint32_t pixel_format; ///< DRM fourcc pixel format for the framebuffer. uint64_t modifier; ///< DRM format modifier describing framebuffer memory layout. - uint32_t handles[4]; ///< GEM handles for each framebuffer plane. - uint32_t pitches[4]; ///< Row stride in bytes for each framebuffer plane. - uint32_t offsets[4]; ///< Byte offset to the first pixel for each framebuffer plane. + std::array handles; ///< GEM handles for each framebuffer plane. + std::array pitches; ///< Row stride in bytes for each framebuffer plane. + std::array offsets; ///< Byte offset to the first pixel for each framebuffer plane. }; /** @@ -1914,12 +1915,12 @@ namespace platf { * @return Capture status reported to the streaming pipeline. */ capture_e snapshot(const pull_free_image_cb_t &pull_free_image_cb, std::shared_ptr &img_out, std::chrono::milliseconds timeout, bool cursor) { - file_t fb_fd[4]; + std::array fb_fd; egl::surface_descriptor_t sd; std::optional frame_timestamp; - auto status = refresh(fb_fd, &sd, frame_timestamp); + auto status = refresh(fb_fd.data(), &sd, frame_timestamp); if (status != capture_e::ok) { return status; } @@ -2045,7 +2046,7 @@ namespace platf { img->pixel_pitch = 4; img->sequence = 0; - std::fill_n(img->sd.fds, 4, -1); + img->sd.fds.fill(-1); return img; } @@ -2104,7 +2105,7 @@ namespace platf { * @return Capture status reported to the streaming pipeline. */ capture_e snapshot(const pull_free_image_cb_t &pull_free_image_cb, std::shared_ptr &img_out, std::chrono::milliseconds /* timeout */, bool cursor) { - file_t fb_fd[4]; + std::array fb_fd; if (!pull_free_image_cb(img_out)) { return platf::capture_e::interrupted; @@ -2112,7 +2113,7 @@ namespace platf { auto img = (egl::img_descriptor_t *) img_out.get(); img->reset(); - auto status = refresh(fb_fd, &img->sd, img->frame_timestamp); + auto status = refresh(fb_fd.data(), &img->sd, img->frame_timestamp); if (status != capture_e::ok) { return status; } diff --git a/src/platform/linux/misc.cpp b/src/platform/linux/misc.cpp index 4d2430da4..babf0a488 100644 --- a/src/platform/linux/misc.cpp +++ b/src/platform/linux/misc.cpp @@ -386,35 +386,35 @@ namespace platf { * @brief Convert a socket address to a printable IP address. */ std::string from_sockaddr(const sockaddr *const ip_addr) { - char data[INET6_ADDRSTRLEN] = {}; + std::array data = {}; auto family = ip_addr->sa_family; if (family == AF_INET6) { - inet_ntop(AF_INET6, &((sockaddr_in6 *) ip_addr)->sin6_addr, data, INET6_ADDRSTRLEN); + inet_ntop(AF_INET6, &((sockaddr_in6 *) ip_addr)->sin6_addr, data.data(), INET6_ADDRSTRLEN); } else if (family == AF_INET) { - inet_ntop(AF_INET, &((sockaddr_in *) ip_addr)->sin_addr, data, INET_ADDRSTRLEN); + inet_ntop(AF_INET, &((sockaddr_in *) ip_addr)->sin_addr, data.data(), INET_ADDRSTRLEN); } - return std::string {data}; + return std::string {data.data()}; } /** * @brief Convert a socket address to a port and printable IP address. */ std::pair from_sockaddr_ex(const sockaddr *const ip_addr) { - char data[INET6_ADDRSTRLEN] = {}; + std::array data = {}; auto family = ip_addr->sa_family; std::uint16_t port = 0; if (family == AF_INET6) { - inet_ntop(AF_INET6, &((sockaddr_in6 *) ip_addr)->sin6_addr, data, INET6_ADDRSTRLEN); + inet_ntop(AF_INET6, &((sockaddr_in6 *) ip_addr)->sin6_addr, data.data(), INET6_ADDRSTRLEN); port = ((sockaddr_in6 *) ip_addr)->sin6_port; } else if (family == AF_INET) { - inet_ntop(AF_INET, &((sockaddr_in *) ip_addr)->sin_addr, data, INET_ADDRSTRLEN); + inet_ntop(AF_INET, &((sockaddr_in *) ip_addr)->sin_addr, data.data(), INET_ADDRSTRLEN); port = ((sockaddr_in *) ip_addr)->sin_port; } - return {port, std::string {data}}; + return {port, std::string {data.data()}}; } /** @@ -611,8 +611,8 @@ namespace platf { * @brief Request a Sunshine process restart on exit. */ void restart_on_exit() { - char executable[PATH_MAX]; - ssize_t len = readlink("/proc/self/exe", executable, PATH_MAX - 1); + std::array executable; + ssize_t len = readlink("/proc/self/exe", executable.data(), executable.size() - 1); if (len == -1) { BOOST_LOG(fatal) << "readlink() failed: "sv << errno; return; @@ -626,7 +626,7 @@ namespace platf { } // Re-exec ourselves with the same arguments - if (execv(executable, lifetime::get_argv()) < 0) { + if (execv(executable.data(), lifetime::get_argv()) < 0) { BOOST_LOG(fatal) << "execv() failed: "sv << errno; return; } @@ -694,6 +694,60 @@ namespace platf { return saddr_v6; } + /** + * @brief Write the source IP address into the first ancillary control message. + * + * @param msg Socket message with control storage sized for packet information. + * @param source_address Local IP address to use for outgoing packets. + * @return Bytes occupied by the packet-information control message. + */ + static socklen_t populate_source_pktinfo(msghdr &msg, const boost::asio::ip::address &source_address) { + socklen_t cmbuflen = 0; + auto pktinfo_cm = CMSG_FIRSTHDR(&msg); + if (source_address.is_v6()) { + struct in6_pktinfo pktInfo; + + struct sockaddr_in6 saddr_v6 = to_sockaddr(source_address.to_v6(), 0); + pktInfo.ipi6_addr = saddr_v6.sin6_addr; + pktInfo.ipi6_ifindex = 0; + + cmbuflen += CMSG_SPACE(sizeof(pktInfo)); + + pktinfo_cm->cmsg_level = IPPROTO_IPV6; + pktinfo_cm->cmsg_type = IPV6_PKTINFO; + pktinfo_cm->cmsg_len = CMSG_LEN(sizeof(pktInfo)); + memcpy(CMSG_DATA(pktinfo_cm), &pktInfo, sizeof(pktInfo)); + } else { +#ifdef IP_PKTINFO + struct in_pktinfo pktInfo; + + struct sockaddr_in saddr_v4 = to_sockaddr(source_address.to_v4(), 0); + pktInfo.ipi_spec_dst = saddr_v4.sin_addr; + pktInfo.ipi_ifindex = 0; + + cmbuflen += CMSG_SPACE(sizeof(pktInfo)); + + pktinfo_cm->cmsg_level = IPPROTO_IP; + pktinfo_cm->cmsg_type = IP_PKTINFO; + pktinfo_cm->cmsg_len = CMSG_LEN(sizeof(pktInfo)); + memcpy(CMSG_DATA(pktinfo_cm), &pktInfo, sizeof(pktInfo)); +#elif defined(IP_SENDSRCADDR) + // FreeBSD uses IP_SENDSRCADDR with struct in_addr instead of IP_PKTINFO + struct sockaddr_in saddr_v4 = to_sockaddr(source_address.to_v4(), 0); + struct in_addr src_addr = saddr_v4.sin_addr; + + cmbuflen += CMSG_SPACE(sizeof(src_addr)); + + pktinfo_cm->cmsg_level = IPPROTO_IP; + pktinfo_cm->cmsg_type = IP_SENDSRCADDR; + pktinfo_cm->cmsg_len = CMSG_LEN(sizeof(src_addr)); + memcpy(CMSG_DATA(pktinfo_cm), &src_addr, sizeof(src_addr)); +#endif + } + + return cmbuflen; + } + /** * @brief Send multiple fixed-size UDP payload blocks using the platform backend. */ @@ -718,62 +772,20 @@ namespace platf { union { #ifdef IP_PKTINFO - char buf[CMSG_SPACE(sizeof(uint16_t)) + std::max(CMSG_SPACE(sizeof(struct in_pktinfo)), CMSG_SPACE(sizeof(struct in6_pktinfo)))]; + std::array buf; #elif defined(IP_SENDSRCADDR) // FreeBSD uses IP_SENDSRCADDR with struct in_addr instead of IP_PKTINFO with struct in_pktinfo - char buf[CMSG_SPACE(sizeof(uint16_t)) + std::max(CMSG_SPACE(sizeof(struct in_addr)), CMSG_SPACE(sizeof(struct in6_pktinfo)))]; + std::array buf; #endif struct cmsghdr alignment; } cmbuf = {}; // Must be zeroed for CMSG_NXTHDR() - socklen_t cmbuflen = 0; - - msg.msg_control = cmbuf.buf; - msg.msg_controllen = sizeof(cmbuf.buf); + msg.msg_control = cmbuf.buf.data(); + msg.msg_controllen = cmbuf.buf.size(); // The PKTINFO option will always be first, then we will conditionally // append the UDP_SEGMENT option next if applicable. - auto pktinfo_cm = CMSG_FIRSTHDR(&msg); - if (send_info.source_address.is_v6()) { - struct in6_pktinfo pktInfo; - - struct sockaddr_in6 saddr_v6 = to_sockaddr(send_info.source_address.to_v6(), 0); - pktInfo.ipi6_addr = saddr_v6.sin6_addr; - pktInfo.ipi6_ifindex = 0; - - cmbuflen += CMSG_SPACE(sizeof(pktInfo)); - - pktinfo_cm->cmsg_level = IPPROTO_IPV6; - pktinfo_cm->cmsg_type = IPV6_PKTINFO; - pktinfo_cm->cmsg_len = CMSG_LEN(sizeof(pktInfo)); - memcpy(CMSG_DATA(pktinfo_cm), &pktInfo, sizeof(pktInfo)); - } else { -#ifdef IP_PKTINFO - struct in_pktinfo pktInfo; - - struct sockaddr_in saddr_v4 = to_sockaddr(send_info.source_address.to_v4(), 0); - pktInfo.ipi_spec_dst = saddr_v4.sin_addr; - pktInfo.ipi_ifindex = 0; - - cmbuflen += CMSG_SPACE(sizeof(pktInfo)); - - pktinfo_cm->cmsg_level = IPPROTO_IP; - pktinfo_cm->cmsg_type = IP_PKTINFO; - pktinfo_cm->cmsg_len = CMSG_LEN(sizeof(pktInfo)); - memcpy(CMSG_DATA(pktinfo_cm), &pktInfo, sizeof(pktInfo)); -#elif defined(IP_SENDSRCADDR) - // FreeBSD uses IP_SENDSRCADDR with struct in_addr instead of IP_PKTINFO - struct sockaddr_in saddr_v4 = to_sockaddr(send_info.source_address.to_v4(), 0); - struct in_addr src_addr = saddr_v4.sin_addr; - - cmbuflen += CMSG_SPACE(sizeof(src_addr)); - - pktinfo_cm->cmsg_level = IPPROTO_IP; - pktinfo_cm->cmsg_type = IP_SENDSRCADDR; - pktinfo_cm->cmsg_len = CMSG_LEN(sizeof(src_addr)); - memcpy(CMSG_DATA(pktinfo_cm), &src_addr, sizeof(src_addr)); -#endif - } + auto cmbuflen = populate_source_pktinfo(msg, send_info.source_address); auto const max_iovs_per_msg = send_info.payload_buffers.size() + (send_info.headers ? 1 : 0); @@ -782,7 +794,7 @@ namespace platf { // UDP GSO on Linux currently only supports sending 64K or 64 segments at a time size_t seg_index = 0; const size_t seg_max = 65536 / 1500; - struct iovec iovs[(send_info.headers ? std::min(seg_max, send_info.block_count) : 1) * max_iovs_per_msg]; + std::vector iovs((send_info.headers ? std::min(seg_max, send_info.block_count) : 1) * max_iovs_per_msg); auto msg_size = send_info.header_size + send_info.payload_size; while (seg_index < send_info.block_count) { int iovlen = 0; @@ -811,7 +823,7 @@ namespace platf { } } - msg.msg_iov = iovs; + msg.msg_iov = iovs.data(); msg.msg_iovlen = iovlen; // We should not use GSO if the data is <= one full block size @@ -819,7 +831,7 @@ namespace platf { msg.msg_controllen = cmbuflen + CMSG_SPACE(sizeof(uint16_t)); // Enable GSO to perform segmentation of our buffer for us - auto cm = CMSG_NXTHDR(&msg, pktinfo_cm); + auto cm = CMSG_NXTHDR(&msg, CMSG_FIRSTHDR(&msg)); cm->cmsg_level = SOL_UDP; cm->cmsg_type = UDP_SEGMENT; cm->cmsg_len = CMSG_LEN(sizeof(uint16_t)); @@ -885,7 +897,7 @@ namespace platf { msgs[i].msg_hdr.msg_name = msg.msg_name; msgs[i].msg_hdr.msg_namelen = msg.msg_namelen; - msgs[i].msg_hdr.msg_control = cmbuf.buf; + msgs[i].msg_hdr.msg_control = cmbuf.buf.data(); msgs[i].msg_hdr.msg_controllen = cmbuflen; msgs[i].msg_hdr.msg_flags = 0; } @@ -946,62 +958,20 @@ namespace platf { union { #ifdef IP_PKTINFO - char buf[std::max(CMSG_SPACE(sizeof(struct in_pktinfo)), CMSG_SPACE(sizeof(struct in6_pktinfo)))]; + std::array buf; #elif defined(IP_SENDSRCADDR) // FreeBSD uses IP_SENDSRCADDR with struct in_addr instead of IP_PKTINFO with struct in_pktinfo - char buf[std::max(CMSG_SPACE(sizeof(struct in_addr)), CMSG_SPACE(sizeof(struct in6_pktinfo)))]; + std::array buf; #endif struct cmsghdr alignment; } cmbuf; - socklen_t cmbuflen = 0; + msg.msg_control = cmbuf.buf.data(); + msg.msg_controllen = cmbuf.buf.size(); - msg.msg_control = cmbuf.buf; - msg.msg_controllen = sizeof(cmbuf.buf); + auto cmbuflen = populate_source_pktinfo(msg, send_info.source_address); - auto pktinfo_cm = CMSG_FIRSTHDR(&msg); - if (send_info.source_address.is_v6()) { - struct in6_pktinfo pktInfo; - - struct sockaddr_in6 saddr_v6 = to_sockaddr(send_info.source_address.to_v6(), 0); - pktInfo.ipi6_addr = saddr_v6.sin6_addr; - pktInfo.ipi6_ifindex = 0; - - cmbuflen += CMSG_SPACE(sizeof(pktInfo)); - - pktinfo_cm->cmsg_level = IPPROTO_IPV6; - pktinfo_cm->cmsg_type = IPV6_PKTINFO; - pktinfo_cm->cmsg_len = CMSG_LEN(sizeof(pktInfo)); - memcpy(CMSG_DATA(pktinfo_cm), &pktInfo, sizeof(pktInfo)); - } else { -#ifdef IP_PKTINFO - struct in_pktinfo pktInfo; - - struct sockaddr_in saddr_v4 = to_sockaddr(send_info.source_address.to_v4(), 0); - pktInfo.ipi_spec_dst = saddr_v4.sin_addr; - pktInfo.ipi_ifindex = 0; - - cmbuflen += CMSG_SPACE(sizeof(pktInfo)); - - pktinfo_cm->cmsg_level = IPPROTO_IP; - pktinfo_cm->cmsg_type = IP_PKTINFO; - pktinfo_cm->cmsg_len = CMSG_LEN(sizeof(pktInfo)); - memcpy(CMSG_DATA(pktinfo_cm), &pktInfo, sizeof(pktInfo)); -#elif defined(IP_SENDSRCADDR) - // FreeBSD uses IP_SENDSRCADDR with struct in_addr instead of IP_PKTINFO - struct sockaddr_in saddr_v4 = to_sockaddr(send_info.source_address.to_v4(), 0); - struct in_addr src_addr = saddr_v4.sin_addr; - - cmbuflen += CMSG_SPACE(sizeof(src_addr)); - - pktinfo_cm->cmsg_level = IPPROTO_IP; - pktinfo_cm->cmsg_type = IP_SENDSRCADDR; - pktinfo_cm->cmsg_len = CMSG_LEN(sizeof(src_addr)); - memcpy(CMSG_DATA(pktinfo_cm), &src_addr, sizeof(src_addr)); -#endif - } - - struct iovec iovs[2]; + std::array iovs; int iovlen = 0; if (send_info.header) { iovs[iovlen].iov_base = (void *) send_info.header; @@ -1012,7 +982,7 @@ namespace platf { iovs[iovlen].iov_len = send_info.payload_size; iovlen++; - msg.msg_iov = iovs; + msg.msg_iov = iovs.data(); msg.msg_iovlen = iovlen; msg.msg_controllen = cmbuflen; diff --git a/src/platform/linux/pipewire.cpp b/src/platform/linux/pipewire.cpp index 7d9b9076c..6ce9d3e21 100644 --- a/src/platform/linux/pipewire.cpp +++ b/src/platform/linux/pipewire.cpp @@ -1202,7 +1202,7 @@ namespace pipewire { img->serial = std::numeric_limitsserial)>::max(); img->data = nullptr; img->data_owned = false; - std::fill_n(img->sd.fds, 4, -1); + img->sd.fds.fill(-1); return img; } diff --git a/src/platform/linux/vaapi.cpp b/src/platform/linux/vaapi.cpp index 44f492bca..1badbb7a8 100644 --- a/src/platform/linux/vaapi.cpp +++ b/src/platform/linux/vaapi.cpp @@ -3,6 +3,8 @@ * @brief Definitions for VA-API hardware accelerated capture. */ // standard includes +#include +#include #include #include #include @@ -13,6 +15,7 @@ extern "C" { #include #include #include +#include #if !VA_CHECK_VERSION(1, 9, 0) /** * @brief Stub vaSyncBuffer when building against libva before 2.9.0. @@ -101,7 +104,10 @@ namespace va { // Number of distinct DRM objects making up the surface. uint32_t num_objects; ///< Num objects. - struct { + /** + * @brief Backing DRM PRIME object with its file descriptor and layout. + */ + struct object_t { // DRM PRIME file descriptor for this object. // Needs to be closed manually int fd; ///< DRM PRIME file descriptor for this object; the owner must close it. @@ -110,12 +116,17 @@ namespace va { uint32_t size; ///< Total byte size of the DRM object. // Format modifier applied to this object, not sure what that means uint64_t drm_format_modifier; ///< DRM format modifier applied to this object. - } objects[4]; ///< DRM PRIME backing objects referenced by the descriptor.. + }; + + std::array objects; ///< DRM PRIME backing objects referenced by the descriptor. // Number of layers making up the surface. uint32_t num_layers; ///< Num layers. - struct { + /** + * @brief DRM layer describing the planes of an exported surface. + */ + struct layer_t { // DRM format fourcc of this layer (DRM_FOURCC_*). uint32_t drm_format; ///< DRM fourcc pixel format for this layer. @@ -123,16 +134,23 @@ namespace va { uint32_t num_planes; ///< Number of image planes in this layer. // references objects --> DRMPRIMESurfaceDescriptor.objects[object_index[0]] - uint32_t object_index[4]; ///< Index of the backing DRM object for each plane. + std::array object_index; ///< Index of the backing DRM object for each plane. // Offset within the object of each plane. - uint32_t offset[4]; ///< Byte offset of each plane within its backing object. + std::array offset; ///< Byte offset of each plane within its backing object. // Pitch of each plane. - uint32_t pitch[4]; ///< Row pitch in bytes for each plane. - } layers[4]; ///< DRM PRIME layer descriptions for the frame.. + std::array pitch; ///< Row pitch in bytes for each plane. + }; + + std::array layers; ///< DRM PRIME layer descriptions for the frame. }; + static_assert(sizeof(DRMPRIMESurfaceDescriptor) == sizeof(VADRMPRIMESurfaceDescriptor)); + static_assert(alignof(DRMPRIMESurfaceDescriptor) == alignof(VADRMPRIMESurfaceDescriptor)); + static_assert(offsetof(DRMPRIMESurfaceDescriptor, objects) == offsetof(VADRMPRIMESurfaceDescriptor, objects)); + static_assert(offsetof(DRMPRIMESurfaceDescriptor, layers) == offsetof(VADRMPRIMESurfaceDescriptor, layers)); + /** * @brief VA display handle released with `vaTerminate`. */ @@ -172,8 +190,8 @@ namespace va { gbm.reset(gbm::create_device(file.el)); if (!gbm) { - char string[1024]; - BOOST_LOG(error) << "Couldn't create GBM device: ["sv << strerror_r(errno, string, sizeof(string)) << ']'; + std::array string; + BOOST_LOG(error) << "Couldn't create GBM device: ["sv << strerror_r(errno, string.data(), string.size()) << ']'; return -1; } @@ -211,7 +229,7 @@ namespace va { entrypoints.resize(num_eps); // Sorted in order of descending preference - VAEntrypoint ep_preferences[] = { + std::array ep_preferences = { VAEntrypointEncSliceLP, VAEntrypointEncSlice, VAEntrypointEncPicture @@ -460,7 +478,7 @@ namespace va { return -1; } - egl::surface_descriptor_t sds[2] = {}; + std::array sds = {}; for (int plane = 0; plane < 2; ++plane) { auto &sd = sds[plane]; auto &layer = prime.layers[plane]; @@ -474,7 +492,7 @@ namespace va { // The modifier must be the same for all planes sd.modifier = prime.objects[layer.object_index[0]].drm_format_modifier; - std::fill_n(sd.fds, 4, -1); + sd.fds.fill(-1); for (int x = 0; x < layer.num_planes; ++x) { sd.fds[x] = prime.objects[layer.object_index[x]].fd; sd.pitches[x] = layer.pitch[x]; @@ -705,8 +723,8 @@ namespace va { auto err = av_hwdevice_ctx_init(*hw_device_buf); if (err) { - char err_str[AV_ERROR_MAX_STRING_SIZE] {0}; - BOOST_LOG(error) << "Failed to create FFMpeg hardware device context: "sv << av_make_error_string(err_str, AV_ERROR_MAX_STRING_SIZE, err); + std::array err_str {0}; + BOOST_LOG(error) << "Failed to create FFMpeg hardware device context: "sv << av_make_error_string(err_str.data(), AV_ERROR_MAX_STRING_SIZE, err); return err; } @@ -741,11 +759,11 @@ namespace va { bool validate(int fd) { va::display_t display {vaGetDisplayDRM(fd)}; if (!display) { - char string[1024]; + std::array string; - auto bytes = readlink(std::format("/proc/self/fd/{}", fd).c_str(), string, sizeof(string)); + auto bytes = readlink(std::format("/proc/self/fd/{}", fd).c_str(), string.data(), string.size()); - std::string_view render_device {string, (std::size_t) bytes}; + std::string_view render_device {string.data(), (std::size_t) bytes}; BOOST_LOG(error) << "Couldn't open a va display from DRM with device: "sv << render_device; return false; @@ -805,8 +823,8 @@ namespace va { file_t file = ::open(render_device.c_str(), O_RDWR); // NOSONAR(cpp:S1874): `_sopen_s` not available if (file.el < 0) { - char string[1024]; - BOOST_LOG(error) << "Couldn't open "sv << render_device << ": " << strerror_r(errno, string, sizeof(string)); + std::array string; + BOOST_LOG(error) << "Couldn't open "sv << render_device << ": " << strerror_r(errno, string.data(), string.size()); return nullptr; } diff --git a/src/platform/linux/vulkan_encode.cpp b/src/platform/linux/vulkan_encode.cpp index 1b4ca5a4b..cc1b7972f 100644 --- a/src/platform/linux/vulkan_encode.cpp +++ b/src/platform/linux/vulkan_encode.cpp @@ -591,11 +591,11 @@ namespace vk { void apply_colorspace() override { auto *colors = video::color_vectors_from_colorspace(colorspace, true); if (colors) { - memcpy(push.color_vec_y.data(), colors->color_vec_y, sizeof(push.color_vec_y)); - memcpy(push.color_vec_u.data(), colors->color_vec_u, sizeof(push.color_vec_u)); - memcpy(push.color_vec_v.data(), colors->color_vec_v, sizeof(push.color_vec_v)); - memcpy(push.range_y.data(), colors->range_y, sizeof(push.range_y)); - memcpy(push.range_uv.data(), colors->range_uv, sizeof(push.range_uv)); + push.color_vec_y = colors->color_vec_y; + push.color_vec_u = colors->color_vec_u; + push.color_vec_v = colors->color_vec_v; + push.range_y = colors->range_y; + push.range_uv = colors->range_uv; } } diff --git a/src/platform/linux/wayland.cpp b/src/platform/linux/wayland.cpp index 0fd483e47..46b5eefd3 100644 --- a/src/platform/linux/wayland.cpp +++ b/src/platform/linux/wayland.cpp @@ -680,7 +680,7 @@ namespace wl { frame_t::frame_t() { // File descriptors aren't open - std::fill_n(sd.fds, 4, -1); + sd.fds.fill(-1); }; /** diff --git a/src/platform/linux/wlgrab.cpp b/src/platform/linux/wlgrab.cpp index 2380fed97..c5cd887c7 100644 --- a/src/platform/linux/wlgrab.cpp +++ b/src/platform/linux/wlgrab.cpp @@ -530,7 +530,7 @@ namespace wl { img->frame_timestamp = current_frame->frame_timestamp; // Prevent dmabuf from closing the file descriptors. - std::fill_n(current_frame->sd.fds, 4, -1); + current_frame->sd.fds.fill(-1); return platf::capture_e::ok; } @@ -550,7 +550,7 @@ namespace wl { img->data = nullptr; // File descriptors aren't open - std::fill_n(img->sd.fds, 4, -1); + img->sd.fds.fill(-1); return img; } diff --git a/src/platform/windows/audio.cpp b/src/platform/windows/audio.cpp index 9edb84034..e00033f33 100644 --- a/src/platform/windows/audio.cpp +++ b/src/platform/windows/audio.cpp @@ -5,6 +5,7 @@ #define INITGUID // standard includes +#include #include #include #include @@ -1360,9 +1361,9 @@ namespace platf::audio { auto old_default_dev = default_device(device_enum); // Install the Steam Streaming Speakers driver - WCHAR driver_path[MAX_PATH] = {}; - ExpandEnvironmentStringsW(STEAM_AUDIO_DRIVER_PATH, driver_path, ARRAYSIZE(driver_path)); - if (fn_DiInstallDriverW(nullptr, driver_path, 0, nullptr)) { + std::array driver_path = {}; + ExpandEnvironmentStringsW(STEAM_AUDIO_DRIVER_PATH, driver_path.data(), driver_path.size()); + if (fn_DiInstallDriverW(nullptr, driver_path.data(), 0, nullptr)) { BOOST_LOG(info) << "Successfully installed Steam Streaming Speakers"sv; // Wait for 5 seconds to allow the audio subsystem to reconfigure things before diff --git a/src/platform/windows/display.h b/src/platform/windows/display.h index 627e64e8f..cfd588ded 100644 --- a/src/platform/windows/display.h +++ b/src/platform/windows/display.h @@ -20,7 +20,10 @@ #include "src/video.h" namespace platf::dxgi { - extern const char *format_str[]; + /** + * @brief Diagnostic names indexed by DXGI_FORMAT. + */ + extern const std::array format_str; // Add D3D11_CREATE_DEVICE_DEBUG here to enable the D3D11 debug runtime. // You should have a debugger like WinDbg attached to receive debug messages. diff --git a/src/platform/windows/display_base.cpp b/src/platform/windows/display_base.cpp index 1872b905e..8005949cf 100644 --- a/src/platform/windows/display_base.cpp +++ b/src/platform/windows/display_base.cpp @@ -3,6 +3,7 @@ * @brief Definitions for the Windows display base code. */ // standard includes +#include #include #include @@ -366,7 +367,7 @@ namespace platf::dxgi { * @return True when Desktop Duplication can capture the requested output. */ bool test_dxgi_duplication(adapter_t &adapter, output_t &output, bool enumeration_only) { - D3D_FEATURE_LEVEL featureLevels[] { + std::array featureLevels { D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, @@ -382,8 +383,8 @@ namespace platf::dxgi { D3D_DRIVER_TYPE_UNKNOWN, nullptr, D3D11_CREATE_DEVICE_FLAGS, - featureLevels, - sizeof(featureLevels) / sizeof(D3D_FEATURE_LEVEL), + featureLevels.data(), + featureLevels.size(), D3D11_SDK_VERSION, &device, nullptr, @@ -561,7 +562,7 @@ namespace platf::dxgi { return -1; } - D3D_FEATURE_LEVEL featureLevels[] { + std::array featureLevels { D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, @@ -582,8 +583,8 @@ namespace platf::dxgi { D3D_DRIVER_TYPE_UNKNOWN, nullptr, D3D11_CREATE_DEVICE_FLAGS, - featureLevels, - sizeof(featureLevels) / sizeof(D3D_FEATURE_LEVEL), + featureLevels.data(), + featureLevels.size(), D3D11_SDK_VERSION, &device, &feature_level, @@ -830,7 +831,7 @@ namespace platf::dxgi { /** * @brief Names for DXGI_FORMAT values used in diagnostic logging. */ - const char *format_str[] = { + const std::array format_str = { "DXGI_FORMAT_UNKNOWN", "DXGI_FORMAT_R32G32B32A32_TYPELESS", "DXGI_FORMAT_R32G32B32A32_FLOAT", @@ -973,7 +974,7 @@ namespace platf::dxgi { } const char *display_base_t::colorspace_to_string(DXGI_COLOR_SPACE_TYPE type) { - const char *type_str[] = { + std::array type_str = { "DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P709", "DXGI_COLOR_SPACE_RGB_FULL_G10_NONE_P709", "DXGI_COLOR_SPACE_RGB_STUDIO_G22_NONE_P709", @@ -1001,7 +1002,7 @@ namespace platf::dxgi { "DXGI_COLOR_SPACE_YCBCR_STUDIO_G24_TOPLEFT_P2020", }; - if (type < ARRAYSIZE(type_str)) { + if (type < type_str.size()) { return type_str[type]; } else { return "UNKNOWN"; diff --git a/src/platform/windows/display_vram.cpp b/src/platform/windows/display_vram.cpp index 48913eddd..b7b3c743a 100644 --- a/src/platform/windows/display_vram.cpp +++ b/src/platform/windows/display_vram.cpp @@ -3,6 +3,7 @@ * @brief Definitions for handling video ram. */ // standard includes +#include #include // platform includes @@ -728,7 +729,7 @@ namespace platf::dxgi { out_UV_viewport = {offsetX / 2, offsetY / 2, out_width_f / 2, out_height_f / 2, 0.0f, 1.0f}; out_UV_viewport_for_clear = {0, 0, (float) out_width / 2, (float) out_height / 2, 0.0f, 1.0f}; - float subsample_offset_in[16 / sizeof(float)] {1.0f / (float) out_width_f, 1.0f / (float) out_height_f}; // aligned to 16-byte + std::array subsample_offset_in {1.0f / (float) out_width_f, 1.0f / (float) out_height_f}; // aligned to 16-byte subsample_offset = make_buffer(device.get(), subsample_offset_in); if (!subsample_offset) { @@ -739,7 +740,7 @@ namespace platf::dxgi { { int32_t rotation_modifier = display->display_rotation == DXGI_MODE_ROTATION_UNSPECIFIED ? 0 : display->display_rotation - 1; - int32_t rotation_data[16 / sizeof(int32_t)] {-rotation_modifier}; // aligned to 16-byte + std::array rotation_data {-rotation_modifier}; // aligned to 16-byte auto rotation = make_buffer(device.get(), rotation_data); if (!rotation) { BOOST_LOG(error) << "Failed to create display rotation vertex constant buffer"; @@ -808,11 +809,11 @@ namespace platf::dxgi { if (rtv_simple_clear) { // Clear the RTVs to ensure the aspect ratio padding is black - const float y_black[] = {0.0f, 0.0f, 0.0f, 0.0f}; - device_ctx->ClearRenderTargetView(out_Y_or_YUV_rtv.get(), y_black); + const std::array y_black = {0.0f, 0.0f, 0.0f, 0.0f}; + device_ctx->ClearRenderTargetView(out_Y_or_YUV_rtv.get(), y_black.data()); if (out_UV_rtv) { - const float uv_black[] = {0.5f, 0.5f, 0.5f, 0.5f}; - device_ctx->ClearRenderTargetView(out_UV_rtv.get(), uv_black); + const std::array uv_black = {0.5f, 0.5f, 0.5f, 0.5f}; + device_ctx->ClearRenderTargetView(out_UV_rtv.get(), uv_black.data()); } rtvs_cleared = true; } else { @@ -859,7 +860,7 @@ namespace platf::dxgi { return -1; } - D3D_FEATURE_LEVEL featureLevels[] { + std::array featureLevels { D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, @@ -874,8 +875,8 @@ namespace platf::dxgi { D3D_DRIVER_TYPE_UNKNOWN, nullptr, D3D11_CREATE_DEVICE_FLAGS | D3D11_CREATE_DEVICE_VIDEO_SUPPORT, - featureLevels, - sizeof(featureLevels) / sizeof(D3D_FEATURE_LEVEL), + featureLevels.data(), + featureLevels.size(), D3D11_SDK_VERSION, &device, nullptr, @@ -1197,8 +1198,8 @@ namespace platf::dxgi { if (!frame->buf[0]) { auto err = av_hwframe_get_buffer(hw_frames_ctx, frame, 0); if (err) { - char err_str[AV_ERROR_MAX_STRING_SIZE] {0}; - BOOST_LOG(error) << "Failed to get hwframe buffer: "sv << av_make_error_string(err_str, AV_ERROR_MAX_STRING_SIZE, err); + std::array err_str {0}; + BOOST_LOG(error) << "Failed to get hwframe buffer: "sv << av_make_error_string(err_str.data(), AV_ERROR_MAX_STRING_SIZE, err); return -1; } } @@ -1212,8 +1213,8 @@ namespace platf::dxgi { auto err = av_hwframe_map(d3d11_frame.get(), frame, AV_HWFRAME_MAP_WRITE | AV_HWFRAME_MAP_OVERWRITE); if (err) { - char err_str[AV_ERROR_MAX_STRING_SIZE] {0}; - BOOST_LOG(error) << "Failed to map D3D11 frame: "sv << av_make_error_string(err_str, AV_ERROR_MAX_STRING_SIZE, err); + std::array err_str {0}; + BOOST_LOG(error) << "Failed to map D3D11 frame: "sv << av_make_error_string(err_str.data(), AV_ERROR_MAX_STRING_SIZE, err); return -1; } @@ -1743,8 +1744,8 @@ namespace platf::dxgi { } if (reclear_dummy) { - const float rgb_black[] = {0.0f, 0.0f, 0.0f, 0.0f}; - device_ctx->ClearRenderTargetView(d3d_img->capture_rt.get(), rgb_black); + const std::array rgb_black = {0.0f, 0.0f, 0.0f, 0.0f}; + device_ctx->ClearRenderTargetView(d3d_img->capture_rt.get(), rgb_black.data()); } if (blend_mouse_cursor_flag) { @@ -1799,7 +1800,7 @@ namespace platf::dxgi { { int32_t rotation_modifier = display_rotation == DXGI_MODE_ROTATION_UNSPECIFIED ? 0 : display_rotation - 1; - int32_t rotation_data[16 / sizeof(int32_t)] {rotation_modifier}; // aligned to 16-byte + std::array rotation_data {rotation_modifier}; // aligned to 16-byte auto rotation = make_buffer(device.get(), rotation_data); if (!rotation) { BOOST_LOG(error) << "Failed to create display rotation vertex constant buffer"; @@ -1819,7 +1820,7 @@ namespace platf::dxgi { // Use a 300 nit target for the mouse cursor. We should really get // the user's SDR white level in nits, but there is no API that // provides that information to Win32 apps. - float white_multiplier_data[16 / sizeof(float)] {300.0f / 80.f}; // aligned to 16-byte + std::array white_multiplier_data {300.0f / 80.f}; // aligned to 16-byte auto white_multiplier = make_buffer(device.get(), white_multiplier_data); if (!white_multiplier) { BOOST_LOG(warning) << "Failed to create cursor blending (normalized white) white multiplier constant buffer"; diff --git a/src/platform/windows/input.cpp b/src/platform/windows/input.cpp index 54f09f5cc..2a2176d5e 100644 --- a/src/platform/windows/input.cpp +++ b/src/platform/windows/input.cpp @@ -14,6 +14,7 @@ #endif // platform includes +#include #include // standard includes @@ -1132,7 +1133,7 @@ namespace platf { // Touchpad is 1920x943 according to ViGEm uint16_t x = touch.x * 1920; uint16_t y = touch.y * 943; - uint8_t touchData[] = { + std::array touchData = { (uint8_t) (x & 0xFF), // Low 8 bits of X (uint8_t) ((x >> 8 & 0x0F) | (y & 0x0F) << 4), // High 4 bits of X and low 4 bits of Y (uint8_t) (y >> 4 & 0xFF) // High 8 bits of Y @@ -1141,9 +1142,9 @@ namespace platf { report.sCurrentTouch.bPacketCounter++; if (touch.eventType != LI_TOUCH_EVENT_CANCEL_ALL) { if (pointerIndex == 0) { - memcpy(report.sCurrentTouch.bTouchData1, touchData, sizeof(touchData)); + memcpy(report.sCurrentTouch.bTouchData1, touchData.data(), touchData.size()); } else { - memcpy(report.sCurrentTouch.bTouchData2, touchData, sizeof(touchData)); + memcpy(report.sCurrentTouch.bTouchData2, touchData.data(), touchData.size()); } } diff --git a/src/platform/windows/misc.cpp b/src/platform/windows/misc.cpp index 7097c850c..c619138d4 100644 --- a/src/platform/windows/misc.cpp +++ b/src/platform/windows/misc.cpp @@ -3,6 +3,7 @@ * @brief Miscellaneous definitions for Windows. */ // standard includes +#include #include #include #include @@ -160,9 +161,9 @@ namespace platf { decltype(WlanSetInterface) *fn_WlanSetInterface = nullptr; ///< Fn wlan set interface. std::filesystem::path appdata() { - WCHAR sunshine_path[MAX_PATH]; - GetModuleFileNameW(nullptr, sunshine_path, _countof(sunshine_path)); - return std::filesystem::path {sunshine_path}.remove_filename() / L"config"sv; + std::array sunshine_path; + GetModuleFileNameW(nullptr, sunshine_path.data(), sunshine_path.size()); + return std::filesystem::path {sunshine_path.data()}.remove_filename() / L"config"sv; } /** @@ -175,32 +176,28 @@ namespace platf { } std::string from_sockaddr(const sockaddr *const socket_address) { - char data[INET6_ADDRSTRLEN] = {}; + std::array data = {}; auto family = socket_address->sa_family; if (family == AF_INET6) { - inet_ntop(AF_INET6, &((sockaddr_in6 *) socket_address)->sin6_addr, data, INET6_ADDRSTRLEN); + inet_ntop(AF_INET6, &((const sockaddr_in6 *) socket_address)->sin6_addr, data.data(), INET6_ADDRSTRLEN); } else if (family == AF_INET) { - inet_ntop(AF_INET, &((sockaddr_in *) socket_address)->sin_addr, data, INET_ADDRSTRLEN); + inet_ntop(AF_INET, &((const sockaddr_in *) socket_address)->sin_addr, data.data(), INET_ADDRSTRLEN); } - return std::string {data}; + return std::string {data.data()}; } std::pair from_sockaddr_ex(const sockaddr *const ip_addr) { - char data[INET6_ADDRSTRLEN] = {}; - auto family = ip_addr->sa_family; std::uint16_t port = 0; if (family == AF_INET6) { - inet_ntop(AF_INET6, &((sockaddr_in6 *) ip_addr)->sin6_addr, data, INET6_ADDRSTRLEN); - port = ((sockaddr_in6 *) ip_addr)->sin6_port; + port = ((const sockaddr_in6 *) ip_addr)->sin6_port; } else if (family == AF_INET) { - inet_ntop(AF_INET, &((sockaddr_in *) ip_addr)->sin_addr, data, INET_ADDRSTRLEN); - port = ((sockaddr_in *) ip_addr)->sin_port; + port = ((const sockaddr_in *) ip_addr)->sin_port; } - return {port, std::string {data}}; + return {port, from_sockaddr(ip_addr)}; } /** @@ -266,11 +263,11 @@ namespace platf { * @brief Write status details to the log. */ void print_status(const std::string_view &prefix, HRESULT status) { - char err_string[1024]; + std::array err_string; - DWORD bytes = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, status, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), err_string, sizeof(err_string), nullptr); + DWORD bytes = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, status, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), err_string.data(), err_string.size(), nullptr); - BOOST_LOG(error) << prefix << ": "sv << std::string_view {err_string, bytes}; + BOOST_LOG(error) << prefix << ": "sv << std::string_view {err_string.data(), bytes}; } /** @@ -1320,15 +1317,15 @@ namespace platf { STARTUPINFOEXW startup_info {}; startup_info.StartupInfo.cb = sizeof(startup_info); - WCHAR executable[MAX_PATH]; - if (GetModuleFileNameW(nullptr, executable, ARRAYSIZE(executable)) == 0) { + std::array executable; + if (GetModuleFileNameW(nullptr, executable.data(), executable.size()) == 0) { auto winerr = GetLastError(); BOOST_LOG(fatal) << "Failed to get Sunshine path: "sv << winerr; return; } PROCESS_INFORMATION process_info; - if (!CreateProcessW(executable, GetCommandLineW(), nullptr, nullptr, false, CREATE_UNICODE_ENVIRONMENT | EXTENDED_STARTUPINFO_PRESENT, nullptr, nullptr, (LPSTARTUPINFOW) &startup_info, &process_info)) { + if (!CreateProcessW(executable.data(), GetCommandLineW(), nullptr, nullptr, false, CREATE_UNICODE_ENVIRONMENT | EXTENDED_STARTUPINFO_PRESENT, nullptr, nullptr, (LPSTARTUPINFOW) &startup_info, &process_info)) { auto winerr = GetLastError(); BOOST_LOG(fatal) << "Unable to restart Sunshine: "sv << winerr; return; @@ -1462,6 +1459,47 @@ namespace platf { return saddr_v6; } + /** + * @brief Write the source IP address into the first ancillary control message. + * + * @param msg Socket message with control storage sized for packet information. + * @param source_address Local IP address to use for outgoing packets. + * @return Bytes occupied by the packet-information control message. + */ + static ULONG populate_source_pktinfo(WSAMSG &msg, const boost::asio::ip::address &source_address) { + ULONG cmbuflen = 0; + auto cm = WSA_CMSG_FIRSTHDR(&msg); + if (source_address.is_v6()) { + IN6_PKTINFO pktInfo; + + SOCKADDR_IN6 saddr_v6 = to_sockaddr(source_address.to_v6(), 0); + pktInfo.ipi6_addr = saddr_v6.sin6_addr; + pktInfo.ipi6_ifindex = 0; + + cmbuflen += WSA_CMSG_SPACE(sizeof(pktInfo)); + + cm->cmsg_level = IPPROTO_IPV6; + cm->cmsg_type = IPV6_PKTINFO; + cm->cmsg_len = WSA_CMSG_LEN(sizeof(pktInfo)); + memcpy(WSA_CMSG_DATA(cm), &pktInfo, sizeof(pktInfo)); + } else { + IN_PKTINFO pktInfo; + + SOCKADDR_IN saddr_v4 = to_sockaddr(source_address.to_v4(), 0); + pktInfo.ipi_addr = saddr_v4.sin_addr; + pktInfo.ipi_ifindex = 0; + + cmbuflen += WSA_CMSG_SPACE(sizeof(pktInfo)); + + cm->cmsg_level = IPPROTO_IP; + cm->cmsg_type = IP_PKTINFO; + cm->cmsg_len = WSA_CMSG_LEN(sizeof(pktInfo)); + memcpy(WSA_CMSG_DATA(cm), &pktInfo, sizeof(pktInfo)); + } + + return cmbuflen; + } + // Use UDP segmentation offload if it is supported by the OS. If the NIC is capable, this will use // hardware acceleration to reduce CPU usage. Support for USO was introduced in Windows 10 20H1. bool send_batch(batched_send_info_t &send_info) { @@ -1515,45 +1553,16 @@ namespace platf { msg.dwFlags = 0; // At most, one DWORD option and one PKTINFO option - char cmbuf[WSA_CMSG_SPACE(sizeof(DWORD)) + std::max(WSA_CMSG_SPACE(sizeof(IN6_PKTINFO)), WSA_CMSG_SPACE(sizeof(IN_PKTINFO)))] = {}; - ULONG cmbuflen = 0; + std::array cmbuf = {}; + msg.Control.buf = cmbuf.data(); + msg.Control.len = cmbuf.size(); - msg.Control.buf = cmbuf; - msg.Control.len = sizeof(cmbuf); - - auto cm = WSA_CMSG_FIRSTHDR(&msg); - if (send_info.source_address.is_v6()) { - IN6_PKTINFO pktInfo; - - SOCKADDR_IN6 saddr_v6 = to_sockaddr(send_info.source_address.to_v6(), 0); - pktInfo.ipi6_addr = saddr_v6.sin6_addr; - pktInfo.ipi6_ifindex = 0; - - cmbuflen += WSA_CMSG_SPACE(sizeof(pktInfo)); - - cm->cmsg_level = IPPROTO_IPV6; - cm->cmsg_type = IPV6_PKTINFO; - cm->cmsg_len = WSA_CMSG_LEN(sizeof(pktInfo)); - memcpy(WSA_CMSG_DATA(cm), &pktInfo, sizeof(pktInfo)); - } else { - IN_PKTINFO pktInfo; - - SOCKADDR_IN saddr_v4 = to_sockaddr(send_info.source_address.to_v4(), 0); - pktInfo.ipi_addr = saddr_v4.sin_addr; - pktInfo.ipi_ifindex = 0; - - cmbuflen += WSA_CMSG_SPACE(sizeof(pktInfo)); - - cm->cmsg_level = IPPROTO_IP; - cm->cmsg_type = IP_PKTINFO; - cm->cmsg_len = WSA_CMSG_LEN(sizeof(pktInfo)); - memcpy(WSA_CMSG_DATA(cm), &pktInfo, sizeof(pktInfo)); - } + auto cmbuflen = populate_source_pktinfo(msg, send_info.source_address); if (send_info.block_count > 1) { cmbuflen += WSA_CMSG_SPACE(sizeof(DWORD)); - cm = WSA_CMSG_NXTHDR(&msg, cm); + auto cm = WSA_CMSG_NXTHDR(&msg, WSA_CMSG_FIRSTHDR(&msg)); cm->cmsg_level = IPPROTO_UDP; cm->cmsg_type = UDP_SEND_MSG_SIZE; cm->cmsg_len = WSA_CMSG_LEN(sizeof(DWORD)); @@ -1585,7 +1594,7 @@ namespace platf { msg.namelen = sizeof(taddr_v4); } - WSABUF bufs[2]; + std::array bufs; DWORD bufcount = 0; if (send_info.header) { bufs[bufcount].buf = (char *) send_info.header; @@ -1596,44 +1605,15 @@ namespace platf { bufs[bufcount].len = send_info.payload_size; bufcount++; - msg.lpBuffers = bufs; + msg.lpBuffers = bufs.data(); msg.dwBufferCount = bufcount; msg.dwFlags = 0; - char cmbuf[std::max(WSA_CMSG_SPACE(sizeof(IN6_PKTINFO)), WSA_CMSG_SPACE(sizeof(IN_PKTINFO)))] = {}; - ULONG cmbuflen = 0; + std::array cmbuf = {}; + msg.Control.buf = cmbuf.data(); + msg.Control.len = cmbuf.size(); - msg.Control.buf = cmbuf; - msg.Control.len = sizeof(cmbuf); - - auto cm = WSA_CMSG_FIRSTHDR(&msg); - if (send_info.source_address.is_v6()) { - IN6_PKTINFO pktInfo; - - SOCKADDR_IN6 saddr_v6 = to_sockaddr(send_info.source_address.to_v6(), 0); - pktInfo.ipi6_addr = saddr_v6.sin6_addr; - pktInfo.ipi6_ifindex = 0; - - cmbuflen += WSA_CMSG_SPACE(sizeof(pktInfo)); - - cm->cmsg_level = IPPROTO_IPV6; - cm->cmsg_type = IPV6_PKTINFO; - cm->cmsg_len = WSA_CMSG_LEN(sizeof(pktInfo)); - memcpy(WSA_CMSG_DATA(cm), &pktInfo, sizeof(pktInfo)); - } else { - IN_PKTINFO pktInfo; - - SOCKADDR_IN saddr_v4 = to_sockaddr(send_info.source_address.to_v4(), 0); - pktInfo.ipi_addr = saddr_v4.sin_addr; - pktInfo.ipi_ifindex = 0; - - cmbuflen += WSA_CMSG_SPACE(sizeof(pktInfo)); - - cm->cmsg_level = IPPROTO_IP; - cm->cmsg_type = IP_PKTINFO; - cm->cmsg_len = WSA_CMSG_LEN(sizeof(pktInfo)); - memcpy(WSA_CMSG_DATA(cm), &pktInfo, sizeof(pktInfo)); - } + auto cmbuflen = populate_source_pktinfo(msg, send_info.source_address); msg.Control.len = cmbuflen; @@ -1813,12 +1793,12 @@ namespace platf { } std::string get_host_name() { - WCHAR hostname[256]; - if (GetHostNameW(hostname, ARRAYSIZE(hostname)) == SOCKET_ERROR) { + std::array hostname; + if (GetHostNameW(hostname.data(), hostname.size()) == SOCKET_ERROR) { BOOST_LOG(error) << "GetHostNameW() failed: "sv << WSAGetLastError(); return "Sunshine"s; } - return utf_utils::to_utf8(hostname); + return utf_utils::to_utf8(hostname.data()); } /** diff --git a/src/platform/windows/nvprefs/nvprefs_interface.cpp b/src/platform/windows/nvprefs/nvprefs_interface.cpp index 09ad072aa..ce27cee09 100644 --- a/src/platform/windows/nvprefs/nvprefs_interface.cpp +++ b/src/platform/windows/nvprefs/nvprefs_interface.cpp @@ -3,6 +3,7 @@ * @brief Definitions for nvidia preferences interface. */ // standard includes +#include #include // local includes @@ -45,15 +46,14 @@ namespace nvprefs { bool nvprefs_interface::load() { if (!pimpl->loaded) { // Check %ProgramData% variable, need it for storing undo file - wchar_t program_data_env[MAX_PATH]; - auto get_env_result = GetEnvironmentVariableW(L"ProgramData", program_data_env, MAX_PATH); - if (get_env_result == 0 || get_env_result >= MAX_PATH || !std::filesystem::is_directory(program_data_env)) { + std::array program_data_env; + if (auto get_env_result = GetEnvironmentVariableW(L"ProgramData", program_data_env.data(), program_data_env.size()); get_env_result == 0 || get_env_result >= MAX_PATH || !std::filesystem::is_directory(program_data_env.data())) { error_message("Missing or malformed %ProgramData% environment variable"); return false; } // Prepare undo file path variables - pimpl->undo_folder_path = std::filesystem::path(program_data_env) / sunshine_program_data_folder; + pimpl->undo_folder_path = std::filesystem::path(program_data_env.data()) / sunshine_program_data_folder; pimpl->undo_file_path = pimpl->undo_folder_path / nvprefs_undo_file_name; // Dynamically load nvapi library and load driver settings diff --git a/src/platform/windows/publish.cpp b/src/platform/windows/publish.cpp index f4a954d03..7347b5a49 100644 --- a/src/platform/windows/publish.cpp +++ b/src/platform/windows/publish.cpp @@ -5,6 +5,7 @@ // platform includes // WinSock2.h must be included before Windows.h // clang-format off +#include #include #include // clang-format on @@ -171,11 +172,11 @@ namespace platf::publish { // Most clients aren't strictly checking TXT record compliance with RFC 1035, // but Apple's mDNS resolver does and rejects the entire answer if an invalid // TXT record is present. - PWCHAR keys[] = {nullptr}; - PWCHAR values[] = {nullptr}; + std::array keys = {nullptr}; + std::array values = {nullptr}; instance.dwPropertyCount = 1; - instance.keys = keys; - instance.values = values; + instance.keys = keys.data(); + instance.values = values.data(); DNS_SERVICE_REGISTER_REQUEST req {}; req.Version = DNS_QUERY_REQUEST_VERSION1; diff --git a/src/process.cpp b/src/process.cpp index 3ca8a718f..a17dbaa8a 100644 --- a/src/process.cpp +++ b/src/process.cpp @@ -5,6 +5,7 @@ #define BOOST_BIND_GLOBAL_PLACEHOLDERS // standard includes +#include #include #include #include @@ -629,18 +630,18 @@ namespace proc { } // Read file and update calculated SHA - char buf[1024 * 16]; + std::array buf; std::ifstream file(filename, std::ifstream::binary); while (file.good()) { - file.read(buf, sizeof(buf)); - if (!EVP_DigestUpdate(ctx.get(), buf, file.gcount())) { + file.read(buf.data(), buf.size()); + if (!EVP_DigestUpdate(ctx.get(), buf.data(), file.gcount())) { return std::nullopt; } } file.close(); - unsigned char result[SHA256_DIGEST_LENGTH]; - if (!EVP_DigestFinal_ex(ctx.get(), result, nullptr)) { + std::array result; + if (!EVP_DigestFinal_ex(ctx.get(), result.data(), nullptr)) { return std::nullopt; } diff --git a/src/rtsp.cpp b/src/rtsp.cpp index c7135ddf0..481300d9a 100644 --- a/src/rtsp.cpp +++ b/src/rtsp.cpp @@ -95,11 +95,14 @@ namespace rtsp_stream { std::uint32_t sequenceNumber; ///< Sequence number. // This field is the AES GCM authentication tag - std::uint8_t tag[16]; ///< Authentication tag appended to the encrypted payload. + std::array tag; ///< Authentication tag appended to the encrypted payload. }; #pragma pack(pop) + static_assert(sizeof(encrypted_rtsp_header_t) == 24); + static_assert(offsetof(encrypted_rtsp_header_t, tag) == 8); + class rtsp_server_t; /** @@ -277,7 +280,7 @@ namespace rtsp_stream { iv[11] = 'R'; // RTSP std::vector plaintext; - if (socket->session->rtsp_cipher->decrypt(std::string_view {(const char *) header->tag, sizeof(header->tag) + bytes}, plaintext, &iv)) { + if (socket->session->rtsp_cipher->decrypt(std::string_view {(const char *) header->tag.data(), sizeof(header->tag) + bytes}, plaintext, &iv)) { BOOST_LOG(error) << "Failed to verify RTSP message tag"sv; respond(socket->sock, *socket->session, nullptr, 400, "BAD REQUEST", 0, {}); @@ -851,7 +854,7 @@ namespace rtsp_stream { header->sequenceNumber = util::endian::big(session.rtsp_iv_counter); // Encrypt the RTSP message in place - session.rtsp_cipher->encrypt(std::string_view {(const char *) header->payload(), (std::size_t) payload_length}, header->tag, &iv); + session.rtsp_cipher->encrypt(std::string_view {(const char *) header->payload(), (std::size_t) payload_length}, header->tag.data(), &iv); // Send the full encrypted message send(sock, std::string_view {(char *) message.data(), message.size()}); @@ -968,7 +971,7 @@ namespace rtsp_stream { for (int x = 0; x < audio::MAX_STREAM_CONFIG; ++x) { auto &stream_config = audio::stream_configs[x]; - std::uint8_t mapping[platf::speaker::MAX_SPEAKERS]; + std::array mapping; auto mapping_p = stream_config.mapping; @@ -978,10 +981,10 @@ namespace rtsp_stream { * To work around this, rotate channels to the left from index '3' */ if (x == audio::SURROUND51 || x == audio::SURROUND71) { - std::copy_n(mapping_p, stream_config.channelCount, mapping); - std::rotate(mapping + 3, mapping + 4, mapping + audio::MAX_STREAM_CONFIG); + std::copy_n(mapping_p, stream_config.channelCount, mapping.begin()); + std::rotate(mapping.begin() + 3, mapping.begin() + 4, mapping.begin() + audio::MAX_STREAM_CONFIG); - mapping_p = mapping; + mapping_p = mapping.data(); } ss << "a=fmtp:97 surround-params="sv << stream_config.channelCount << stream_config.streams << stream_config.coupledStreams; @@ -1005,7 +1008,7 @@ namespace rtsp_stream { * @param req Parsed RTSP request being handled. */ void cmd_setup(rtsp_server_t *server, tcp::socket &sock, launch_session_t &session, msg_t &&req) { - OPTION_ITEM options[4] {}; + std::array options {}; auto &seqn = options[0]; auto &session_option = options[1]; diff --git a/src/stream.cpp b/src/stream.cpp index 1291c9c62..8ecfb3ee3 100644 --- a/src/stream.cpp +++ b/src/stream.cpp @@ -4,6 +4,7 @@ */ // standard includes +#include #include #include #include @@ -54,7 +55,7 @@ constexpr int IDX_SET_RGB_LED = 14; ///< Control-stream message index for set r constexpr int IDX_SET_ADAPTIVE_TRIGGERS = 15; ///< Control-stream message index for set adaptive triggers. constexpr int IDX_SET_PLAYER_LEDS = 16; ///< Control-stream message index for set player indicator LEDs. -static const short packetTypes[] = { +static const std::array packetTypes = { 0x0305, // Start A 0x0307, // Start B 0x0301, // Invalidate reference frames @@ -125,7 +126,7 @@ namespace stream { // zero padding, such as AV1 (Sunshine extension). boost::endian::little_uint16_at lastPayloadLen; ///< Last payload len. - std::uint8_t unknown[2]; ///< Reserved bytes with no known client-visible meaning. + std::array unknown; ///< Reserved bytes with no known client-visible meaning. }; static_assert( @@ -147,7 +148,7 @@ namespace stream { } RTP_PACKET rtp; ///< RTP header that prefixes this payload. - char reserved[4]; ///< Reserved protocol padding bytes. + std::array reserved; ///< Reserved protocol padding bytes. NV_VIDEO_PACKET packet; ///< GameStream video packet header. }; @@ -159,9 +160,9 @@ namespace stream { /** * @brief IV. */ - std::uint8_t iv[12]; // 12-byte IV is ideal for AES-GCM + std::array iv; // 12-byte IV is ideal for AES-GCM std::uint32_t frameNumber; ///< Frame number. - std::uint8_t tag[16]; ///< Authentication tag appended to the encrypted payload. + std::array tag; ///< Authentication tag appended to the encrypted payload. }; /** @@ -269,8 +270,8 @@ namespace stream { std::uint8_t event_flags; std::uint8_t type_left; ///< Adaptive-trigger mode for the left trigger. std::uint8_t type_right; ///< Adaptive-trigger mode for the right trigger. - std::uint8_t left[DS_EFFECT_PAYLOAD_SIZE]; ///< Left adaptive-trigger effect payload. - std::uint8_t right[DS_EFFECT_PAYLOAD_SIZE]; ///< Right adaptive-trigger effect payload. + std::array left; ///< Left adaptive-trigger effect payload. + std::array right; ///< Right adaptive-trigger effect payload. }; /** @@ -317,6 +318,15 @@ namespace stream { #pragma pack(pop) + static_assert(sizeof(video_packet_raw_t) == sizeof(RTP_PACKET) + 4 + sizeof(NV_VIDEO_PACKET)); + static_assert(offsetof(video_packet_raw_t, packet) == sizeof(RTP_PACKET) + 4); + static_assert(sizeof(video_packet_enc_prefix_t) == 32); + static_assert(offsetof(video_packet_enc_prefix_t, frameNumber) == 12); + static_assert(offsetof(video_packet_enc_prefix_t, tag) == 16); + static_assert(sizeof(control_adaptive_triggers_t) == 9 + 2 * DS_EFFECT_PAYLOAD_SIZE); + static_assert(offsetof(control_adaptive_triggers_t, left) == 9); + static_assert(offsetof(control_adaptive_triggers_t, right) == 9 + DS_EFFECT_PAYLOAD_SIZE); + /** * @brief Round a byte count up to the next PKCS#7 padding boundary. * @@ -1097,9 +1107,9 @@ namespace stream { plaintext.id = util::endian::little(msg.id); plaintext.event_flags = msg.data.adaptive_triggers.event_flags; plaintext.type_left = msg.data.adaptive_triggers.type_left; - std::ranges::copy(msg.data.adaptive_triggers.left, plaintext.left); + std::ranges::copy(msg.data.adaptive_triggers.left, plaintext.left.begin()); plaintext.type_right = msg.data.adaptive_triggers.type_right; - std::ranges::copy(msg.data.adaptive_triggers.right, plaintext.right); + std::ranges::copy(msg.data.adaptive_triggers.right, plaintext.right.begin()); std::array encrypted_payload; @@ -1434,8 +1444,8 @@ namespace stream { udp::endpoint peer; - std::array buf[2]; - std::function recv_func[2]; + std::array, 2> buf; + std::array, 2> recv_func; platf::set_thread_name("stream::recv"); @@ -1762,8 +1772,8 @@ namespace stream { // Encrypt the target buffer in place auto *prefix = (video_packet_enc_prefix_t *) shards.prefix(x); prefix->frameNumber = (std::uint32_t) packet->frame_index(); - std::copy(std::begin(iv), std::end(iv), prefix->iv); - session->video.cipher->encrypt(std::string_view {(char *) inspect, (size_t) blocksize}, prefix->tag, (uint8_t *) inspect, &iv); + std::copy(std::begin(iv), std::end(iv), prefix->iv.begin()); + session->video.cipher->encrypt(std::string_view {(char *) inspect, (size_t) blocksize}, prefix->tag.data(), (uint8_t *) inspect, &iv); } if (x - next_shard_to_send + 1 >= send_batch_size || x + 1 == shards.size()) { diff --git a/src/upnp.cpp b/src/upnp.cpp index ca20e9856..d983ce15d 100644 --- a/src/upnp.cpp +++ b/src/upnp.cpp @@ -3,6 +3,7 @@ * @brief Definitions for UPnP port mapping. */ // standard includes +#include #include // workaround for type_t error in miniupnpc 2.3.3, see https://github.com/miniupnp/miniupnp/commit/e263ab6f56c382e10fed31347ec68095d691a0e8 // lib includes @@ -145,10 +146,10 @@ namespace upnp { for (auto it = std::begin(mappings); it != std::end(mappings) && !shutdown_event->peek(); ++it) { auto mapping = *it; - char uniqueId[8]; + std::array uniqueId; // Open a pinhole for the LAN port, since there will be no WAN->LAN port mapping on IPv6 - err = UPNP_AddPinhole(urls->controlURL_6FC, data.IPv6FC.servicetype, "", "0", lan_addr.data(), mapping.port.lan.c_str(), mapping.port.proto.c_str(), mapping_period.c_str(), uniqueId); + err = UPNP_AddPinhole(urls->controlURL_6FC, data.IPv6FC.servicetype, "", "0", lan_addr.data(), mapping.port.lan.c_str(), mapping.port.proto.c_str(), mapping_period.c_str(), uniqueId.data()); if (err == UPNPCOMMAND_SUCCESS) { BOOST_LOG(debug) << "Successfully created pinhole for "sv << mapping.port.proto << ' ' << mapping.port.lan; } else { @@ -180,11 +181,11 @@ namespace upnp { * @return `true` on success. */ bool map_upnp_port(const IGDdatas &data, const urls_t &urls, const std::string &lan_addr, const mapping_t &mapping) { - char intClient[16]; - char intPort[6]; - char desc[80]; - char enabled[4]; - char leaseDuration[16]; + std::array intClient; + std::array intPort; + std::array desc; + std::array enabled; + std::array leaseDuration; bool indefinite = false; // First check if this port is already mapped successfully @@ -197,27 +198,27 @@ namespace upnp { mapping.port.proto.c_str(), nullptr, // Out params - intClient, - intPort, - desc, - enabled, - leaseDuration + intClient.data(), + intPort.data(), + desc.data(), + enabled.data(), + leaseDuration.data() ); if (err == 714) { // NoSuchEntryInArray BOOST_LOG(debug) << "Mapping entry not found for "sv << mapping.port.wan; } else if (err == UPNPCOMMAND_SUCCESS) { // Some routers change the description, so we can't check that here - if (!std::strcmp(intClient, lan_addr.c_str())) { - if (std::atoi(leaseDuration) == 0) { + if (std::string_view {intClient.data()} == lan_addr) { + if (std::atoi(leaseDuration.data()) == 0) { BOOST_LOG(debug) << "Static mapping entry found for "sv << mapping.port.wan; // It's a static mapping, so we're done here return true; } else { - BOOST_LOG(debug) << "Mapping entry found for "sv << mapping.port.wan << " ("sv << leaseDuration << " seconds remaining)"sv; + BOOST_LOG(debug) << "Mapping entry found for "sv << mapping.port.wan << " ("sv << leaseDuration.data() << " seconds remaining)"sv; } } else { - BOOST_LOG(warning) << "UPnP conflict detected with: "sv << intClient; + BOOST_LOG(warning) << "UPnP conflict detected with: "sv << intClient.data(); // Some UPnP IGDs won't let unauthenticated clients delete other conflicting port mappings // for security reasons, but we will give it a try anyway. diff --git a/src/utility.h b/src/utility.h index fa96bdd0c..cf7e7a567 100644 --- a/src/utility.h +++ b/src/utility.h @@ -6,6 +6,8 @@ // standard includes #include +#include +#include #include #include #include @@ -414,7 +416,7 @@ namespace util { typedef T elem_type; private: - const char _bits[16] { + const std::array _bits { '0', '1', '2', @@ -433,7 +435,7 @@ namespace util { 'F' }; - char _hex[sizeof(elem_type) * 2]; + std::array _hex; ///< Formatted hexadecimal characters. public: /** @@ -464,7 +466,7 @@ namespace util { * @return Iterator to the first element. */ char *begin() { - return _hex; + return _hex.data(); } /** @@ -473,7 +475,7 @@ namespace util { * @return Iterator one past the last element. */ char *end() { - return _hex + sizeof(elem_type) * 2; + return _hex.data() + _hex.size(); } /** @@ -482,7 +484,7 @@ namespace util { * @return Iterator to the first element. */ const char *begin() const { - return _hex; + return _hex.data(); } /** @@ -491,7 +493,7 @@ namespace util { * @return Iterator one past the last element. */ const char *end() const { - return _hex + sizeof(elem_type) * 2; + return _hex.data() + _hex.size(); } /** @@ -500,7 +502,7 @@ namespace util { * @return Pointer to the first formatted hexadecimal character. */ const char *cbegin() const { - return _hex; + return _hex.data(); } /** @@ -509,7 +511,7 @@ namespace util { * @return Pointer one past the last formatted hexadecimal character. */ const char *cend() const { - return _hex + sizeof(elem_type) * 2; + return _hex.data() + _hex.size(); } /** @@ -573,7 +575,7 @@ namespace util { return hex; } - const char _bits[16] { + const std::array _bits { '0', '1', '2', @@ -629,7 +631,7 @@ namespace util { */ template T from_hex(const std::string_view &hex, bool rev = false) { - std::uint8_t buf[sizeof(T)]; + std::array buf; static char constexpr shift_bit = 'a' - 'A'; @@ -660,9 +662,9 @@ namespace util { return (std::uint8_t) (ch | (char) 32) - 'a' + (char) 10; }; - std::fill_n(buf + buf_size, padding, 0); + std::fill_n(buf.begin() + buf_size, padding, 0); - std::for_each_n(buf, buf_size, [&](auto &el) { + std::for_each_n(buf.begin(), buf_size, [&](auto &el) { while (!is_convertable(*data)) { --data; } @@ -680,7 +682,7 @@ namespace util { std::reverse(std::begin(buf), std::end(buf)); } - return *reinterpret_cast(buf); + return std::bit_cast(buf); } /** @@ -1469,7 +1471,7 @@ namespace util { _els {0} {}; /** - * @brief Construct an owning contiguous buffer. + * @brief Move an owning contiguous buffer and leave the source logically empty. * * @param o Source object used for comparison or assignment. */ @@ -1486,12 +1488,12 @@ namespace util { */ buffer_t(const buffer_t &o): _els {o._els}, - _buf {std::make_unique(_els)} { + _buf(_els) { std::copy(o.begin(), o.end(), begin()); } /** - * @brief Assign state from another instance while preserving ownership semantics. + * @brief Exchange allocations and logical counts with the source buffer. * * @param o Source object used for comparison or assignment. * @return Reference returned by the operator overload. @@ -1510,7 +1512,7 @@ namespace util { */ explicit buffer_t(size_t elements): _els {elements}, - _buf {std::make_unique(elements)} { + _buf(elements) { } /** @@ -1521,8 +1523,8 @@ namespace util { */ explicit buffer_t(size_t elements, const T &t): _els {elements}, - _buf {std::make_unique(elements)} { - std::fill_n(_buf.get(), elements, t); + _buf(elements) { + std::fill_n(_buf.data(), elements, t); } /** @@ -1569,7 +1571,7 @@ namespace util { * @return Iterator to the first element. */ T *begin() { - return _buf.get(); + return _buf.data(); } /** @@ -1578,7 +1580,7 @@ namespace util { * @return Iterator to the first element. */ const T *begin() const { - return _buf.get(); + return _buf.data(); } /** @@ -1587,7 +1589,7 @@ namespace util { * @return Iterator one past the last element. */ T *end() { - return _buf.get() + _els; + return _buf.data() + _els; } /** @@ -1596,12 +1598,12 @@ namespace util { * @return Iterator one past the last element. */ const T *end() const { - return _buf.get() + _els; + return _buf.data() + _els; } private: - size_t _els; - std::unique_ptr _buf; + size_t _els; ///< Logical element count, which may be smaller than the allocation. + std::vector _buf; ///< Owned allocation retained when the logical count changes. }; /** diff --git a/src/uuid.h b/src/uuid.h index 00e397e34..b1c4ed900 100644 --- a/src/uuid.h +++ b/src/uuid.h @@ -5,6 +5,7 @@ #pragma once // standard includes +#include #include /** @@ -15,10 +16,10 @@ namespace uuid_util { * @brief UUID value exposed through multiple integer views. */ union uuid_t { - std::uint8_t b8[16]; ///< UUID bytes. - std::uint16_t b16[8]; ///< UUID viewed as 16-bit words. - std::uint32_t b32[4]; ///< UUID viewed as 32-bit words. - std::uint64_t b64[2]; ///< UUID viewed as 64-bit words. + std::array b8; ///< UUID bytes. + std::array b16; ///< UUID viewed as 16-bit words. + std::array b32; ///< UUID viewed as 32-bit words. + std::array b64; ///< UUID viewed as 64-bit words. /** * @brief Generate a UUID value. @@ -66,7 +67,7 @@ namespace uuid_util { auto hex = util::hex(*this, true); auto hex_view = hex.to_string_view(); - std::string_view slices[] = { + std::array slices = { hex_view.substr(0, 8), hex_view.substr(8, 4), hex_view.substr(12, 4), diff --git a/src/video.cpp b/src/video.cpp index 6d72dea79..c90847ecb 100644 --- a/src/video.cpp +++ b/src/video.cpp @@ -262,8 +262,8 @@ namespace video { // Perform color conversion and scaling to the final size auto status = sws_scale_frame(sws.get(), requires_padding ? sws_output_frame.get() : sw_frame.get(), sws_input_frame.get()); if (status < 0) { - char string[AV_ERROR_MAX_STRING_SIZE]; - BOOST_LOG(error) << "Couldn't scale frame: "sv << av_make_error_string(string, AV_ERROR_MAX_STRING_SIZE, status); + std::array string; + BOOST_LOG(error) << "Couldn't scale frame: "sv << av_make_error_string(string.data(), AV_ERROR_MAX_STRING_SIZE, status); return -1; } @@ -288,8 +288,8 @@ namespace video { if (frame->hw_frames_ctx) { auto status = av_hwframe_transfer_data(frame, sw_frame.get(), 0); if (status < 0) { - char string[AV_ERROR_MAX_STRING_SIZE]; - BOOST_LOG(error) << "Failed to transfer image data to hardware frame: "sv << av_make_error_string(string, AV_ERROR_MAX_STRING_SIZE, status); + std::array string; + BOOST_LOG(error) << "Failed to transfer image data to hardware frame: "sv << av_make_error_string(string.data(), AV_ERROR_MAX_STRING_SIZE, status); return -1; } } @@ -390,15 +390,15 @@ namespace video { auto status = av_opt_set_dict(sws.get(), &options); av_dict_free(&options); if (status < 0) { - char string[AV_ERROR_MAX_STRING_SIZE]; - BOOST_LOG(error) << "Failed to set SWS options: "sv << av_make_error_string(string, AV_ERROR_MAX_STRING_SIZE, status); + std::array string; + BOOST_LOG(error) << "Failed to set SWS options: "sv << av_make_error_string(string.data(), AV_ERROR_MAX_STRING_SIZE, status); return -1; } status = sws_init_context(sws.get(), nullptr, nullptr); if (status < 0) { - char string[AV_ERROR_MAX_STRING_SIZE]; - BOOST_LOG(error) << "Failed to initialize SWS: "sv << av_make_error_string(string, AV_ERROR_MAX_STRING_SIZE, status); + std::array string; + BOOST_LOG(error) << "Failed to initialize SWS: "sv << av_make_error_string(string.data(), AV_ERROR_MAX_STRING_SIZE, status); return -1; } @@ -1837,8 +1837,8 @@ namespace video { // send the frame to the encoder auto ret = avcodec_send_frame(ctx.get(), frame); if (ret < 0) { - char err_str[AV_ERROR_MAX_STRING_SIZE] {0}; - BOOST_LOG(error) << "Could not send a frame for encoding: "sv << av_make_error_string(err_str, AV_ERROR_MAX_STRING_SIZE, ret); + std::array err_str {0}; + BOOST_LOG(error) << "Could not send a frame for encoding: "sv << av_make_error_string(err_str.data(), AV_ERROR_MAX_STRING_SIZE, ret); return -1; } @@ -2114,8 +2114,8 @@ namespace video { auto err = av_hwdevice_ctx_create_derived(&derived_context, platform_formats->avcodec_derived_dev_type, encoding_stream_context.get(), 0); if (err) { - char err_str[AV_ERROR_MAX_STRING_SIZE] {0}; - BOOST_LOG(error) << "Failed to derive device context: "sv << av_make_error_string(err_str, AV_ERROR_MAX_STRING_SIZE, err); + std::array err_str {0}; + BOOST_LOG(error) << "Failed to derive device context: "sv << av_make_error_string(err_str.data(), AV_ERROR_MAX_STRING_SIZE, err); return nullptr; } @@ -2251,19 +2251,19 @@ namespace video { encode_device->init_codec_options(ctx.get(), &options); if (auto status = avcodec_open2(ctx.get(), codec, &options)) { - char err_str[AV_ERROR_MAX_STRING_SIZE] {0}; + std::array err_str {0}; if (!video_format.fallback_options.empty() && retries == 0) { BOOST_LOG(info) << "Retrying with fallback configuration options for ["sv << video_format.name << "] after error: "sv - << av_make_error_string(err_str, AV_ERROR_MAX_STRING_SIZE, status); + << av_make_error_string(err_str.data(), AV_ERROR_MAX_STRING_SIZE, status); continue; } else { BOOST_LOG(error) << "Could not open codec ["sv << video_format.name << "]: "sv - << av_make_error_string(err_str, AV_ERROR_MAX_STRING_SIZE, status); + << av_make_error_string(err_str.data(), AV_ERROR_MAX_STRING_SIZE, status); return nullptr; } @@ -3528,8 +3528,8 @@ namespace video { auto status = av_hwdevice_ctx_create(&hw_device_buf, AV_HWDEVICE_TYPE_VAAPI, render_device.empty() ? nullptr : render_device.c_str(), nullptr, 0); if (status < 0) { - char string[AV_ERROR_MAX_STRING_SIZE]; - BOOST_LOG(error) << "Failed to create a VAAPI device: "sv << av_make_error_string(string, AV_ERROR_MAX_STRING_SIZE, status); + std::array string; + BOOST_LOG(error) << "Failed to create a VAAPI device: "sv << av_make_error_string(string.data(), AV_ERROR_MAX_STRING_SIZE, status); return -1; } @@ -3581,8 +3581,8 @@ namespace video { auto status = av_hwdevice_ctx_create(&hw_device_buf, AV_HWDEVICE_TYPE_CUDA, nullptr, nullptr, 1 /* AV_CUDA_USE_PRIMARY_CONTEXT */); if (status < 0) { - char string[AV_ERROR_MAX_STRING_SIZE]; - BOOST_LOG(error) << "Failed to create a CUDA device: "sv << av_make_error_string(string, AV_ERROR_MAX_STRING_SIZE, status); + std::array string; + BOOST_LOG(error) << "Failed to create a CUDA device: "sv << av_make_error_string(string.data(), AV_ERROR_MAX_STRING_SIZE, status); return -1; } @@ -3597,8 +3597,8 @@ namespace video { auto status = av_hwdevice_ctx_create(&hw_device_buf, AV_HWDEVICE_TYPE_VIDEOTOOLBOX, nullptr, nullptr, 0); if (status < 0) { - char string[AV_ERROR_MAX_STRING_SIZE]; - BOOST_LOG(error) << "Failed to create a VideoToolbox device: "sv << av_make_error_string(string, AV_ERROR_MAX_STRING_SIZE, status); + std::array string; + BOOST_LOG(error) << "Failed to create a VideoToolbox device: "sv << av_make_error_string(string.data(), AV_ERROR_MAX_STRING_SIZE, status); return -1; } @@ -3635,8 +3635,8 @@ namespace video { auto err = av_hwdevice_ctx_init(ctx_buf.get()); if (err) { - char err_str[AV_ERROR_MAX_STRING_SIZE] {0}; - BOOST_LOG(error) << "Failed to create FFMpeg hardware device context: "sv << av_make_error_string(err_str, AV_ERROR_MAX_STRING_SIZE, err); + std::array err_str {0}; + BOOST_LOG(error) << "Failed to create FFMpeg hardware device context: "sv << av_make_error_string(err_str.data(), AV_ERROR_MAX_STRING_SIZE, err); return err; } diff --git a/src/video_colorspace.cpp b/src/video_colorspace.cpp index 115347558..a8f23f482 100644 --- a/src/video_colorspace.cpp +++ b/src/video_colorspace.cpp @@ -5,6 +5,8 @@ // this include #include "video_colorspace.h" +#include + // local includes #include "logging.h" #include "video.h" @@ -233,7 +235,7 @@ namespace video { return color_vectors; }; - static constexpr color_t colors[] = { + static constexpr std::array colors = { generate_color_vectors({rec601, false, 8}, false), generate_color_vectors({rec601, true, 8}, false), generate_color_vectors({rec601, false, 10}, false), diff --git a/src/video_colorspace.h b/src/video_colorspace.h index 7d515fea9..0d047d145 100644 --- a/src/video_colorspace.h +++ b/src/video_colorspace.h @@ -4,6 +4,8 @@ */ #pragma once +#include + extern "C" { #include } @@ -80,11 +82,11 @@ namespace video { * @brief Pair of Sunshine and AVCodec colorimetry descriptions. */ struct alignas(16) color_t { - float color_vec_y[4]; ///< Color vec y. - float color_vec_u[4]; ///< Color vec u. - float color_vec_v[4]; ///< Color vec v. - float range_y[2]; ///< Range y. - float range_uv[2]; ///< Range uv. + std::array color_vec_y; ///< Color vec y. + std::array color_vec_u; ///< Color vec u. + std::array color_vec_v; ///< Color vec v. + std::array range_y; ///< Range y. + std::array range_uv; ///< Range uv. }; /** diff --git a/tests/unit/platform/test_common.cpp b/tests/unit/platform/test_common.cpp index 90055f933..d7f63f117 100644 --- a/tests/unit/platform/test_common.cpp +++ b/tests/unit/platform/test_common.cpp @@ -6,8 +6,18 @@ // test includes #include "../../tests_common.h" +// standard includes +#include +#include +#include +#include +#include + // lib includes +#include +#include #include +#include // local includes #include @@ -16,3 +26,94 @@ TEST(HostnameTests, TestAsioEquality) { // These should be equivalent on all platforms for ASCII hostnames ASSERT_EQ(platf::get_host_name(), boost::asio::ip::host_name()); } + +TEST(SocketAddressTest, FormatsConstIpv4AndIpv6AddressesAndPreservesNetworkOrderPorts) { + for (const auto *text : {"192.0.2.17", "2001:db8::17"}) { + const boost::asio::ip::udp::endpoint endpoint {boost::asio::ip::make_address(text), 4321}; + EXPECT_EQ(platf::from_sockaddr(endpoint.data()), text); + const auto [port, address] = platf::from_sockaddr_ex(endpoint.data()); + EXPECT_EQ(port, htons(4321)); + EXPECT_EQ(address, text); + } +} + +TEST(SocketAddressTest, UnsupportedAddressFamiliesProduceEmptyAddressesAndZeroPorts) { + const sockaddr address {}; + EXPECT_TRUE(platf::from_sockaddr(&address).empty()); + EXPECT_EQ(platf::from_sockaddr_ex(&address), (std::pair {0, {}})); +} + +#if defined(_WIN32) || defined(__linux__) || defined(__FreeBSD__) +/** + * @brief Exercise source-address control messages on bound UDP sockets with optional headers. + */ +class UdpSourceAddressTest: public testing::TestWithParam> {}; + +TEST_P(UdpSourceAddressTest, SendsTheExpectedDatagramFromTheRequestedAddress) { + const auto [ipv6, batched, with_header] = GetParam(); + auto address = boost::asio::ip::make_address(ipv6 ? "::1" : "127.0.0.1"); + boost::asio::io_context context; + boost::asio::ip::udp::socket receiver(context, {address, 0}); + // FreeBSD requires a bound port before accepting IP_SENDSRCADDR. + boost::asio::ip::udp::socket sender(context, {receiver.local_endpoint().protocol(), 0}); + const auto port = receiver.local_endpoint().port(); + const auto native_socket = static_cast(sender.native_handle()); + const std::string_view header = "header"; + const std::string_view payload = "payload"; + if (batched) { + const std::string_view headers = "headerheader"; + const std::string_view payloads = "payloadpayload"; + std::vector buffers {{payloads.data(), payloads.size()}}; + platf::batched_send_info_t batch_info { + with_header ? headers.data() : nullptr, + with_header ? header.size() : 0, + buffers, + payload.size(), + 0, + 2, + native_socket, + address, + port, + address + }; + ASSERT_TRUE(platf::send_batch(batch_info)); + } else { + platf::send_info_t packet_info { + with_header ? header.data() : nullptr, + with_header ? header.size() : 0, + payload.data(), + payload.size(), + native_socket, + address, + port, + address + }; + ASSERT_TRUE(platf::send(packet_info)); + } + + for (auto packet = 0; packet < (batched ? 2 : 1); ++packet) { + std::array bytes; + boost::asio::ip::udp::endpoint peer; + boost::system::error_code receive_error; + std::size_t received = 0; + bool completed = false; + receiver.async_receive_from(boost::asio::buffer(bytes), peer, [&receive_error, &received, &completed](const auto &result, std::size_t size) { + receive_error = result; + received = size; + completed = true; + }); + context.restart(); + context.run_for(std::chrono::seconds {2}); + ASSERT_TRUE(completed); + ASSERT_FALSE(receive_error) << receive_error.message(); + EXPECT_EQ(peer.address(), address); + EXPECT_EQ(std::string_view(bytes.data(), received), with_header ? "headerpayload" : "payload"); + } +} + +INSTANTIATE_TEST_SUITE_P( + Loopback, + UdpSourceAddressTest, + testing::Combine(testing::Bool(), testing::Bool(), testing::Bool()) +); +#endif diff --git a/tests/unit/test_audio.cpp b/tests/unit/test_audio.cpp index c1f1a32bf..851f250d4 100644 --- a/tests/unit/test_audio.cpp +++ b/tests/unit/test_audio.cpp @@ -11,6 +11,21 @@ using namespace audio; +TEST(AudioLayoutTest, CustomMappingRemainsContiguousAndUsesAllEightChannels) { + const stream_params_t params {8, 6, 2, {0, 1, 4, 5, 2, 3, 6, 7}}; + auto copy = params; + EXPECT_EQ(copy.channelCount, 8); + EXPECT_EQ(copy.streams, 6); + EXPECT_EQ(copy.coupledStreams, 2); + EXPECT_EQ(copy.mapping.size(), 8U); + EXPECT_EQ(copy.mapping.back(), 7); + EXPECT_EQ(copy.mapping.data() + 7, ©.mapping[7]); + copy.mapping[0] = 7; + EXPECT_EQ(params.mapping[0], 0); + EXPECT_EQ(stream_configs.size(), MAX_STREAM_CONFIG); + EXPECT_EQ(stream_configs[HIGH_SURROUND71].channelCount, 8); +} + struct AudioTest: PlatformTestSuite, testing::WithParamInterface, config_t>> { void SetUp() override { BaseTest::SetUp(); diff --git a/tests/unit/test_stream.cpp b/tests/unit/test_stream.cpp index da89e28ec..e94ceb052 100644 --- a/tests/unit/test_stream.cpp +++ b/tests/unit/test_stream.cpp @@ -25,25 +25,25 @@ namespace stream { } // namespace stream TEST(ConcatAndInsertTests, ConcatNoInsertionTest) { - char b1[] = {'a', 'b'}; - char b2[] = {'c', 'd', 'e'}; - auto res = stream::concat_and_insert(0, 2, std::string_view {b1, sizeof(b1)}, std::string_view {b2, sizeof(b2)}); + std::array b1 = {'a', 'b'}; + std::array b2 = {'c', 'd', 'e'}; + auto res = stream::concat_and_insert(0, 2, std::string_view {b1.data(), b1.size()}, std::string_view {b2.data(), b2.size()}); auto expected = std::vector {'a', 'b', 'c', 'd', 'e'}; ASSERT_EQ(res, expected); } TEST(ConcatAndInsertTests, ConcatLargeStrideTest) { - char b1[] = {'a', 'b'}; - char b2[] = {'c', 'd', 'e'}; - auto res = stream::concat_and_insert(1, sizeof(b1) + sizeof(b2) + 1, std::string_view {b1, sizeof(b1)}, std::string_view {b2, sizeof(b2)}); + std::array b1 = {'a', 'b'}; + std::array b2 = {'c', 'd', 'e'}; + auto res = stream::concat_and_insert(1, b1.size() + b2.size() + 1, std::string_view {b1.data(), b1.size()}, std::string_view {b2.data(), b2.size()}); auto expected = std::vector {0, 'a', 'b', 'c', 'd', 'e'}; ASSERT_EQ(res, expected); } TEST(ConcatAndInsertTests, ConcatSmallStrideTest) { - char b1[] = {'a', 'b'}; - char b2[] = {'c', 'd', 'e'}; - auto res = stream::concat_and_insert(1, 1, std::string_view {b1, sizeof(b1)}, std::string_view {b2, sizeof(b2)}); + std::array b1 = {'a', 'b'}; + std::array b2 = {'c', 'd', 'e'}; + auto res = stream::concat_and_insert(1, 1, std::string_view {b1.data(), b1.size()}, std::string_view {b2.data(), b2.size()}); auto expected = std::vector {0, 'a', 0, 'b', 0, 'c', 0, 'd', 0, 'e'}; ASSERT_EQ(res, expected); } diff --git a/tests/unit/test_utility.cpp b/tests/unit/test_utility.cpp index 0de618330..4a4422c64 100644 --- a/tests/unit/test_utility.cpp +++ b/tests/unit/test_utility.cpp @@ -255,6 +255,89 @@ TEST(UtilityBufferTests, CopyConstruction) { EXPECT_EQ(buf1[0], 55); } +TEST(UtilityBufferTests, SizeConstructionValueInitializesEveryElement) { + const util::buffer_t buf(4); + EXPECT_EQ(buf.end() - buf.begin(), 4); + EXPECT_TRUE(std::ranges::all_of(buf, [](int value) { + return value == 0; + })); +} + +TEST(UtilityBufferTests, LogicalResizeRetainsAllocationAndHiddenElements) { + util::buffer_t buf(4, 7); + auto *allocation = buf.begin(); + buf[3] = 99; + buf.fake_resize(2); + EXPECT_EQ(buf.size(), 2U); + EXPECT_EQ(buf.begin(), allocation); + EXPECT_EQ(buf.end(), allocation + 2); + + const util::buffer_t copy(buf); + EXPECT_EQ(copy.size(), 2U); + EXPECT_NE(copy.begin(), allocation); + EXPECT_EQ(copy[0], 7); + EXPECT_EQ(copy[1], 7); + buf[0] = 10; + EXPECT_EQ(copy[0], 7); + + buf.fake_resize(0); + EXPECT_EQ(buf.begin(), buf.end()); + buf.fake_resize(4); + EXPECT_EQ(buf.begin(), allocation); + EXPECT_EQ(buf[3], 99); +} + +TEST(UtilityBufferTests, MoveConstructionTransfersAllocationAndEmptiesSource) { + util::buffer_t source(4, 9); + source.fake_resize(2); + auto *allocation = source.begin(); + const util::buffer_t destination(std::move(source)); + EXPECT_EQ(destination.size(), 2U); + EXPECT_EQ(destination.begin(), allocation); + EXPECT_EQ(destination[1], 9); + EXPECT_EQ(source.size(), 0U); // NOSONAR(cpp:S5272): buffer_t specifies a zero logical count after move construction. + EXPECT_EQ(source.begin(), source.end()); +} + +TEST(UtilityBufferTests, MoveAssignmentExchangesBothAllocationsAndLogicalSizes) { + util::buffer_t source(4, 9); + source.fake_resize(2); + util::buffer_t destination(3, 7); + auto *source_allocation = source.begin(); + auto *destination_allocation = destination.begin(); + + EXPECT_EQ(&(destination = std::move(source)), &destination); + EXPECT_EQ(destination.size(), 2U); + EXPECT_EQ(destination.begin(), source_allocation); + EXPECT_EQ(destination[1], 9); + EXPECT_EQ(source.size(), 3U); // NOSONAR(cpp:S5272): buffer_t move assignment exchanges both allocations and logical counts. + EXPECT_EQ(source.begin(), destination_allocation); + EXPECT_EQ(source[2], 7); +} + +TEST(UtilityHexTests, IteratorsAndViewsExposeExactlyTheFormattedBytes) { + auto hex = util::hex(std::uint16_t {0xABCD}); + EXPECT_EQ(hex.end() - hex.begin(), 4); + EXPECT_EQ(std::string(hex.begin(), hex.end()), "ABCD"); + *hex.begin() = '0'; + const auto &constant_hex = hex; + EXPECT_EQ(constant_hex.end() - constant_hex.begin(), 4); + EXPECT_EQ(constant_hex.cbegin(), constant_hex.begin()); + EXPECT_EQ(constant_hex.cend(), constant_hex.end()); + EXPECT_EQ(constant_hex.to_string_view(), "0BCD"); + EXPECT_EQ(constant_hex.to_string(), "0BCD"); +} + +TEST(UtilityFromHexTests, ShortInputPadsUnusedBytesWithZeros) { + EXPECT_EQ(util::from_hex("ABCD"), util::endian::little(std::uint64_t {0xABCD})); + EXPECT_EQ(util::from_hex("ABCD", true), util::endian::big(std::uint64_t {0xABCD})); +} + +TEST(UtilityFromHexTests, DecodesIntoAByteArrayWithoutPointerTypePunning) { + const auto bytes = util::from_hex>("12:34:56:78", true); + EXPECT_EQ(bytes, (std::array {0x12, 0x34, 0x56, 0x78})); +} + TEST(UtilityAppendStructTests, AppendsDataCorrectly) { struct test_struct_t { std::uint8_t a; diff --git a/tests/unit/test_uuid.cpp b/tests/unit/test_uuid.cpp new file mode 100644 index 000000000..c86c80195 --- /dev/null +++ b/tests/unit/test_uuid.cpp @@ -0,0 +1,69 @@ +/** + * @file tests/unit/test_uuid.cpp + * @brief Tests for UUID byte layout, generation, formatting, and ordering. + */ + +// test includes +#include "../tests_common.h" + +// standard includes +#include +#include +#include +#include +#include + +// local includes +#include +#include + +TEST(UuidTest, PreservesNativeLayoutAndCanonicalFormatting) { + static_assert(sizeof(uuid_util::uuid_t) == 16); + static_assert(alignof(uuid_util::uuid_t) == alignof(std::uint64_t)); + static_assert(std::is_trivially_copyable_v); + const uuid_util::uuid_t uuid {.b8 = {0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF}}; + EXPECT_EQ(uuid.string(), "00112233-4455-6677-8899-AABBCCDDEEFF"); // NOSONAR(cpp:S6232): Calling a union member function does not access an inactive data member. +} + +TEST(UuidTest, GenerationPreservesDrawOrderAndMasks) { + std::default_random_engine engine {42}; // NOSONAR(cpp:S2245): Deterministic regression fixture; no security-sensitive values are generated. + auto expected_engine = engine; // NOSONAR(cpp:S2245): Copy the deterministic fixture to verify draw order independently. + std::uniform_int_distribution distribution(0, 255); + std::array expected; + for (auto &byte : expected) { + byte = distribution(expected_engine); + } + expected[7] = std::to_integer(std::byte {expected[7]} & std::byte {0b00101111}); + expected[9] = std::to_integer(std::byte {expected[9]} & std::byte {0b10011111}); + + const auto uuid = uuid_util::uuid_t::generate(engine); + EXPECT_EQ(uuid.b8, expected); + EXPECT_EQ(engine, expected_engine); + EXPECT_EQ(uuid_util::uuid_t::generate().string().size(), 36U); +} + +TEST(UuidTest, ComparesBothWordsInTheirEstablishedOrder) { + const uuid_util::uuid_t base {.b64 = {2, 3}}; + const uuid_util::uuid_t equal {.b64 = {2, 3}}; + const uuid_util::uuid_t lower_first {.b64 = {1, 9}}; + const uuid_util::uuid_t higher_first {.b64 = {3, 1}}; + const uuid_util::uuid_t lower_second {.b64 = {2, 2}}; + const uuid_util::uuid_t higher_second {.b64 = {2, 4}}; + EXPECT_EQ(base, equal); + EXPECT_FALSE(base < equal); + EXPECT_FALSE(base > equal); + for (const auto &lower : {lower_first, lower_second}) { + EXPECT_FALSE(base == lower); + EXPECT_TRUE(lower < base); + EXPECT_TRUE(base > lower); + EXPECT_FALSE(base < lower); + EXPECT_FALSE(lower > base); + } + for (const auto &higher : {higher_first, higher_second}) { + EXPECT_FALSE(base == higher); + EXPECT_TRUE(base < higher); + EXPECT_TRUE(higher > base); + EXPECT_FALSE(higher < base); + EXPECT_FALSE(base > higher); + } +} diff --git a/tests/unit/test_video_colorspace.cpp b/tests/unit/test_video_colorspace.cpp index 6a3b4efd8..1b34eee96 100644 --- a/tests/unit/test_video_colorspace.cpp +++ b/tests/unit/test_video_colorspace.cpp @@ -8,12 +8,31 @@ // standard includes #include +#include #include +#include #include // local includes #include +TEST(VideoColorspaceTest, PreservesShaderConstantBufferLayout) { + static_assert(std::is_standard_layout_v); + static_assert(std::is_trivially_copyable_v); + static_assert(sizeof(video::color_t) == 64); + static_assert(alignof(video::color_t) == 16); + static_assert(offsetof(video::color_t, color_vec_y) == 0); + static_assert(offsetof(video::color_t, color_vec_u) == 16); + static_assert(offsetof(video::color_t, color_vec_v) == 32); + static_assert(offsetof(video::color_t, range_y) == 48); + static_assert(offsetof(video::color_t, range_uv) == 56); + + const auto *vectors = video::color_vectors_from_colorspace({video::colorspace_e::rec709, false, 8}, false); + ASSERT_NE(vectors, nullptr); + EXPECT_EQ(vectors->range_y, (std::array {1.0f, 0.0f})); + EXPECT_EQ(vectors->range_uv, (std::array {1.0f, 0.0f})); +} + TEST(VideoColorspaceTest, DescribesEveryColorspaceAndUnknownValues) { using enum video::colorspace_e; const std::array cases { diff --git a/tools/audio.cpp b/tools/audio.cpp index 3678a3087..0b8ca3b65 100644 --- a/tools/audio.cpp +++ b/tools/audio.cpp @@ -5,6 +5,7 @@ #define INITGUID // platform includes +#include #include #include #include @@ -59,51 +60,72 @@ namespace audio { PROPVARIANT prop; }; + /** + * @brief Speaker layout available for audio device probing. + */ struct format_t { - std::string_view name; - int channels; - int channel_mask; - } formats[] { - {"Mono"sv, - 1, - SPEAKER_FRONT_CENTER}, - {"Stereo"sv, - 2, - SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT}, - {"Quadraphonic"sv, - 4, - SPEAKER_FRONT_LEFT | - SPEAKER_FRONT_RIGHT | - SPEAKER_BACK_LEFT | - SPEAKER_BACK_RIGHT}, - {"Surround 5.1 (Side)"sv, - 6, - SPEAKER_FRONT_LEFT | - SPEAKER_FRONT_RIGHT | - SPEAKER_FRONT_CENTER | - SPEAKER_LOW_FREQUENCY | - SPEAKER_SIDE_LEFT | - SPEAKER_SIDE_RIGHT}, - {"Surround 5.1 (Back)"sv, - 6, - SPEAKER_FRONT_LEFT | - SPEAKER_FRONT_RIGHT | - SPEAKER_FRONT_CENTER | - SPEAKER_LOW_FREQUENCY | - SPEAKER_BACK_LEFT | - SPEAKER_BACK_RIGHT}, - {"Surround 7.1"sv, - 8, - SPEAKER_FRONT_LEFT | - SPEAKER_FRONT_RIGHT | - SPEAKER_FRONT_CENTER | - SPEAKER_LOW_FREQUENCY | - SPEAKER_BACK_LEFT | - SPEAKER_BACK_RIGHT | - SPEAKER_SIDE_LEFT | - SPEAKER_SIDE_RIGHT} + std::string_view name; ///< Display name of the speaker layout. + int channels; ///< Number of channels in the layout. + int channel_mask; ///< Windows speaker-position mask. }; + /** + * @brief Speaker layouts tested when probing an audio device. + */ + const std::array formats {{ + { + "Mono"sv, + 1, + SPEAKER_FRONT_CENTER, + }, + { + "Stereo"sv, + 2, + SPEAKER_FRONT_LEFT | + SPEAKER_FRONT_RIGHT, + }, + { + "Quadraphonic"sv, + 4, + SPEAKER_FRONT_LEFT | + SPEAKER_FRONT_RIGHT | + SPEAKER_BACK_LEFT | + SPEAKER_BACK_RIGHT, + }, + { + "Surround 5.1 (Side)"sv, + 6, + SPEAKER_FRONT_LEFT | + SPEAKER_FRONT_RIGHT | + SPEAKER_FRONT_CENTER | + SPEAKER_LOW_FREQUENCY | + SPEAKER_SIDE_LEFT | + SPEAKER_SIDE_RIGHT, + }, + { + "Surround 5.1 (Back)"sv, + 6, + SPEAKER_FRONT_LEFT | + SPEAKER_FRONT_RIGHT | + SPEAKER_FRONT_CENTER | + SPEAKER_LOW_FREQUENCY | + SPEAKER_BACK_LEFT | + SPEAKER_BACK_RIGHT, + }, + { + "Surround 7.1"sv, + 8, + SPEAKER_FRONT_LEFT | + SPEAKER_FRONT_RIGHT | + SPEAKER_FRONT_CENTER | + SPEAKER_LOW_FREQUENCY | + SPEAKER_BACK_LEFT | + SPEAKER_BACK_RIGHT | + SPEAKER_SIDE_LEFT | + SPEAKER_SIDE_RIGHT, + }, + }}; + void set_wave_format(audio::wave_format_t &wave_format, const format_t &format) { wave_format->nChannels = format.channels; wave_format->nBlockAlign = wave_format->nChannels * wave_format->wBitsPerSample / 8; diff --git a/tools/sunshinesvc.cpp b/tools/sunshinesvc.cpp index e23ecf9ad..9c2fef858 100644 --- a/tools/sunshinesvc.cpp +++ b/tools/sunshinesvc.cpp @@ -3,6 +3,7 @@ * @brief Handles launching Sunshine.exe into user sessions as SYSTEM */ #define WIN32_LEAN_AND_MEAN +#include #include #include #include @@ -120,29 +121,29 @@ HANDLE DuplicateTokenForSession(DWORD console_session_id) { } HANDLE OpenLogFileHandle() { - WCHAR log_file_name[MAX_PATH]; + std::array log_file_name; // Create sunshine.log in the Temp folder (usually %SYSTEMROOT%\Temp) - GetTempPathW(_countof(log_file_name), log_file_name); - wcscat_s(log_file_name, L"sunshine.log"); + GetTempPathW(log_file_name.size(), log_file_name.data()); + wcscat_s(log_file_name.data(), log_file_name.size(), L"sunshine.log"); // Preserve previous service output before opening the current log. - logging::rotate_log_file(log_file_name); + logging::rotate_log_file(log_file_name.data()); // The file handle must be inheritable for our child process to use it SECURITY_ATTRIBUTES security_attributes = {sizeof(security_attributes), nullptr, TRUE}; // Create the current sunshine.log - return CreateFileW(log_file_name, GENERIC_WRITE, FILE_SHARE_READ, &security_attributes, CREATE_ALWAYS, 0, nullptr); + return CreateFileW(log_file_name.data(), GENERIC_WRITE, FILE_SHARE_READ, &security_attributes, CREATE_ALWAYS, 0, nullptr); } bool RunTerminationHelper(HANDLE console_token, DWORD pid) { - WCHAR module_path[MAX_PATH]; - GetModuleFileNameW(nullptr, module_path, _countof(module_path)); + std::array module_path; + GetModuleFileNameW(nullptr, module_path.data(), module_path.size()); std::wstring command; command += L'"'; - command += module_path; + command += module_path.data(); command += L'"'; command += std::format(L" --terminate {}", pid); @@ -153,7 +154,7 @@ bool RunTerminationHelper(HANDLE console_token, DWORD pid) { // Execute ourselves as a detached process in the user session with the --terminate argument. // This will allow us to attach to Sunshine's console and send it a Ctrl-C event. PROCESS_INFORMATION process_info; - if (!CreateProcessAsUserW(console_token, module_path, (LPWSTR) command.c_str(), nullptr, nullptr, FALSE, CREATE_UNICODE_ENVIRONMENT | DETACHED_PROCESS, nullptr, nullptr, &startup_info, &process_info)) { + if (!CreateProcessAsUserW(console_token, module_path.data(), command.data(), nullptr, nullptr, FALSE, CREATE_UNICODE_ENVIRONMENT | DETACHED_PROCESS, nullptr, nullptr, &startup_info, &process_info)) { return false; } @@ -172,6 +173,18 @@ bool RunTerminationHelper(HANDLE console_token, DWORD pid) { return exit_code == 0; } +/** + * @brief Terminate Sunshine gracefully, forcing termination if it does not exit within 20 seconds. + * + * @param console_token Token for the console session running Sunshine. + * @param process_info Handles and identifier of the running Sunshine process. + */ +void TerminateSunshine(HANDLE console_token, const PROCESS_INFORMATION &process_info) { + if (!RunTerminationHelper(console_token, process_info.dwProcessId) || WaitForSingleObject(process_info.hProcess, 20000) != WAIT_OBJECT_0) { + TerminateProcess(process_info.hProcess, ERROR_PROCESS_ABORTED); + } +} + VOID WINAPI ServiceMain(DWORD dwArgc, LPTSTR *lpszArgv) { service_status_handle = RegisterServiceCtrlHandlerEx(SERVICE_NAME, HandlerEx, nullptr); if (service_status_handle == nullptr) { @@ -279,8 +292,8 @@ VOID WINAPI ServiceMain(DWORD dwArgc, LPTSTR *lpszArgv) { bool still_running; do { // Wait for the stop event to be set, Sunshine.exe to terminate, or the console session to change - const HANDLE wait_objects[] = {stop_event, process_info.hProcess, session_change_event}; - switch (WaitForMultipleObjects(_countof(wait_objects), wait_objects, FALSE, INFINITE)) { + const std::array wait_objects = {stop_event, process_info.hProcess, session_change_event}; + switch (WaitForMultipleObjects(wait_objects.size(), wait_objects.data(), FALSE, INFINITE)) { case WAIT_OBJECT_0 + 2: if (WTSGetActiveConsoleSessionId() == console_session_id) { // The active console session didn't actually change. Let Sunshine keep running. @@ -290,11 +303,7 @@ VOID WINAPI ServiceMain(DWORD dwArgc, LPTSTR *lpszArgv) { // Fall-through to terminate Sunshine.exe and start it again. case WAIT_OBJECT_0: // The service is shutting down, so try to gracefully terminate Sunshine.exe. - // If it doesn't terminate in 20 seconds, we will forcefully terminate it. - if (!RunTerminationHelper(console_token, process_info.dwProcessId) || WaitForSingleObject(process_info.hProcess, 20000) != WAIT_OBJECT_0) { - // If it won't terminate gracefully, kill it now - TerminateProcess(process_info.hProcess, ERROR_PROCESS_ABORTED); - } + TerminateSunshine(console_token, process_info); still_running = false; break; @@ -310,6 +319,12 @@ VOID WINAPI ServiceMain(DWORD dwArgc, LPTSTR *lpszArgv) { still_running = false; break; } + default: + // Stop the service rather than orphaning Sunshine after an unexpected wait failure. + SetEvent(stop_event); + TerminateSunshine(console_token, process_info); + still_running = false; + break; } } while (still_running); @@ -343,11 +358,6 @@ int DoGracefulTermination(DWORD pid) { } int main(int argc, char *argv[]) { - static const SERVICE_TABLE_ENTRY service_table[] = { - {(LPSTR) SERVICE_NAME, ServiceMain}, - {nullptr, nullptr} - }; - // Check if this is a reinvocation of ourselves to send Ctrl-C to Sunshine.exe if (argc == 3 && strcmp(argv[1], "--terminate") == 0) { return DoGracefulTermination(atol(argv[2])); @@ -356,16 +366,20 @@ int main(int argc, char *argv[]) { // By default, services have their current directory set to %SYSTEMROOT%\System32. // We want to use the directory where Sunshine.exe is located instead of system32. // This requires stripping off 2 path components: the file name and the last folder - WCHAR module_path[MAX_PATH]; - GetModuleFileNameW(nullptr, module_path, _countof(module_path)); + std::array module_path; + GetModuleFileNameW(nullptr, module_path.data(), module_path.size()); for (auto i = 0; i < 2; i++) { - auto last_sep = wcsrchr(module_path, '\\'); + auto last_sep = wcsrchr(module_path.data(), '\\'); if (last_sep) { *last_sep = 0; } } - SetCurrentDirectoryW(module_path); + if (!SetCurrentDirectoryW(module_path.data())) { + return GetLastError(); + } // Trigger our ServiceMain() - return StartServiceCtrlDispatcher(service_table); + std::string service_name {SERVICE_NAME}; + const std::array service_table = {{{service_name.data(), ServiceMain}, {nullptr, nullptr}}}; + return StartServiceCtrlDispatcher(service_table.data()); }