diff --git a/CMakeLists.txt b/CMakeLists.txt index 1be0a7e6..2ff36abe 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -67,13 +67,15 @@ if (WIVRN_BUILD_SERVER) if (WIVRN_USE_VAAPI STREQUAL "AUTO") pkg_check_modules(LIBAV IMPORTED_TARGET libavcodec libavutil libswscale libavfilter) - if (LIBAV_FOUND) + pkg_check_modules(LIBDRM IMPORTED_TARGET libdrm) + if (LIBAV_FOUND AND LIBDRM_FOUND) set(WIVRN_USE_VAAPI ON) else() set(WIVRN_USE_VAAPI OFF) endif() elseif (WIVRN_USE_VAAPI) pkg_check_modules(LIBAV REQUIRED IMPORTED_TARGET libavcodec libavutil libswscale libavfilter) + pkg_check_modules(LIBDRM REQUIRED IMPORTED_TARGET libdrm) endif() if (WIVRN_USE_X264 STREQUAL "AUTO") diff --git a/common/CMakeLists.txt b/common/CMakeLists.txt index 175e2663..e1c1cc69 100644 --- a/common/CMakeLists.txt +++ b/common/CMakeLists.txt @@ -48,12 +48,13 @@ if(ANDROID) file(ARCHIVE_EXTRACT INPUT ${CMAKE_BINARY_DIR}/vulkan-sdk-${VULKAN_VERSION}.tar.gz DESTINATION ${CMAKE_BINARY_DIR}) target_include_directories(wivrn-common PUBLIC ${CMAKE_BINARY_DIR}/Vulkan-Headers-vulkan-sdk-${VULKAN_VERSION}/include) + target_compile_definitions(wivrn-common PUBLIC VMA_VULKAN_VERSION=1001000) else() target_link_libraries(wivrn-common PUBLIC Vulkan::Headers) endif() target_link_libraries(wivrn-common PUBLIC Boost::pfr wivrn-external) target_compile_features(wivrn-common PRIVATE cxx_std_20) -target_compile_definitions(wivrn-common PUBLIC VULKAN_HPP_NO_STRUCT_CONSTRUCTORS VMA_VULKAN_VERSION=1001000) +target_compile_definitions(wivrn-common PUBLIC VULKAN_HPP_NO_STRUCT_CONSTRUCTORS) target_include_directories(wivrn-common PUBLIC ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_BINARY_DIR}) diff --git a/server/CMakeLists.txt b/server/CMakeLists.txt index ecbfec49..d8a74ad8 100644 --- a/server/CMakeLists.txt +++ b/server/CMakeLists.txt @@ -63,13 +63,14 @@ add_executable(wivrn-server hostname.cpp wivrn_ipc.cpp - driver/audio_pulse.cpp - driver/audio_setup.cpp - driver/configuration.cpp encoder/encoder_settings.cpp encoder/video_encoder.cpp encoder/yuv_converter.cpp + + driver/audio_pulse.cpp + driver/audio_setup.cpp driver/clock_offset.cpp + driver/configuration.cpp driver/wivrn_hmd.cpp driver/wivrn_pacer.cpp driver/wivrn_comp_target.cpp @@ -79,9 +80,13 @@ add_executable(wivrn-server driver/wivrn_session.cpp driver/wivrn_connection.cpp driver/xrt_cast.cpp + + utils/wivrn_vk_bundle.cpp + ${WIVRN_SHADER_HEADERS} ) target_compile_features(wivrn-server PRIVATE cxx_std_20) +target_compile_definitions(wivrn-server PRIVATE VULKAN_HPP_NO_CONSTRUCTORS) target_include_directories(wivrn-server SYSTEM PRIVATE ${monado_SOURCE_DIR}/src/xrt/compositor/) target_include_directories(wivrn-server PRIVATE .) @@ -94,11 +99,11 @@ endif() if(WIVRN_USE_VAAPI) target_sources( wivrn-server - PRIVATE encoder/ffmpeg/VideoEncoderFFMPEG.cpp - encoder/ffmpeg/VideoEncoderVA.cpp + PRIVATE encoder/ffmpeg/video_encoder_ffmpeg.cpp + encoder/ffmpeg/video_encoder_va.cpp encoder/ffmpeg/ffmpeg_helper.cpp ) - target_link_libraries(wivrn-server PRIVATE PkgConfig::LIBAV) + target_link_libraries(wivrn-server PRIVATE PkgConfig::LIBAV PkgConfig::LIBDRM) endif() if(WIVRN_USE_X264) diff --git a/server/driver/wivrn_comp_target.cpp b/server/driver/wivrn_comp_target.cpp index b021a9b8..1826f4bd 100644 --- a/server/driver/wivrn_comp_target.cpp +++ b/server/driver/wivrn_comp_target.cpp @@ -18,19 +18,49 @@ */ #include "wivrn_comp_target.h" +#include "encoder/video_encoder.h" #include "main/comp_compositor.h" #include "math/m_space.h" #include "encoder/video_encoder.h" -#include "vk/vk_cmd_pool.h" #include "xrt_cast.h" #include #include #include +#include #include +using namespace xrt::drivers::wivrn; + static const uint8_t image_free = 0; static const uint8_t image_acquired = 1; +std::vector wivrn_comp_target::wanted_instance_extensions = {}; +std::vector wivrn_comp_target::wanted_device_extensions = { +// For FFMPEG +#ifdef VK_KHR_external_memory_fd + VK_KHR_EXTERNAL_MEMORY_FD_EXTENSION_NAME, +#endif +#ifdef VK_EXT_external_memory_dma_buf + VK_EXT_EXTERNAL_MEMORY_DMA_BUF_EXTENSION_NAME, +#endif +#ifdef VK_EXT_image_drm_format_modifier + VK_EXT_IMAGE_DRM_FORMAT_MODIFIER_EXTENSION_NAME, +#endif + +// For vulkan video encode +#ifdef VK_KHR_video_queue + VK_KHR_VIDEO_QUEUE_EXTENSION_NAME, +#endif +#ifdef VK_KHR_video_encode_queue + VK_KHR_VIDEO_ENCODE_QUEUE_EXTENSION_NAME, +#endif +#ifdef VK_KHR_video_encode_h264 + VK_KHR_VIDEO_ENCODE_H264_EXTENSION_NAME, +#endif +#ifdef VK_KHR_video_encode_h265 + VK_KHR_VIDEO_ENCODE_H265_EXTENSION_NAME, +#endif +}; static void target_init_semaphores(struct wivrn_comp_target * cn); @@ -51,29 +81,34 @@ static void destroy_images(struct wivrn_comp_target * cn) cn->encoder_threads.clear(); cn->encoders.clear(); - struct vk_bundle * vk = get_vk(cn); - - for (uint32_t i = 0; i < cn->image_count; i++) - { - if (cn->images[i].view == VK_NULL_HANDLE) - { - continue; - } - - vk->vkDestroyImageView(vk->device, cn->images[i].view, NULL); - vk->vkDestroyImage(vk->device, cn->images[i].handle, NULL); - vk->vkFreeMemory(vk->device, cn->psc.images[i].memory, NULL); - vk->vkFreeCommandBuffers(vk->device, cn->pool.pool, 1, &cn->psc.images[i].present_cmd); - } + cn->psc.images.clear(); free(cn->images); - free(cn->psc.images); cn->images = NULL; - cn->psc.images = NULL; + cn->psc.images.clear(); target_fini_semaphores(cn); } +namespace +{ +class scoped_lock +{ + os_mutex & mutex; + +public: + scoped_lock(os_mutex & mutex) : + mutex(mutex) + { + os_mutex_lock(&mutex); + } + ~scoped_lock() + { + os_mutex_unlock(&mutex); + } +}; +}; // namespace + struct encoder_thread_param { wivrn_comp_target * cn; @@ -88,6 +123,7 @@ static void create_encoders(wivrn_comp_target * cn, std::vectorencoders.empty()); assert(cn->encoder_threads.empty()); + assert(cn->wivrn_bundle); to_headset::video_stream_description desc{}; desc.width = cn->width; @@ -101,21 +137,9 @@ static void create_encoders(wivrn_comp_target * cn, std::vectorencoders.size(); auto & encoder = cn->encoders.emplace_back( - VideoEncoder::Create(vk, cn->pool, settings, stream_index, desc.width, desc.height, desc.fps)); + VideoEncoder::Create(*cn->wivrn_bundle, settings, stream_index, desc.width, desc.height, desc.fps)); desc.items.push_back(settings); - std::vector images(cn->image_count); - std::vector memory(cn->image_count); - std::vector views(cn->image_count); - - for (size_t j = 0; j < cn->image_count; j++) - { - images[j] = cn->images[j].handle; - memory[j] = cn->psc.images[j].memory; - views[j] = cn->images[j].view; - } - encoder->SetImages(cn->width, cn->height, cn->format, cn->image_count, images.data(), views.data(), memory.data()); - thread_params[settings.group].encoders.emplace_back(encoder); } @@ -134,156 +158,72 @@ static void create_encoders(wivrn_comp_target * cn, std::vectorcnx->send_control(desc); } -class drm_image_modifier_helper +static VkResult create_images(struct wivrn_comp_target * cn, vk::ImageUsageFlags flags, const std::vector & settings) { - VkImageDrmFormatModifierListCreateInfoEXT drm_info{}; - std::vector modifiers; - -public: - void * pNext = nullptr; - drm_image_modifier_helper(vk_bundle * vk, VkFormat format, VkImageTiling tiling) - { - if (tiling != VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT) - return; - - VkDrmFormatModifierPropertiesListEXT drm_list{}; - drm_list.sType = VK_STRUCTURE_TYPE_DRM_FORMAT_MODIFIER_PROPERTIES_LIST_EXT; - - VkFormatProperties2 format_prop{}; - format_prop.sType = VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_2; - format_prop.pNext = &drm_list; - - vk->vkGetPhysicalDeviceFormatProperties2(vk->physical_device, format, &format_prop); - - std::vector properties(drm_list.drmFormatModifierCount); - drm_list.pDrmFormatModifierProperties = properties.data(); - - vk->vkGetPhysicalDeviceFormatProperties2(vk->physical_device, format, &format_prop); - - VkFormatFeatureFlags required_features = VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT | - VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT | - VK_FORMAT_FEATURE_TRANSFER_SRC_BIT; - for (const auto & mod: properties) - { - if ((mod.drmFormatModifierTilingFeatures & required_features) == required_features) - modifiers.push_back(mod.drmFormatModifier); - } - - assert(not modifiers.empty()); - - drm_info.sType = VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_LIST_CREATE_INFO_EXT; - drm_info.drmFormatModifierCount = modifiers.size(); - drm_info.pDrmFormatModifiers = modifiers.data(); - - pNext = &drm_info; - } -}; - -static VkResult create_images(struct wivrn_comp_target * cn, VkImageUsageFlags flags, const std::vector & settings) -{ - struct vk_bundle * vk = get_vk(cn); - + auto vk = get_vk(cn); assert(cn->image_count > 0); COMP_DEBUG(cn->c, "Creating %d images.", cn->image_count); + auto & device = cn->wivrn_bundle->device; destroy_images(cn); + auto format = vk::Format(cn->format); + cn->images = U_TYPED_ARRAY_CALLOC(struct comp_target_image, cn->image_count); - cn->psc.images = U_TYPED_ARRAY_CALLOC(pseudo_swapchain::pseudo_swapchain_memory, cn->image_count); - VkImageSubresourceRange subresource_range{}; - subresource_range.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - subresource_range.baseMipLevel = 0; - subresource_range.levelCount = 1; - subresource_range.baseArrayLayer = 0; - subresource_range.layerCount = 1; - - flags |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_SAMPLED_BIT; - - VkImageTiling tiling = get_required_tiling(vk, settings); - drm_image_modifier_helper drm_list(vk, cn->format, tiling); - - VkExternalMemoryHandleTypeFlags handle_types = get_handle_types(settings); - - VkExternalMemoryImageCreateInfo image_export_info{ - .sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO, - .pNext = drm_list.pNext, - .handleTypes = handle_types, - }; - - VkExportMemoryAllocateInfo export_info{ - .sType = VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO, - .handleTypes = handle_types, - }; + cn->psc.images.resize(cn->image_count); + for (uint32_t i = 0; i < cn->image_count; i++) + { + auto & image = cn->psc.images[i].image; + image = image_allocation( + device, { + .flags = vk::ImageCreateFlagBits::eExtendedUsage | vk::ImageCreateFlagBits::eMutableFormat, + .imageType = vk::ImageType::e2D, + .format = format, + .extent = { + .width = cn->width, + .height = cn->height, + .depth = 1, + }, + .mipLevels = 1, + .arrayLayers = 1, + .samples = vk::SampleCountFlagBits::e1, + .tiling = vk::ImageTiling::eOptimal, + .usage = flags | vk::ImageUsageFlagBits::eStorage, + .sharingMode = vk::SharingMode::eExclusive, + }, + { + .usage = VMA_MEMORY_USAGE_AUTO, + }); + cn->images[i].handle = image; + } for (uint32_t i = 0; i < cn->image_count; i++) { - auto & image = cn->images[i].handle; - auto & image_view = cn->images[i].view; - auto & memory = cn->psc.images[i].memory; - - VkExtent3D extent{cn->width, cn->height, 1}; - - VkImageCreateInfo image_info{}; - image_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; - image_info.pNext = &image_export_info; - image_info.imageType = VK_IMAGE_TYPE_2D; - image_info.format = cn->format; - image_info.extent = extent; - image_info.mipLevels = 1; - image_info.arrayLayers = 1; - image_info.samples = VK_SAMPLE_COUNT_1_BIT; - image_info.tiling = tiling; - image_info.usage = flags; - image_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; - image_info.queueFamilyIndexCount = 0; - image_info.pQueueFamilyIndices = NULL; - image_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; - - VkResult res = vk->vkCreateImage(vk->device, &image_info, NULL, &image); - VK_CHK_AND_RET(res, "vkCreateImage"); - - VkMemoryDedicatedAllocateInfoKHR dedicated_allocate_info{ - .sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO, - .pNext = &export_info, - .image = image, + auto & item = cn->psc.images[i]; + vk::ImageViewUsageCreateInfo usage{ + .usage = flags, }; + item.image_view = vk::raii::ImageView(device, + { + .pNext = &usage, + .image = item.image, + .viewType = vk::ImageViewType::e2D, + .format = format, + .subresourceRange = { + .aspectMask = vk::ImageAspectFlagBits::eColor, + .levelCount = 1, + .layerCount = 1, + }, + }); + cn->images[i].view = *item.image_view; + item.yuv = yuv_converter(vk->physical_device, device, item.image, format, vk::Extent2D{cn->width, cn->height}); - VkDeviceSize size; - res = vk_alloc_and_bind_image_memory(vk, image, -1, &dedicated_allocate_info, "wivrn_comp_target", &memory, &size); - VK_CHK_AND_RET(res, "vk_alloc_and_bind_image_memory"); + item.fence = vk::raii::Fence(device, vk::FenceCreateInfo()); - res = vk_create_view( // - vk, // vk_bundle - image, // image - VK_IMAGE_VIEW_TYPE_2D, // type - cn->format, // format - subresource_range, // subresource_range - &image_view); // out_view - VK_CHK_AND_RET(res, "vk_create_view"); - - VkFenceCreateInfo createinfo{}; - createinfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; - createinfo.pNext = NULL; - createinfo.flags = 0; - - res = vk->vkCreateFence(vk->device, &createinfo, NULL, &cn->psc.images[i].fence); - VK_CHK_AND_RET(res, "vkCreateFence"); - - res = vk_cmd_pool_create_and_begin_cmd_buffer(vk, &cn->pool, VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, &cn->psc.images[i].present_cmd); - VK_CHK_AND_RET(res, "vk_cmd_pool_create_and_begin_cmd_buffer"); - - VkImageSubresourceRange first_color_level_subresource_range{ - .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, - .baseMipLevel = 0, - .levelCount = 1, - .baseArrayLayer = 0, - .layerCount = 1, - }; - vk_cmd_image_barrier_gpu_locked(vk, cn->psc.images[i].present_cmd, image, 0, VK_ACCESS_SHADER_READ_BIT, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, VK_IMAGE_LAYOUT_GENERAL, first_color_level_subresource_range); - - res = vk->vkEndCommandBuffer(cn->psc.images[i].present_cmd); - VK_CHK_AND_RET(res, "vkEndCommandBuffer"); + item.command_buffer = std::move(device.allocateCommandBuffers( + {.commandPool = *cn->command_pool, + .commandBufferCount = 1})[0]); } return VK_SUCCESS; @@ -298,10 +238,24 @@ static bool comp_wivrn_init_post_vulkan(struct comp_target * ct, uint32_t prefer { struct wivrn_comp_target * cn = (struct wivrn_comp_target *)ct; auto vk = get_vk(cn); - - auto res = vk_cmd_pool_init(vk, &cn->pool, 0); - VK_CHK_WITH_RET(res, "vk_cmd_pool_init", false); - return true; + try + { + cn->wivrn_bundle.emplace(*vk, + wivrn_comp_target::wanted_instance_extensions, + wivrn_comp_target::wanted_device_extensions); + cn->command_pool = vk::raii::CommandPool( + cn->wivrn_bundle->device, + { + .flags = vk::CommandPoolCreateFlagBits::eResetCommandBuffer, + .queueFamilyIndex = vk->queue_family_index, + }); + return true; + } + catch (std::exception & e) + { + U_LOG_E("Compositor target init failed: %s", e.what()); + } + return false; } static bool comp_wivrn_check_ready(struct comp_target * ct) @@ -351,7 +305,7 @@ static void target_init_semaphores(struct wivrn_comp_target * cn) } } -static void comp_wivrn_create_images(struct comp_target * ct, const struct comp_target_create_images_info *create_info) +static void comp_wivrn_create_images(struct comp_target * ct, const struct comp_target_create_images_info * create_info) { struct wivrn_comp_target * cn = (struct wivrn_comp_target *)ct; @@ -362,7 +316,7 @@ static void comp_wivrn_create_images(struct comp_target * ct, const struct comp_ target_init_semaphores(cn); - //FIXME: select preferred format + // FIXME: select preferred format assert(create_info->format_count > 0); ct->format = create_info->formats[0]; ct->width = create_info->extent.width; @@ -375,12 +329,12 @@ static void comp_wivrn_create_images(struct comp_target * ct, const struct comp_ cn->height = create_info->extent.height; cn->color_space = create_info->color_space; - auto settings = get_encoder_settings(get_vk(cn), cn->width, cn->height); + auto settings = get_encoder_settings(*cn->wivrn_bundle->physical_device, cn->width, cn->height); - VkResult res = create_images(cn, create_info->image_usage, settings); + VkResult res = create_images(cn, vk::ImageUsageFlags(create_info->image_usage), settings); if (res != VK_SUCCESS) { - vk_print_result(get_vk(cn), __FILE__, __LINE__, __func__, res, "create_images"); + vk_print_result(get_vk(cn), __FILE__, __LINE__, __func__, res, "create_images"); // TODO abort(); } @@ -406,23 +360,19 @@ static VkResult comp_wivrn_acquire(struct comp_target * ct, uint32_t * out_index struct wivrn_comp_target * cn = (struct wivrn_comp_target *)ct; struct vk_bundle * vk = get_vk(cn); - VkSubmitInfo submit{}; - submit.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; - submit.pNext = NULL; - submit.waitSemaphoreCount = 0; - submit.pWaitSemaphores = NULL; - submit.pWaitDstStageMask = NULL; - submit.commandBufferCount = 0; - submit.pCommandBuffers = NULL; - submit.signalSemaphoreCount = 1; - submit.pSignalSemaphores = &cn->semaphores.present_complete; + vk::Semaphore sem(cn->semaphores.present_complete); - VkResult res = vk_cmd_pool_submit(vk, &cn->pool, 1, &submit, VK_NULL_HANDLE); - VK_CHK_AND_RET(res, "vk_locked_submit"); + vk::SubmitInfo submit_info{ + .signalSemaphoreCount = 1, + .pSignalSemaphores = &sem, + }; - res = VK_ERROR_OUT_OF_HOST_MEMORY; + { + scoped_lock lock(vk->queue_mutex); + cn->wivrn_bundle->queue.submit(submit_info); + } - while (res != VK_SUCCESS) + while (true) { std::lock_guard lock(cn->psc.mutex); for (uint32_t i = 0; i < ct->image_count; i++) @@ -432,13 +382,10 @@ static VkResult comp_wivrn_acquire(struct comp_target * ct, uint32_t * out_index cn->psc.images[i].status = image_acquired; *out_index = i; - res = VK_SUCCESS; - break; + return VK_SUCCESS; } } }; - - return res; } static void * comp_wivrn_present_thread(void * void_param) @@ -470,7 +417,7 @@ static void * comp_wivrn_present_thread(void * void_param) presenting_index = i; } indices[nb_fences] = i; - fences[nb_fences++] = cn->psc.images[i].fence; + fences[nb_fences++] = *cn->psc.images[i].fence; } } @@ -495,7 +442,7 @@ static void * comp_wivrn_present_thread(void * void_param) { for (auto & encoder: param->encoders) { - encoder->Encode(*cn->cnx, psc_image.view_info, psc_image.frame_index, presenting_index); + encoder->Encode(*cn->cnx, psc_image.view_info, psc_image.frame_index); } } catch (...) @@ -514,21 +461,39 @@ static void * comp_wivrn_present_thread(void * void_param) } static VkResult comp_wivrn_present(struct comp_target * ct, - VkQueue queue, + VkQueue queue_, uint32_t index, uint64_t timeline_semaphore_value, uint64_t desired_present_time_ns, uint64_t present_slop_ns) { struct wivrn_comp_target * cn = (struct wivrn_comp_target *)ct; - struct vk_bundle * vk = get_vk(cn); assert(index < cn->image_count); + struct vk_bundle * vk = get_vk(cn); + + auto & command_buffer = cn->psc.images[index].command_buffer; + command_buffer.reset(); + command_buffer.begin(vk::CommandBufferBeginInfo{}); + + vk::Semaphore wait_semaphore = cn->semaphores.render_complete; + vk::PipelineStageFlags wait_stage = vk::PipelineStageFlagBits::eAllCommands; + vk::SubmitInfo submit_info{ + .waitSemaphoreCount = 1, + .pWaitSemaphores = &wait_semaphore, + .pWaitDstStageMask = &wait_stage, + .commandBufferCount = 1, + .pCommandBuffers = &*command_buffer, + }; + if (cn->c->base.slot.layer_count == 0 or not cn->cnx->get_offset()) { // TODO: Tell the headset that there is no image to display assert(cn->psc.images[index].status == image_acquired); + command_buffer.end(); + scoped_lock lock(vk->queue_mutex); + cn->wivrn_bundle->queue.submit(submit_info); cn->psc.images[index].status = image_free; return VK_SUCCESS; } @@ -536,33 +501,20 @@ static VkResult comp_wivrn_present(struct comp_target * ct, assert(index < ct->image_count); assert(ct->images != NULL); - std::vector cmdBuffers{cn->psc.images[index].present_cmd}; - + auto & yuv = cn->psc.images[index].yuv; + yuv.record_draw_commands(command_buffer); for (auto & encoder: cn->encoders) { - VkCommandBuffer cmdBuffer = VK_NULL_HANDLE; - encoder->PresentImage(index, &cmdBuffer); - if (cmdBuffer != VK_NULL_HANDLE) - cmdBuffers.push_back(cmdBuffer); + encoder->PresentImage(yuv, command_buffer); } - - VkPipelineStageFlags sem_flags = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT; - VkSubmitInfo submit{}; - submit.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; - submit.pNext = NULL; - submit.waitSemaphoreCount = 1; - submit.pWaitSemaphores = &cn->semaphores.render_complete; - submit.pWaitDstStageMask = &sem_flags; - submit.commandBufferCount = cmdBuffers.size(); - submit.pCommandBuffers = cmdBuffers.data(); - submit.signalSemaphoreCount = 0; - submit.pSignalSemaphores = NULL; + command_buffer.end(); std::lock_guard lock(cn->psc.mutex); - VkResult res = vk->vkResetFences(vk->device, 1, &cn->psc.images[index].fence); - VK_CHK_AND_RET(res, "vkResetFences"); - res = vk_cmd_pool_submit(vk, &cn->pool, 1, &submit, cn->psc.images[index].fence); - VK_CHK_AND_RET(res, "vk_locked_submit"); + cn->wivrn_bundle->device.resetFences(*cn->psc.images[index].fence); + { + scoped_lock lock(vk->queue_mutex); + cn->wivrn_bundle->queue.submit(submit_info, *cn->psc.images[index].fence); + } assert(cn->psc.images[index].status == image_acquired); cn->frame_index++; @@ -645,15 +597,16 @@ static VkResult comp_wivrn_update_timings(struct comp_target * ct) static void comp_wivrn_set_title(struct comp_target * ct, const char * title) {} +wivrn_comp_target::~wivrn_comp_target() +{ + if (wivrn_bundle) + wivrn_bundle->device.waitIdle(); + destroy_images(this); +} + static void comp_wivrn_destroy(struct comp_target * ct) { - struct wivrn_comp_target * cn = (struct wivrn_comp_target *)ct; - - vk_bundle * vk = get_vk(cn); - vk->vkDeviceWaitIdle(vk->device); - destroy_images(cn); - - delete cn; + delete (struct wivrn_comp_target *)ct; } static void comp_wivrn_info_gpu(struct comp_target * ct, int64_t frame_id, uint64_t gpu_start_ns, uint64_t gpu_end_ns, uint64_t when_ns) diff --git a/server/driver/wivrn_comp_target.h b/server/driver/wivrn_comp_target.h index 53eeda49..7d590b61 100644 --- a/server/driver/wivrn_comp_target.h +++ b/server/driver/wivrn_comp_target.h @@ -23,13 +23,18 @@ #include "wivrn_session.h" #include "main/comp_target.h" -#include "vk/vk_cmd_pool.h" + +#include "encoder/yuv_converter.h" +#include "utils/wivrn_vk_bundle.h" +#include "vk/allocation.h" #include #include #include +#include #include #include "driver/wivrn_pacer.h" +#include namespace xrt::drivers::wivrn { @@ -38,15 +43,18 @@ class VideoEncoder; struct pseudo_swapchain { - struct pseudo_swapchain_memory + struct item { - VkFence fence; - VkDeviceMemory memory; - VkCommandBuffer present_cmd; + image_allocation image; + vk::raii::ImageView image_view = nullptr; + vk::raii::Fence fence = nullptr; + vk::raii::CommandBuffer command_buffer = nullptr; + yuv_converter yuv; uint8_t status; // bitmask of consumer status, index 0 for acquired, the rest for each encoder uint64_t frame_index; to_headset::video_stream_data_shard::view_info_t view_info{}; - } * images{}; + }; + std::vector images; std::mutex mutex; std::condition_variable cv; }; @@ -55,7 +63,8 @@ struct wivrn_comp_target : public comp_target { wivrn_pacer pacer; - vk_cmd_pool pool; + std::optional wivrn_bundle; + vk::raii::CommandPool command_pool = nullptr; float fps; @@ -68,6 +77,9 @@ struct wivrn_comp_target : public comp_target VkColorSpaceKHR color_space; + static std::vector wanted_instance_extensions; + static std::vector wanted_device_extensions; + struct encoder_thread { int index; @@ -89,6 +101,7 @@ struct wivrn_comp_target : public comp_target std::shared_ptr cnx; wivrn_comp_target(std::shared_ptr cnx, struct comp_compositor * c, float fps); + ~wivrn_comp_target(); void on_feedback(const from_headset::feedback &, const clock_offset &); }; diff --git a/server/encoder/encoder_settings.cpp b/server/encoder/encoder_settings.cpp index 7b77a0fc..9e6884ad 100644 --- a/server/encoder/encoder_settings.cpp +++ b/server/encoder/encoder_settings.cpp @@ -19,8 +19,8 @@ #include "encoder_settings.h" #include "driver/configuration.h" +#include "util/u_logging.h" #include "video_encoder.h" -#include "vk/vk_helpers.h" #include #include @@ -29,7 +29,7 @@ #include "wivrn_config.h" #ifdef WIVRN_USE_VAAPI -#include "ffmpeg/VideoEncoderVA.h" +#include "ffmpeg/video_encoder_va.h" #endif using namespace xrt::drivers::wivrn; @@ -37,14 +37,13 @@ using namespace xrt::drivers::wivrn; // TODO: size independent bitrate static const uint64_t default_bitrate = 50'000'000; -static bool is_nvidia(vk_bundle * vk) +static bool is_nvidia(vk::PhysicalDevice physical_device) { - VkPhysicalDeviceProperties physical_device_properties; - vk->vkGetPhysicalDeviceProperties(vk->physical_device, &physical_device_properties); - return physical_device_properties.vendorID == 0x10DE; + auto props = physical_device.getProperties(); + return props.vendorID == 0x10DE; } -static std::vector get_encoder_default_settings(vk_bundle * vk, uint16_t width, uint16_t height) +static std::vector get_encoder_default_settings(vk::PhysicalDevice physical_device, uint16_t width, uint16_t height) { xrt::drivers::wivrn::encoder_settings settings{}; settings.width = width; @@ -55,7 +54,7 @@ static std::vector get_encoder_default_se settings.video_height = settings.height; settings.video_width = settings.width; - if (is_nvidia(vk)) + if (is_nvidia(physical_device)) { #ifdef WIVRN_USE_NVENC settings.encoder_name = encoder_nvenc; @@ -85,13 +84,13 @@ static std::vector get_encoder_default_se return {settings}; } -std::vector xrt::drivers::wivrn::get_encoder_settings(vk_bundle * vk, uint16_t width, uint16_t height) +std::vector xrt::drivers::wivrn::get_encoder_settings(vk::PhysicalDevice physical_device, uint16_t width, uint16_t height) { try { const auto & config = configuration::read_user_configuration(); if (config.encoders.empty()) - return get_encoder_default_settings(vk, width, height); + return get_encoder_default_settings(physical_device, width, height); std::vector res; int next_group = 0; for (const auto & encoder: config.encoders) @@ -118,45 +117,5 @@ std::vector xrt::drivers::wivrn::get_encoder_settings(vk_bundl { U_LOG_E("Failed to read encoder configuration: %s", e.what()); } - return get_encoder_default_settings(vk, width, height); -} - -VkImageTiling xrt::drivers::wivrn::get_required_tiling(vk_bundle * vk, - const std::vector & settings) -{ - bool can_optimal = true; - bool can_drm = vk->has_EXT_image_drm_format_modifier; - for (const auto & item: settings) - { -#ifdef WIVRN_USE_VAAPI - if (item.encoder_name == encoder_vaapi) - { - can_optimal = false; - if (not use_drm_format_modifiers) - can_drm = false; - } -#endif - } - if (can_optimal) - return VK_IMAGE_TILING_OPTIMAL; - if (can_drm) - return VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT; - return VK_IMAGE_TILING_LINEAR; -} - -VkExternalMemoryHandleTypeFlags xrt::drivers::wivrn::get_handle_types(const std::vector & settings) -{ - VkExternalMemoryHandleTypeFlags result = 0; - for (const auto & item: settings) - { -#ifdef WIVRN_USE_VAAPI - if (item.encoder_name == encoder_vaapi) - result |= VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT; -#endif -#ifdef WIVRN_USE_NVENC - if (item.encoder_name == encoder_nvenc) - result |= VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT; -#endif - } - return result; + return get_encoder_default_settings(physical_device, width, height); } diff --git a/server/encoder/encoder_settings.h b/server/encoder/encoder_settings.h index f5cf1bcc..5969c93f 100644 --- a/server/encoder/encoder_settings.h +++ b/server/encoder/encoder_settings.h @@ -19,11 +19,11 @@ #pragma once -#include "vk/vk_helpers.h" #include "wivrn_packets.h" #include #include +#include namespace xrt::drivers::wivrn { @@ -38,10 +38,6 @@ struct encoder_settings : public to_headset::video_stream_description::item int group = 0; }; -std::vector get_encoder_settings(vk_bundle * vk, uint16_t width, uint16_t height); - -VkImageTiling get_required_tiling(vk_bundle * vk, const std::vector & settings); - -VkExternalMemoryHandleTypeFlags get_handle_types(const std::vector & settings); +std::vector get_encoder_settings(vk::PhysicalDevice physical_device, uint16_t width, uint16_t height); } // namespace xrt::drivers::wivrn diff --git a/server/encoder/ffmpeg/VideoEncoderVA.cpp b/server/encoder/ffmpeg/VideoEncoderVA.cpp deleted file mode 100644 index b88e78e3..00000000 --- a/server/encoder/ffmpeg/VideoEncoderVA.cpp +++ /dev/null @@ -1,359 +0,0 @@ -/* - * WiVRn VR streaming - * Copyright (C) 2022 Guillaume Meunier - * Copyright (C) 2022 Patrick Nicolas - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -#include "VideoEncoderVA.h" -#include "ffmpeg_helper.h" -#include "vk/vk_helpers.h" -#include -#include -#include -#include -#include -#include - -extern "C" -{ -#include -#include -#include -#include -#include -#include -#include -#include -} - -namespace -{ - -const char * -encoder(VideoEncoderFFMPEG::Codec codec) -{ - switch (codec) - { - case VideoEncoderFFMPEG::Codec::h264: - return "h264_vaapi"; - case VideoEncoderFFMPEG::Codec::h265: - return "hevc_vaapi"; - } - throw std::runtime_error("invalid codec " + std::to_string(int(codec))); -} - -void set_hwframe_ctx(AVCodecContext * ctx, AVBufferRef * hw_device_ctx) -{ - av_buffer_ptr hw_frames_ref(av_hwframe_ctx_alloc(hw_device_ctx)); - int err = 0; - - if (not hw_frames_ref) - { - throw std::runtime_error("Failed to create VAAPI frame context."); - } - auto frames_ctx = (AVHWFramesContext *)(hw_frames_ref->data); - frames_ctx->format = AV_PIX_FMT_VAAPI; - frames_ctx->sw_format = AV_PIX_FMT_NV12; - frames_ctx->width = ctx->width; - frames_ctx->height = ctx->height; - frames_ctx->initial_pool_size = 3; - if ((err = av_hwframe_ctx_init(hw_frames_ref.get())) < 0) - { - throw std::system_error(err, av_error_category(), "Failed to initialize VAAPI frame context"); - } - ctx->hw_frames_ctx = av_buffer_ref(hw_frames_ref.get()); - if (!ctx->hw_frames_ctx) - err = AVERROR(ENOMEM); -} - -std::optional -get_render_device(vk_bundle * vk) -{ - VkPhysicalDeviceDrmPropertiesEXT drmProps{}; - drmProps.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRM_PROPERTIES_EXT; - - VkPhysicalDeviceProperties2 props{}; - props.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2; - props.pNext = &drmProps; - - vk->vkGetPhysicalDeviceProperties2(vk->physical_device, &props); - - if (!drmProps.hasRender) - { - U_LOG_E("Failed to find render DRM device"); - throw std::runtime_error("Failed to find render DRM device"); - } - std::filesystem::path path = "/dev/dri/renderD" + std::to_string(drmProps.renderMinor); - if (not std::filesystem::exists(path)) - { - U_LOG_W("DRI device %s does not exist, reverting to default", path.c_str()); - return std::nullopt; - } - return path; -} - -} // namespace - -VideoEncoderVA::VideoEncoderVA(vk_bundle * vk, const xrt::drivers::wivrn::encoder_settings & settings, float fps) : - vk(vk), width(settings.width), height(settings.height), offset_x(settings.offset_x), offset_y(settings.offset_y) -{ - codec = settings.codec; - /* VAAPI Encoding pipeline - * The encoding pipeline has 3 frame types: - * - input vulkan frames, only used to initialize the mapped frames - * - mapped frames, one per input frame, same format, and point to the same memory on the device - * - encoder frame, with a format compatible with the encoder, created by the filter - * Each frame type has a corresponding hardware frame context, the vulkan one is provided - * - * The pipeline is simply made of a scale_vaapi object, that does the conversion between formats - * and the encoder that takes the converted frame and produces packets. - */ - - AVBufferRef * tmp; - const auto device = get_render_device(vk); - int err = av_hwdevice_ctx_create(&tmp, AV_HWDEVICE_TYPE_VAAPI, device ? device->c_str() : NULL, NULL, 0); - if (err < 0) - { - throw std::system_error(err, av_error_category(), "Failed create VAAPI device" + (device ? (" " + device->string()) : std::string())); - } - hw_ctx_vaapi.reset(tmp); - - const char * encoder_name = encoder(codec); - const AVCodec * codec = avcodec_find_encoder_by_name(encoder_name); - if (codec == nullptr) - { - throw std::runtime_error(std::string("Failed to find encoder ") + encoder_name); - } - - encoder_ctx.reset(avcodec_alloc_context3(codec)); - if (not encoder_ctx) - { - throw std::runtime_error("failed to allocate VAAPI encoder"); - } - - AVDictionary * opts = nullptr; - av_dict_set(&opts, "async_depth", "1", 0); - for (auto option: settings.options) - { - av_dict_set(&opts, option.first.c_str(), option.second.c_str(), 0); - } - switch (this->codec) - { - case Codec::h264: - encoder_ctx->profile = FF_PROFILE_H264_MAIN; - break; - case Codec::h265: - encoder_ctx->profile = FF_PROFILE_HEVC_MAIN; - break; - } - - encoder_ctx->width = width; - encoder_ctx->height = height; - encoder_ctx->time_base = {std::chrono::steady_clock::duration::period::num, - std::chrono::steady_clock::duration::period::den}; - encoder_ctx->framerate = AVRational{(int)fps, 1}; - encoder_ctx->sample_aspect_ratio = AVRational{1, 1}; - encoder_ctx->pix_fmt = AV_PIX_FMT_VAAPI; - encoder_ctx->max_b_frames = 0; - encoder_ctx->bit_rate = settings.bitrate; - encoder_ctx->gop_size = std::numeric_limitsgop_size)>::max(); - - set_hwframe_ctx(encoder_ctx.get(), hw_ctx_vaapi.get()); - - err = avcodec_open2(encoder_ctx.get(), codec, &opts); - av_dict_free(&opts); - if (err < 0) - { - throw std::system_error(err, av_error_category(), "Cannot open video encoder codec"); - } - - if (encoder_ctx->delay != 0) - { - U_LOG_W("Encoder %d reports a %d frame delay, reprojection will fail", stream_idx, encoder_ctx->delay); - } -} - -void VideoEncoderVA::PushFrame(uint32_t frame_index, bool idr, std::chrono::steady_clock::time_point pts) -{ - assert(frame_index < mapped_frames.size()); - av_frame_ptr encoder_frame = make_av_frame(); - int err = av_buffersrc_add_frame_flags(filter_in, mapped_frames[frame_index].get(), AV_BUFFERSRC_FLAG_PUSH | AV_BUFFERSRC_FLAG_KEEP_REF); - if (err != 0) - { - throw std::system_error(err, av_error_category(), "av_buffersrc_add_frame failed"); - } - err = av_buffersink_get_frame(filter_out, encoder_frame.get()); - if (err != 0) - { - throw std::system_error(err, av_error_category(), "av_buffersink_get_frame failed"); - } - - encoder_frame->pict_type = idr ? AV_PICTURE_TYPE_I : AV_PICTURE_TYPE_P; - encoder_frame->pts = pts.time_since_epoch().count(); - err = avcodec_send_frame(encoder_ctx.get(), encoder_frame.get()); - if (err) - { - throw std::system_error(err, av_error_category(), "avcodec_send_frame failed"); - } -} - -void VideoEncoderVA::SetImages( - int width, - int height, - VkFormat format, - int num_images, - VkImage * images, - VkImageView * views, - VkDeviceMemory * memory) -{ - mapped_frames.clear(); - av_buffer_ptr va_ctx(av_hwframe_ctx_alloc(hw_ctx_vaapi.get())); - if (!va_ctx) - { - throw std::runtime_error("Failed to create VAAPI frame context."); - } - AVHWFramesContext * va_frames_ctx = (AVHWFramesContext *)(va_ctx->data); - va_frames_ctx->format = AV_PIX_FMT_VAAPI; - va_frames_ctx->sw_format = vk_format_to_av_format(format); - va_frames_ctx->width = width; - va_frames_ctx->height = height; - va_frames_ctx->initial_pool_size = num_images; - int err = av_hwframe_ctx_init(va_ctx.get()); - if (err) - { - throw std::system_error(err, av_error_category(), "Failed to create VAAPI frame context"); - } - - mapped_frames.reserve(num_images); - for (int i = 0; i < num_images; ++i) - { - VkMemoryRequirements req; - vk->vkGetImageMemoryRequirements(vk->device, images[i], &req); - - int fd; - VkMemoryGetFdInfoKHR export_info{}; - export_info.sType = VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR; - export_info.memory = memory[i]; - export_info.handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT; - vk->vkGetMemoryFdKHR(vk->device, &export_info, &fd); - - auto drm_frame = make_av_frame(); - drm_frame->format = AV_PIX_FMT_DRM_PRIME; - drm_frame->width = width; - drm_frame->height = height; - drm_frame->buf[0] = av_buffer_alloc(sizeof(AVDRMFrameDescriptor)); - drm_frame->data[0] = drm_frame->buf[0]->data; - auto & drm_frame_desc = *(AVDRMFrameDescriptor *)drm_frame->data[0]; - drm_frame_desc.nb_objects = 1; - drm_frame_desc.objects[0].fd = fd; - drm_frame_desc.objects[0].size = req.size; - drm_frame_desc.nb_layers = 1; - drm_frame_desc.layers[0].format = vk_format_to_fourcc(format); - drm_frame_desc.layers[0].nb_planes = 1; - drm_frame_desc.layers[0].planes[0].object_index = 0; - - // DRM format modifiers seem to be broken on ffmpeg or radeon, or both - bool drm_tiling = use_drm_format_modifiers and vk->has_EXT_image_drm_format_modifier; - if (drm_tiling) - { - VkImageDrmFormatModifierPropertiesEXT modifiers{}; - modifiers.sType = VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_PROPERTIES_EXT; - vk->vkGetImageDrmFormatModifierPropertiesEXT(vk->device, images[i], &modifiers); - drm_frame_desc.objects[0].format_modifier = modifiers.drmFormatModifier; - } - // if we don't have modifiers, we did linear tiling - VkImageSubresource subresource{(use_drm_format_modifiers and vk->has_EXT_image_drm_format_modifier) - ? VK_IMAGE_ASPECT_MEMORY_PLANE_0_BIT_EXT - : VK_IMAGE_ASPECT_COLOR_BIT, - 0, - 0}; - VkSubresourceLayout layout; - vk->vkGetImageSubresourceLayout(vk->device, images[i], &subresource, &layout); - drm_frame_desc.layers[0].planes[0].offset = layout.offset; - drm_frame_desc.layers[0].planes[0].pitch = layout.rowPitch; - - auto va_frame = make_av_frame(); - err = av_hwframe_get_buffer(va_ctx.get(), va_frame.get(), 0); - if (err) - throw std::system_error(err, av_error_category(), "Failed to create VAAPI frame"); - err = av_hwframe_map(va_frame.get(), drm_frame.get(), AV_HWFRAME_MAP_DIRECT); - if (err) - throw std::system_error(err, av_error_category(), "Failed to map DRM frame to VAAPI frame"); - va_frame->crop_left = offset_x; - va_frame->crop_right = width - this->width - offset_x; - va_frame->crop_top = offset_y; - va_frame->crop_bottom = height - this->height - offset_y; - mapped_frames.push_back(std::move(va_frame)); - } - - InitFilterGraph(); -} - -void VideoEncoderVA::InitFilterGraph() -{ - assert(not mapped_frames.empty()); - - filter_graph.reset(avfilter_graph_alloc()); - - AVFilterInOut * outputs = avfilter_inout_alloc(); - AVFilterInOut * inputs = avfilter_inout_alloc(); - - std::stringstream buffer_filter_args; - buffer_filter_args << "video_size=" << mapped_frames[0]->width << "x" << mapped_frames[0]->height; - buffer_filter_args << ":pix_fmt=" << mapped_frames[0]->format; - buffer_filter_args << ":time_base=" << encoder_ctx->time_base.num << "/" << encoder_ctx->time_base.den; - int err; - if ((err = avfilter_graph_create_filter(&filter_in, avfilter_get_by_name("buffer"), "in", buffer_filter_args.str().c_str(), NULL, filter_graph.get()))) - { - throw std::system_error(err, av_error_category(), "filter_in creation failed"); - } - AVBufferSrcParameters * par = av_buffersrc_parameters_alloc(); - memset(par, 0, sizeof(*par)); - par->format = AV_PIX_FMT_NONE; - par->hw_frames_ctx = av_buffer_ref(mapped_frames[0]->hw_frames_ctx); - av_buffersrc_parameters_set(filter_in, par); - av_free(par); - - if ((err = avfilter_graph_create_filter(&filter_out, avfilter_get_by_name("buffersink"), "out", NULL, NULL, filter_graph.get()))) - { - throw std::system_error(err, av_error_category(), "filter_out creation failed"); - } - - outputs->name = av_strdup("in"); - outputs->filter_ctx = filter_in; - outputs->pad_idx = 0; - outputs->next = NULL; - - inputs->name = av_strdup("out"); - inputs->filter_ctx = filter_out; - inputs->pad_idx = 0; - inputs->next = NULL; - - std::string scale_param = "scale_vaapi=format=nv12:w=" + std::to_string(encoder_ctx->width) + - ":h=" + std::to_string(encoder_ctx->height); - err = avfilter_graph_parse_ptr(filter_graph.get(), scale_param.c_str(), &inputs, &outputs, NULL); - avfilter_inout_free(&outputs); - avfilter_inout_free(&inputs); - if (err < 0) - { - throw std::system_error(err, av_error_category(), "avfilter_graph_parse_ptr failed"); - } - - if ((err = avfilter_graph_config(filter_graph.get(), NULL))) - { - throw std::system_error(err, av_error_category(), "avfilter_graph_config failed"); - } -} diff --git a/server/encoder/ffmpeg/VideoEncoderVA.h b/server/encoder/ffmpeg/VideoEncoderVA.h deleted file mode 100644 index 8afff7e5..00000000 --- a/server/encoder/ffmpeg/VideoEncoderVA.h +++ /dev/null @@ -1,68 +0,0 @@ -/* - * WiVRn VR streaming - * Copyright (C) 2022 Guillaume Meunier - * Copyright (C) 2022 Patrick Nicolas - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -#pragma once - -#include "VideoEncoderFFMPEG.h" -#include "ffmpeg_helper.h" -#include "vk/vk_helpers.h" - -extern "C" -{ -#include -} - -// DRM format modifiers are not implemented before ffmpeg 5 -inline const bool use_drm_format_modifiers = LIBAVUTIL_VERSION_MAJOR >= 57; - -struct AVFilterContext; - -class VideoEncoderVA : public VideoEncoderFFMPEG -{ -public: - VideoEncoderVA(vk_bundle * vk, const xrt::drivers::wivrn::encoder_settings & settings, float fps); - - void - SetImages(int width, - int height, - VkFormat format, - int num_images, - VkImage * images, - VkImageView * views, - VkDeviceMemory * memory) override; - - void - PushFrame(uint32_t frame_index, bool idr, std::chrono::steady_clock::time_point pts) override; - -private: - void - InitFilterGraph(); - - vk_bundle * vk; - int width; - int height; - // relevant part of the input image to encode - int offset_x; - int offset_y; - av_buffer_ptr hw_ctx_vaapi; - std::vector mapped_frames; - av_filter_graph_ptr filter_graph; - AVFilterContext * filter_in = nullptr; - AVFilterContext * filter_out = nullptr; -}; diff --git a/server/encoder/ffmpeg/ffmpeg_helper.h b/server/encoder/ffmpeg/ffmpeg_helper.h index 91245692..d22a2216 100644 --- a/server/encoder/ffmpeg/ffmpeg_helper.h +++ b/server/encoder/ffmpeg/ffmpeg_helper.h @@ -63,9 +63,6 @@ using av_codec_context_ptr = std::unique_ptr; using av_filter_graph_ptr = std::unique_ptr; using av_packet_ptr = std::unique_ptr; -av_buffer_ptr -make_av_buffer(AVBufferRef *); - av_frame_ptr make_av_frame(AVFrame *); diff --git a/server/encoder/ffmpeg/VideoEncoderFFMPEG.cpp b/server/encoder/ffmpeg/video_encoder_ffmpeg.cpp similarity index 58% rename from server/encoder/ffmpeg/VideoEncoderFFMPEG.cpp rename to server/encoder/ffmpeg/video_encoder_ffmpeg.cpp index de976759..4c4f9a8a 100644 --- a/server/encoder/ffmpeg/VideoEncoderFFMPEG.cpp +++ b/server/encoder/ffmpeg/video_encoder_ffmpeg.cpp @@ -17,11 +17,9 @@ * along with this program. If not, see . */ -#include "VideoEncoderFFMPEG.h" -#include -#include +#include "video_encoder_ffmpeg.h" +#include "util/u_logging.h" #include -#include extern "C" { @@ -32,54 +30,6 @@ extern "C" namespace { -bool should_keep_nal_h264(const uint8_t * header_start) -{ - uint8_t nal_type = (header_start[2] == 0 ? header_start[4] : header_start[3]) & 0x1F; - switch (nal_type) - { - case 6: // supplemental enhancement information - case 9: // access unit delimiter - return false; - default: - return true; - } -} - -bool should_keep_nal_h265(const uint8_t * header_start) -{ - uint8_t nal_type = ((header_start[2] == 0 ? header_start[4] : header_start[3]) >> 1) & 0x3F; - switch (nal_type) - { - case 35: // access unit delimiter - case 39: // supplemental enhancement information - return false; - default: - return true; - } -} - -void filter_NAL(const uint8_t * input, size_t input_size, std::vector & out, VideoEncoderFFMPEG::Codec codec) -{ - if (input_size < 4) - return; - std::array header = {{0, 0, 1}}; - auto end = input + input_size; - auto header_start = input; - while (header_start != end) - { - auto next_header = std::search(header_start + 3, end, header.begin(), header.end()); - if (next_header != end and next_header[-1] == 0) - { - next_header--; - } - if (codec == VideoEncoderFFMPEG::Codec::h264 and should_keep_nal_h264(header_start)) - out.insert(out.end(), header_start, next_header); - if (codec == VideoEncoderFFMPEG::Codec::h265 and should_keep_nal_h265(header_start)) - out.insert(out.end(), header_start, next_header); - header_start = next_header; - } -} - bool set_log_level() { const char * level = getenv("FFMPEG_LOG_LEVEL"); @@ -113,9 +63,9 @@ bool set_log_level() bool VideoEncoderFFMPEG::once = set_log_level(); -void VideoEncoderFFMPEG::Encode(int index, bool idr, std::chrono::steady_clock::time_point target_timestamp) +void VideoEncoderFFMPEG::Encode(bool idr, std::chrono::steady_clock::time_point target_timestamp) { - PushFrame(index, idr, target_timestamp); + PushFrame(idr, target_timestamp); av_packet_ptr enc_pkt(av_packet_alloc()); int err = avcodec_receive_packet(encoder_ctx.get(), enc_pkt.get()); if (err == 0) diff --git a/server/encoder/ffmpeg/VideoEncoderFFMPEG.h b/server/encoder/ffmpeg/video_encoder_ffmpeg.h similarity index 81% rename from server/encoder/ffmpeg/VideoEncoderFFMPEG.h rename to server/encoder/ffmpeg/video_encoder_ffmpeg.h index dc4213cd..b2ce07c2 100644 --- a/server/encoder/ffmpeg/VideoEncoderFFMPEG.h +++ b/server/encoder/ffmpeg/video_encoder_ffmpeg.h @@ -19,10 +19,9 @@ #pragma once -#include "../video_encoder.h" +#include "encoder/video_encoder.h" #include "ffmpeg_helper.h" #include -#include class VideoEncoderFFMPEG : public xrt::drivers::wivrn::VideoEncoder { @@ -30,14 +29,13 @@ public: using Codec = xrt::drivers::wivrn::video_codec; void - Encode(int index, bool idr, std::chrono::steady_clock::time_point target_timestamp) override; + Encode(bool idr, std::chrono::steady_clock::time_point target_timestamp) override; protected: virtual void - PushFrame(uint32_t frame_index, bool idr, std::chrono::steady_clock::time_point pts) = 0; + PushFrame(bool idr, std::chrono::steady_clock::time_point pts) = 0; av_codec_context_ptr encoder_ctx; - Codec codec; private: static bool once; diff --git a/server/encoder/ffmpeg/video_encoder_va.cpp b/server/encoder/ffmpeg/video_encoder_va.cpp new file mode 100644 index 00000000..94c3d759 --- /dev/null +++ b/server/encoder/ffmpeg/video_encoder_va.cpp @@ -0,0 +1,416 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2022-2024 Guillaume Meunier + * Copyright (C) 2022-2024 Patrick Nicolas + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +// must be included before vulkan_raii + +#include "video_encoder_va.h" + +#include "encoder/yuv_converter.h" +#include "util/u_logging.h" +#include "utils/wivrn_vk_bundle.h" + +#include +#include +#include +#include +#include + +extern "C" +{ +#include +#include +#include +#include +} + +namespace +{ +const char * +encoder(VideoEncoderFFMPEG::Codec codec) +{ + switch (codec) + { + case VideoEncoderFFMPEG::Codec::h264: + return "h264_vaapi"; + case VideoEncoderFFMPEG::Codec::h265: + return "hevc_vaapi"; + } + throw std::runtime_error("invalid codec " + std::to_string(int(codec))); +} + +av_buffer_ptr make_hwframe_ctx(AVBufferRef * hw_device_ctx, AVPixelFormat hw_format, AVPixelFormat sw_format, int width, int height) +{ + av_buffer_ptr hw_frames_ref(av_hwframe_ctx_alloc(hw_device_ctx)); + + if (not hw_frames_ref) + { + throw std::runtime_error("Failed to create VAAPI frame context."); + } + auto frames_ctx = (AVHWFramesContext *)(hw_frames_ref->data); + frames_ctx->format = hw_format; + frames_ctx->sw_format = sw_format; + frames_ctx->width = width; + frames_ctx->height = height; + frames_ctx->initial_pool_size = 10; + if (int err = av_hwframe_ctx_init(hw_frames_ref.get()); err < 0) + { + throw std::system_error(err, av_error_category(), "Failed to initialize frame context"); + } + return std::move(hw_frames_ref); +} + +std::optional +get_render_device(vk::raii::PhysicalDevice & physical_device) +{ + auto [props, drm_props] = physical_device.getProperties2(); + + if (!drm_props.hasRender) + { + U_LOG_E("Failed to find render DRM device"); + throw std::runtime_error("Failed to find render DRM device"); + } + std::filesystem::path path = "/dev/dri/renderD" + std::to_string(drm_props.renderMinor); + if (not std::filesystem::exists(path)) + { + U_LOG_W("DRI device %s does not exist, reverting to default", path.c_str()); + return std::nullopt; + } + return path; +} + +av_buffer_ptr make_drm_hw_ctx(vk::raii::PhysicalDevice & physical_device) +{ + const auto device = get_render_device(physical_device); + AVBufferRef * hw_ctx; + int err = av_hwdevice_ctx_create(&hw_ctx, AV_HWDEVICE_TYPE_DRM, device ? device->c_str() : NULL, NULL, 0); + if (err) + throw std::system_error(err, av_error_category(), "FFMPEG drm hardware context creation failed"); + return av_buffer_ptr(hw_ctx); +} + +std::unordered_map vulkan_drm_format_map = { + {DRM_FORMAT_R8, vk::Format::eR8Unorm}, + {DRM_FORMAT_R16, vk::Format::eR16Unorm}, + {DRM_FORMAT_GR88, vk::Format::eR8G8Unorm}, + {DRM_FORMAT_RG88, vk::Format::eR8G8Unorm}, + {DRM_FORMAT_GR1616, vk::Format::eR16G16Unorm}, + {DRM_FORMAT_RG1616, vk::Format::eR16G16Unorm}, + {DRM_FORMAT_ARGB8888, vk::Format::eB8G8R8A8Unorm}, + {DRM_FORMAT_XRGB8888, vk::Format::eB8G8R8A8Unorm}, + {DRM_FORMAT_ABGR8888, vk::Format::eR8G8B8A8Unorm}, + {DRM_FORMAT_XBGR8888, vk::Format::eR8G8B8A8Unorm}, +}; + +vk::Format drm_to_vulkan_fmt(uint32_t drm_fourcc) +{ + return vulkan_drm_format_map.at(drm_fourcc); +} + +} // namespace + +video_encoder_va::video_encoder_va(wivrn_vk_bundle & vk, xrt::drivers::wivrn::encoder_settings & settings, float fps) : + luma(nullptr), chroma(nullptr) +{ + auto drm_hw_ctx = make_drm_hw_ctx(vk.physical_device); + AVBufferRef * tmp; + int err = av_hwdevice_ctx_create_derived(&tmp, + AV_HWDEVICE_TYPE_VAAPI, + drm_hw_ctx.get(), + 0); + if (err) + throw std::system_error(err, av_error_category(), "FFMPEG vaapi hardware context creation failed"); + av_buffer_ptr vaapi_hw_ctx(tmp); + + settings.video_width += settings.video_width % 2; + settings.video_height += settings.video_height % 2; + + auto vaapi_frame_ctx = make_hwframe_ctx(vaapi_hw_ctx.get(), AV_PIX_FMT_VAAPI, AV_PIX_FMT_NV12, settings.video_width, settings.video_height); + + assert(av_pix_fmt_count_planes(AV_PIX_FMT_NV12) == 2); + + rect = vk::Rect2D{ + .offset = { + .x = settings.offset_x, + .y = settings.offset_y, + }, + .extent = { + .width = settings.width, + .height = settings.height, + }}; + + err = av_hwframe_ctx_create_derived(&tmp, + AV_PIX_FMT_DRM_PRIME, + drm_hw_ctx.get(), + vaapi_frame_ctx.get(), + AV_HWFRAME_MAP_DIRECT); + if (err < 0) + { + throw std::system_error(err, av_error_category(), "Cannot create drm frame context"); + } + drm_frame_ctx = av_buffer_ptr(tmp); + + const char * encoder_name = encoder(settings.codec); + const AVCodec * codec = avcodec_find_encoder_by_name(encoder_name); + if (codec == nullptr) + { + throw std::runtime_error(std::string("Failed to find encoder ") + encoder_name); + } + + encoder_ctx = av_codec_context_ptr(avcodec_alloc_context3(codec)); + if (not encoder_ctx) + { + throw std::runtime_error("failed to allocate VAAPI encoder"); + } + + AVDictionary * opts = nullptr; + av_dict_set(&opts, "async_depth", "1", 0); + for (auto option: settings.options) + { + av_dict_set(&opts, option.first.c_str(), option.second.c_str(), 0); + } + switch (settings.codec) + { + case Codec::h264: + encoder_ctx->profile = FF_PROFILE_H264_MAIN; + break; + case Codec::h265: + encoder_ctx->profile = FF_PROFILE_HEVC_MAIN; + break; + } + + encoder_ctx->width = settings.video_width; + encoder_ctx->height = settings.video_height; + encoder_ctx->time_base = {std::chrono::steady_clock::duration::period::num, + std::chrono::steady_clock::duration::period::den}; + encoder_ctx->framerate = AVRational{(int)fps, 1}; + encoder_ctx->sample_aspect_ratio = AVRational{1, 1}; + encoder_ctx->pix_fmt = AV_PIX_FMT_VAAPI; + encoder_ctx->color_range = AVCOL_RANGE_JPEG; + encoder_ctx->colorspace = AVCOL_SPC_BT709; + encoder_ctx->color_trc = AVCOL_TRC_BT709; + encoder_ctx->color_primaries = AVCOL_PRI_BT709; + settings.range = VK_SAMPLER_YCBCR_RANGE_ITU_FULL; + settings.color_model = VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_709; + encoder_ctx->max_b_frames = 0; + encoder_ctx->bit_rate = settings.bitrate; + encoder_ctx->gop_size = std::numeric_limitsgop_size)>::max(); + encoder_ctx->hw_frames_ctx = av_buffer_ref(vaapi_frame_ctx.get()); + + err = avcodec_open2(encoder_ctx.get(), codec, &opts); + av_dict_free(&opts); + if (err < 0) + { + throw std::system_error(err, av_error_category(), "Cannot open video encoder codec"); + } + + if (encoder_ctx->delay != 0) + { + U_LOG_W("Encoder %d reports a %d frame delay, reprojection will fail", stream_idx, encoder_ctx->delay); + } + + va_frame = make_av_frame(); + err = av_hwframe_get_buffer(vaapi_frame_ctx.get(), va_frame.get(), 0); + if (err < 0) + { + throw std::system_error(err, av_error_category(), "Cannot create vaapi frame"); + } + drm_frame = make_av_frame(); + err = av_hwframe_get_buffer(drm_frame_ctx.get(), drm_frame.get(), 0); + if (err < 0) + { + throw std::system_error(err, av_error_category(), "Cannot create vulkan frame"); + } + av_hwframe_map(va_frame.get(), drm_frame.get(), AV_HWFRAME_MAP_DIRECT); + va_frame->color_range = AVCOL_RANGE_JPEG; + va_frame->colorspace = AVCOL_SPC_BT709; + va_frame->color_primaries = AVCOL_PRI_BT709; + va_frame->color_trc = AVCOL_TRC_BT709; + auto desc = (AVDRMFrameDescriptor *)drm_frame->data[0]; + + const bool has_modifiers = + std::ranges::any_of(vk.device_extensions, [](const char * ext) { + return strcmp(ext, VK_EXT_IMAGE_DRM_FORMAT_MODIFIER_EXTENSION_NAME) == 0; + }); + + assert(desc->nb_layers == desc->nb_objects); + + for (int i = 0; i < desc->nb_layers; ++i) + { + std::vector plane_layouts; + for (int plane = 0; plane < desc->layers[i].nb_planes; ++plane) + { + plane_layouts.push_back({ + .offset = vk::DeviceSize(desc->layers[i].planes[plane].offset), + .rowPitch = vk::DeviceSize(desc->layers[i].planes[plane].pitch), + }); + } + vk::ImageDrmFormatModifierExplicitCreateInfoEXT drm_info{ + .drmFormatModifier = desc->objects[0].format_modifier, + .drmFormatModifierPlaneCount = uint32_t(plane_layouts.size()), + .pPlaneLayouts = plane_layouts.data(), + }; + vk::StructureChain image_create_info{ + vk::ImageCreateInfo{ + .imageType = vk::ImageType::e2D, + .format = drm_to_vulkan_fmt(desc->layers[i].format), + .extent = { + .width = uint32_t(drm_frame->width / (i == 0 ? 1 : 2)), + .height = uint32_t(drm_frame->height / (i == 0 ? 1 : 2)), + .depth = 1, + }, + .mipLevels = 1, + .arrayLayers = 1, + .samples = vk::SampleCountFlagBits::e1, + .tiling = has_modifiers ? vk::ImageTiling::eDrmFormatModifierEXT : (desc->objects[0].format_modifier == DRM_FORMAT_MOD_LINEAR ? vk::ImageTiling::eLinear : vk::ImageTiling::eOptimal), + .usage = vk::ImageUsageFlagBits::eTransferDst, + .sharingMode = vk::SharingMode::eExclusive, + .initialLayout = vk::ImageLayout::eUndefined, + }, + vk::ExternalMemoryImageCreateInfo{ + .pNext = has_modifiers ? &drm_info : nullptr, + .handleTypes = vk::ExternalMemoryHandleTypeFlagBits::eDmaBufEXT, + }, + + }; + auto & image = (i == 0 ? luma : chroma); + image = vk.device.createImage(image_create_info.get()); + + auto memory_props = vk.device.getMemoryFdPropertiesKHR(vk::ExternalMemoryHandleTypeFlagBits::eDmaBufEXT, desc->objects[i].fd); + + vk::StructureChain alloc_info{ + vk::MemoryAllocateInfo{ + .allocationSize = desc->objects[i].size, + .memoryTypeIndex = vk.get_memory_type(memory_props.memoryTypeBits, vk::MemoryPropertyFlagBits::eDeviceLocal), + }, + vk::MemoryDedicatedAllocateInfo{ + .image = *image, + }, + vk::ImportMemoryFdInfoKHR{ + .handleType = vk::ExternalMemoryHandleTypeFlagBits::eDmaBufEXT, + .fd = dup(desc->objects[i].fd), + }, + }; + try + { + mem.push_back(vk.device.allocateMemory(alloc_info.get())); + } + catch (...) + { + close(alloc_info.get().fd); + throw; + } + image.bindMemory(*mem.back(), 0); + } +} + +void video_encoder_va::PresentImage(yuv_converter & src_yuv, vk::raii::CommandBuffer & cmd_buf) +{ + std::array im_barriers = { + vk::ImageMemoryBarrier{ + .srcAccessMask = vk::AccessFlagBits::eNone, + .dstAccessMask = vk::AccessFlagBits::eMemoryWrite, + .oldLayout = vk::ImageLayout::eUndefined, + .newLayout = vk::ImageLayout::eTransferDstOptimal, + .image = *luma, + .subresourceRange = {.aspectMask = vk::ImageAspectFlagBits::eColor, + .baseMipLevel = 0, + .levelCount = 1, + .baseArrayLayer = 0, + .layerCount = 1}, + }, + vk::ImageMemoryBarrier{ + .srcAccessMask = vk::AccessFlagBits::eNone, + .dstAccessMask = vk::AccessFlagBits::eMemoryWrite, + .oldLayout = vk::ImageLayout::eUndefined, + .newLayout = vk::ImageLayout::eTransferDstOptimal, + .image = *chroma, + .subresourceRange = {.aspectMask = vk::ImageAspectFlagBits::eColor, + .baseMipLevel = 0, + .levelCount = 1, + .baseArrayLayer = 0, + .layerCount = 1}, + }, + }; + cmd_buf.pipelineBarrier( + vk::PipelineStageFlagBits::eAllCommands, + vk::PipelineStageFlagBits::eTransfer, + {}, + nullptr, + nullptr, + im_barriers); + + cmd_buf.copyImage( + src_yuv.luma, + vk::ImageLayout::eTransferSrcOptimal, + *luma, + vk::ImageLayout::eTransferDstOptimal, + vk::ImageCopy{ + .srcSubresource = { + .aspectMask = vk::ImageAspectFlagBits::eColor, + .layerCount = 1, + }, + .srcOffset = { + .x = rect.offset.x, + .y = rect.offset.y, + }, + .dstSubresource = { + .aspectMask = vk::ImageAspectFlagBits::eColor, + .layerCount = 1, + }, + .extent = { + .width = rect.extent.width, + .height = rect.extent.height, + .depth = 1, + }}); + + cmd_buf.copyImage( + src_yuv.chroma, + vk::ImageLayout::eTransferSrcOptimal, + *chroma, + vk::ImageLayout::eTransferDstOptimal, + vk::ImageCopy{ + .srcSubresource = { + .aspectMask = vk::ImageAspectFlagBits::eColor, + .layerCount = 1, + }, + .srcOffset = { + .x = rect.offset.x / 2, + .y = rect.offset.y / 2, + }, + .dstSubresource = { + .aspectMask = vk::ImageAspectFlagBits::eColor, + .layerCount = 1, + }, + .extent = { + .width = rect.extent.width / 2, + .height = rect.extent.height / 2, + .depth = 1, + }}); +} + +void video_encoder_va::PushFrame(bool idr, std::chrono::steady_clock::time_point pts) +{ + va_frame->pict_type = idr ? AV_PICTURE_TYPE_I : AV_PICTURE_TYPE_P; + va_frame->pts = pts.time_since_epoch().count(); + int err = avcodec_send_frame(encoder_ctx.get(), va_frame.get()); + if (err) + { + throw std::system_error(err, av_error_category(), "avcodec_send_frame failed"); + } +} diff --git a/server/encoder/ffmpeg/video_encoder_va.h b/server/encoder/ffmpeg/video_encoder_va.h new file mode 100644 index 00000000..bbf9bf52 --- /dev/null +++ b/server/encoder/ffmpeg/video_encoder_va.h @@ -0,0 +1,49 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2022-2024 Guillaume Meunier + * Copyright (C) 2022-2024 Patrick Nicolas + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#pragma once + +#include "video_encoder_ffmpeg.h" +#include "ffmpeg_helper.h" +#include "utils/wivrn_vk_bundle.h" +#include + +namespace xrt::drivers::wivrn +{ +struct encoder_settings; +} + +class video_encoder_va : public VideoEncoderFFMPEG +{ + av_buffer_ptr drm_frame_ctx; + av_frame_ptr va_frame; + av_frame_ptr drm_frame; + vk::Rect2D rect; + vk::raii::Image luma; + vk::raii::Image chroma; + std::vector mem; + +public: + video_encoder_va(wivrn_vk_bundle&, xrt::drivers::wivrn::encoder_settings & settings, float fps); + + void PresentImage(yuv_converter & src_yuv, vk::raii::CommandBuffer & cmd_buf) override; + +protected: + void PushFrame(bool idr, std::chrono::steady_clock::time_point pts) override; +}; diff --git a/server/encoder/shaders/yuv.comp.glsl b/server/encoder/shaders/yuv.comp.glsl new file mode 100644 index 00000000..86dcfbf6 --- /dev/null +++ b/server/encoder/shaders/yuv.comp.glsl @@ -0,0 +1,75 @@ +#version 450 + +layout(binding = 0, rgba8) uniform readonly image2D rgb; +layout(binding = 1, r8) uniform writeonly image2D luminance; + +#define SEMIPLANAR + +#ifdef SEMIPLANAR +layout(binding = 2, rg8) uniform writeonly image2D chroma_uv; +#else +layout(binding = 2, r8) uniform writeonly image2D chroma_u; +layout(binding = 3, r8) uniform writeonly image2D chroma_v; +#endif + +layout(push_constant) uniform PushConstants +{ + mat3 color_space; +} +pcs; + +layout(constant_id = 0) const bool full_range = true; + +layout(local_size_x = 16, local_size_y = 16) in; + +vec3 rgb_to_ycbcr(vec3 color) +{ + vec3 yuv = transpose(pcs.color_space) * color; + + if (full_range) + { + return yuv + vec3(0, 0.5, 0.5); + } + else + { + // The matrix multiplication gives us Y in [0, 1] and Cb and Cr in [-0.5, 0.5]. + // This converts to "MPEG" or "Narrow" in the range [16, 235] and [16, 240]. + return vec3( + (219.0 * yuv.x + 16.0) / 256.0, + (224.0 * yuv.y + 128.0) / 256.0, + (224.0 * yuv.z + 128.0) / 256.0); + } +} + +void main() +{ + vec2 self_id = gl_GlobalInvocationID.xy; + ivec2 coords = ivec2(self_id.x * 2, self_id.y * 2); + ivec2 chroma_coords = coords / 2; + + int j, k; + vec2 uvs[4]; + for (k = 0; k < 2; k += 1) + { + for (j = 0; j < 2; j += 1) + { + ivec2 texel_coords = coords + ivec2(j, k); + vec4 texel = imageLoad(rgb, texel_coords); + vec3 yuv = rgb_to_ycbcr(texel.rgb); + + imageStore(luminance, texel_coords, vec4(yuv.x)); + + int i = k * 2 + j; + uvs[i] = yuv.yz; + } + } + + vec2 uv = mix(mix(uvs[0], uvs[1], 0.5), mix(uvs[2], uvs[3], 0.5), 0.5); + +#ifdef SEMIPLANAR + imageStore(chroma_uv, chroma_coords, vec4(uv.x, uv.y, 0, 0)); +#else + imageStore(chroma_u, chroma_coords, vec4(u.x)); + imageStore(chroma_v, chroma_coords, vec4(v.y)); +#endif +} diff --git a/server/encoder/shaders/yuv_converter.uv.frag.glsl b/server/encoder/shaders/yuv_converter.uv.frag.glsl deleted file mode 100644 index ee67529e..00000000 --- a/server/encoder/shaders/yuv_converter.uv.frag.glsl +++ /dev/null @@ -1,46 +0,0 @@ -/* - * WiVRn VR streaming - * Copyright (C) 2022 Guillaume Meunier - * Copyright (C) 2022 Patrick Nicolas - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -#version 450 - -layout (binding = 0) uniform sampler2D image; - -layout (location = 0) in vec2 pos; - -layout (location = 0) out vec2 uv; - -float gamma(float x) -{ - if (x <= 0.0031308) - return 12.92 * x; - else - return 1.055 * pow(x, 1/2.4) - 0.055; -} - -vec4 gamma4(vec4 x) -{ - return vec4(gamma(x.r), gamma(x.g), gamma(x.b), gamma(x.a)); -} - -void main() { - vec4 rgba = gamma4(texture(image, pos)); - uv.x = 0.5 + rgba.r * -0.1146 + rgba.g * -0.3854 + rgba.b * 0.5; - uv.y = 0.5 + rgba.r * 0.5 + rgba.g * -0.4542 + rgba.b * -0.0458; -} - diff --git a/server/encoder/shaders/yuv_converter.vert.glsl b/server/encoder/shaders/yuv_converter.vert.glsl deleted file mode 100644 index 5dab93bd..00000000 --- a/server/encoder/shaders/yuv_converter.vert.glsl +++ /dev/null @@ -1,27 +0,0 @@ -/* - * WiVRn VR streaming - * Copyright (C) 2022 Guillaume Meunier - * Copyright (C) 2022 Patrick Nicolas - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -#version 450 - -layout (location = 0) out vec2 outUV; - -void main() { - outUV = vec2((gl_VertexIndex << 1) & 2, gl_VertexIndex & 2); // [(0, 0), (2, 0), (0, 2)] - gl_Position = vec4(outUV * 2.0f + -1.0f, 0.0f, 1.0f); // [(-1, -1), (3, -1), (-1, 3)] -} diff --git a/server/encoder/shaders/yuv_converter.y.frag.glsl b/server/encoder/shaders/yuv_converter.y.frag.glsl deleted file mode 100644 index e3e99623..00000000 --- a/server/encoder/shaders/yuv_converter.y.frag.glsl +++ /dev/null @@ -1,44 +0,0 @@ -/* - * WiVRn VR streaming - * Copyright (C) 2022 Guillaume Meunier - * Copyright (C) 2022 Patrick Nicolas - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -#version 450 - -layout (binding = 0) uniform sampler2D image; - -layout (location = 0) in vec2 pos; - -layout (location = 0) out float y; - -float gamma(float x) -{ - if (x <= 0.0031308) - return 12.92 * x; - else - return 1.055 * pow(x, 1/2.4) - 0.055; -} - -vec4 gamma4(vec4 x) -{ - return vec4(gamma(x.r), gamma(x.g), gamma(x.b), gamma(x.a)); -} - -void main() { - vec4 rgba = gamma4(texture(image, pos)); - y = rgba.r * 0.2126 + rgba.g * 0.7152 + rgba.b * 0.0722; -} diff --git a/server/encoder/video_encoder.cpp b/server/encoder/video_encoder.cpp index 49fe1e4c..46e3b6f3 100644 --- a/server/encoder/video_encoder.cpp +++ b/server/encoder/video_encoder.cpp @@ -20,6 +20,7 @@ // Include first because of incompatibility between Eigen and X includes #include "driver/wivrn_session.h" +#include "os/os_time.h" #include "video_encoder.h" #include @@ -30,7 +31,7 @@ #include "video_encoder_nvenc.h" #endif #ifdef WIVRN_USE_VAAPI -#include "ffmpeg/VideoEncoderVA.h" +#include "ffmpeg/video_encoder_va.h" #endif #ifdef WIVRN_USE_X264 #include "video_encoder_x264.h" @@ -40,8 +41,7 @@ namespace xrt::drivers::wivrn { std::unique_ptr VideoEncoder::Create( - vk_bundle * vk, - vk_cmd_pool & pool, + wivrn_vk_bundle & wivrn_vk, encoder_settings & settings, uint8_t stream_idx, int input_width, @@ -53,19 +53,19 @@ std::unique_ptr VideoEncoder::Create( #ifdef WIVRN_USE_X264 if (settings.encoder_name == encoder_x264) { - res = std::make_unique(vk, pool, settings, input_width, input_height, fps); + res = std::make_unique(wivrn_vk, settings, fps); } #endif #ifdef WIVRN_USE_NVENC if (settings.encoder_name == encoder_nvenc) { - res = std::make_unique(vk, settings, fps); + res = std::make_unique(wivrn_vk, settings, fps); } #endif #ifdef WIVRN_USE_VAAPI if (settings.encoder_name == encoder_vaapi) { - res = std::make_unique(vk, settings, fps); + res = std::make_unique(wivrn_vk, settings, fps); } #endif if (not res) @@ -98,8 +98,7 @@ void VideoEncoder::SyncNeeded() void VideoEncoder::Encode(wivrn_session & cnx, const to_headset::video_stream_data_shard::view_info_t & view_info, - uint64_t frame_index, - int index) + uint64_t frame_index) { this->cnx = &cnx; auto target_timestamp = std::chrono::steady_clock::time_point(std::chrono::nanoseconds(view_info.display_time)); @@ -115,7 +114,7 @@ void VideoEncoder::Encode(wivrn_session & cnx, shard.shard_idx = 0; shard.view_info = view_info; - Encode(index, idr, target_timestamp); + Encode(idr, target_timestamp); cnx.dump_time("encode_end", frame_index, os_monotonic_get_ns(), stream_idx, extra); } diff --git a/server/encoder/video_encoder.h b/server/encoder/video_encoder.h index 05b3349b..750392dc 100644 --- a/server/encoder/video_encoder.h +++ b/server/encoder/video_encoder.h @@ -19,19 +19,20 @@ #pragma once -#include "vk/vk_cmd_pool.h" -#include "vk/vk_helpers.h" #include "driver/clock_offset.h" #include #include #include #include #include -#include +#include #include "encoder_settings.h" #include "wivrn_packets.h" +class yuv_converter; +struct wivrn_vk_bundle; + namespace xrt::drivers::wivrn { @@ -63,41 +64,29 @@ private: std::ofstream video_dump; public: - static std::unique_ptr Create(vk_bundle * vk, - vk_cmd_pool & pool, - encoder_settings & settings, - uint8_t stream_idx, - int input_width, - int input_height, - float fps); + static std::unique_ptr Create( + wivrn_vk_bundle &, + encoder_settings & settings, + uint8_t stream_idx, + int input_width, + int input_height, + float fps); virtual ~VideoEncoder() = default; - // set input images to be encoded. - // later referred by index only - virtual void SetImages(int width, - int height, - VkFormat format, - int num_images, - VkImage * images, - VkImageView * views, - VkDeviceMemory * memory) = 0; - - // optional entrypoint, called on present to submit command buffers for the image. - virtual void PresentImage(int index, VkCommandBuffer * out_buffer) - {} + // called on present to submit command buffers for the image. + virtual void PresentImage(yuv_converter & src_yuv, vk::raii::CommandBuffer & cmd_buf) = 0; // The other end lost a frame and needs to resynchronize void SyncNeeded(); void Encode(wivrn_session & cnx, const to_headset::video_stream_data_shard::view_info_t & view_info, - uint64_t frame_index, - int index); + uint64_t frame_index); protected: - // encode the image at provided index. - virtual void Encode(int index, bool idr, std::chrono::steady_clock::time_point target_timestamp) = 0; + // called when command buffer finished executing + virtual void Encode(bool idr, std::chrono::steady_clock::time_point target_timestamp) = 0; void SendData(std::span data, bool end_of_frame); }; diff --git a/server/encoder/video_encoder_nvenc.cpp b/server/encoder/video_encoder_nvenc.cpp index a6e3ac5d..e9c43c34 100644 --- a/server/encoder/video_encoder_nvenc.cpp +++ b/server/encoder/video_encoder_nvenc.cpp @@ -1,7 +1,7 @@ /* * WiVRn VR streaming - * Copyright (C) 2022 Guillaume Meunier - * Copyright (C) 2022 Patrick Nicolas + * Copyright (C) 2022-2024 Guillaume Meunier + * Copyright (C) 2022-2024 Patrick Nicolas * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -18,9 +18,13 @@ */ #include "video_encoder_nvenc.h" +#include "encoder/yuv_converter.h" +#include "util/u_logging.h" +#include "utils/wivrn_vk_bundle.h" -#include "vk/vk_helpers.h" #include +#include +#include #define NVENC_CHECK_NOENCODER(x) \ do \ @@ -60,9 +64,20 @@ namespace xrt::drivers::wivrn { -VideoEncoderNvenc::VideoEncoderNvenc(vk_bundle * vk, const encoder_settings & settings, float fps) : - vk(vk), offset_x(settings.offset_x), offset_y(settings.offset_y), width(settings.width), height(settings.height), codec(settings.codec), fps(fps), bitrate(settings.bitrate) +VideoEncoderNvenc::VideoEncoderNvenc(wivrn_vk_bundle & vk, const encoder_settings & settings, float fps) : + vk(vk), fps(fps), bitrate(settings.bitrate) { + rect = vk::Rect2D{ + .offset = { + .x = settings.offset_x, + .y = settings.offset_y, + }, + .extent = { + .width = settings.width, + .height = settings.height, + }, + }; + pitch = settings.video_width; CU_CHECK(cuInit(0)); CU_CHECK(cuCtxCreate(&cuda, 0, 0)); @@ -70,22 +85,28 @@ VideoEncoderNvenc::VideoEncoderNvenc(vk_bundle * vk, const encoder_settings & se fn.version = NV_ENCODE_API_FUNCTION_LIST_VER; NVENC_CHECK_NOENCODER(NvEncodeAPICreateInstance(&fn)); - NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS params{}; - params.version = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER; - params.deviceType = NV_ENC_DEVICE_TYPE_CUDA; - params.device = cuda; - params.apiVersion = NVENCAPI_VERSION; + { + NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS params{ + .version = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER, + .deviceType = NV_ENC_DEVICE_TYPE_CUDA, + .device = cuda, + .reserved = {}, + .apiVersion = NVENCAPI_VERSION, + .reserved1 = {}, + .reserved2 = {}, + }; - NVENC_CHECK_NOENCODER(fn.nvEncOpenEncodeSessionEx(¶ms, &session_handle)); + NVENC_CHECK_NOENCODER(fn.nvEncOpenEncodeSessionEx(¶ms, &session_handle)); + } uint32_t count; std::vector presets; - auto encodeGUID = codec == video_codec::h264 ? NV_ENC_CODEC_H264_GUID : NV_ENC_CODEC_HEVC_GUID; + auto encodeGUID = settings.codec == video_codec::h264 ? NV_ENC_CODEC_H264_GUID : NV_ENC_CODEC_HEVC_GUID; NVENC_CHECK(fn.nvEncGetEncodePresetCount(session_handle, encodeGUID, &count)); presets.resize(count); NVENC_CHECK(fn.nvEncGetEncodePresetGUIDs(session_handle, encodeGUID, presets.data(), count, &count)); - switch (codec) + switch (settings.codec) { case video_codec::h264: printf("%d H264 presets\n", count); @@ -106,22 +127,7 @@ VideoEncoderNvenc::VideoEncoderNvenc(vk_bundle * vk, const encoder_settings & se cap_param.capsToQuery = NV_ENC_CAPS_SUPPORT_REF_PIC_INVALIDATION; int cap_value; NVENC_CHECK(fn.nvEncGetEncodeCaps(session_handle, encodeGUID, &cap_param, &cap_value)); - supports_frame_invalidation = cap_value; - if (supports_frame_invalidation) - printf("Frame invalidation supported\n"); - else - printf("Frame invalidation not supported\n"); -} -void VideoEncoderNvenc::SetImages(int full_width, - int full_height, - VkFormat format, - int num_images, - VkImage * images, - VkImageView * views, - VkDeviceMemory * memory) -{ - auto encodeGUID = codec == video_codec::h264 ? NV_ENC_CODEC_H264_GUID : NV_ENC_CODEC_HEVC_GUID; // auto presetGUID = codec == video_codec::h264 ? NV_ENC_PRESET_LOW_LATENCY_DEFAULT_GUID : // NV_ENC_PRESET_P7_GUID; #pragma GCC diagnostic push @@ -145,7 +151,7 @@ void VideoEncoderNvenc::SetImages(int full_width, params.gopLength = NVENC_INFINITE_GOPLENGTH; params.frameIntervalP = 1; - switch (codec) + switch (settings.codec) { case video_codec::h264: params.encodeCodecConfig.h264Config.repeatSPSPPS = 1; @@ -163,10 +169,10 @@ void VideoEncoderNvenc::SetImages(int full_width, params2.version = NV_ENC_INITIALIZE_PARAMS_VER; params2.encodeGUID = encodeGUID; params2.presetGUID = presetGUID; - params2.encodeWidth = uint32_t(width); - params2.encodeHeight = uint32_t(height); - params2.darWidth = uint32_t(width); - params2.darHeight = uint32_t(height); + params2.encodeWidth = settings.video_width; + params2.encodeHeight = settings.video_height; + params2.darWidth = settings.video_width; + params2.darHeight = settings.video_height; params2.frameRateNum = (uint32_t)fps; params2.frameRateDen = 1; params2.enableEncodeAsync = 0; @@ -188,73 +194,119 @@ void VideoEncoderNvenc::SetImages(int full_width, NVENC_CHECK(fn.nvEncCreateBitstreamBuffer(session_handle, ¶ms3)); bitstreamBuffer = params3.bitstreamBuffer; - // TODO: cleanup on error - this->images.resize(num_images); - CU_CHECK(cuCtxPushCurrent(cuda)); - for (int i = 0; i < num_images; i++) + vk::DeviceSize buffer_size = pitch * settings.video_height * 3 / 2; + + vk::StructureChain buffer_create_info{ + vk::BufferCreateInfo{ + .size = buffer_size, + .usage = vk::BufferUsageFlagBits::eTransferDst, + }, + vk::ExternalMemoryBufferCreateInfo{ + .handleTypes = vk::ExternalMemoryHandleTypeFlagBitsKHR::eOpaqueFd, + }, + }; + + yuv_buffer = vk::raii::Buffer(vk.device, buffer_create_info.get()); + auto memory_req = yuv_buffer.getMemoryRequirements(); + + vk::StructureChain mem_info{ + vk::MemoryAllocateInfo{ + .allocationSize = buffer_size, + .memoryTypeIndex = vk.get_memory_type(memory_req.memoryTypeBits, vk::MemoryPropertyFlagBits::eDeviceLocal), + }, + vk::MemoryDedicatedAllocateInfo{ + .buffer = *yuv_buffer, + }, + vk::ExportMemoryAllocateInfo{ + .handleTypes = vk::ExternalMemoryHandleTypeFlagBitsKHR::eOpaqueFd, + }, + }; + mem = vk.device.allocateMemory(mem_info.get()); + yuv_buffer.bindMemory(*mem, 0); + + int fd = vk.device.getMemoryFdKHR({ + .memory = *mem, + .handleType = vk::ExternalMemoryHandleTypeFlagBitsKHR::eOpaqueFd, + }); + { - VkMemoryGetFdInfoKHR getinfo{}; - getinfo.sType = VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR; - getinfo.pNext = nullptr; - getinfo.memory = memory[i]; - getinfo.handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT; - - int fd; - VkResult res = vk->vkGetMemoryFdKHR(vk->device, &getinfo, &fd); - VK_CHK_WITH_RET(res, "vkGetMemoryFdKHR", ); - - VkMemoryRequirements memoryreq; - vk->vkGetImageMemoryRequirements(vk->device, images[i], &memoryreq); - - CUexternalMemory extmem; - CUDA_EXTERNAL_MEMORY_HANDLE_DESC param{}; - param.type = CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD; - param.handle.fd = fd; - param.size = memoryreq.size; - param.flags = 0; + CUDA_EXTERNAL_MEMORY_HANDLE_DESC param{ + .type = CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD, + .handle = {.fd = fd}, + .size = memory_req.size, + .flags = 0, + }; CU_CHECK(cuImportExternalMemory(&extmem, ¶m)); - CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC param2{}; - param2.offset = 0; - param2.arrayDesc.Width = (size_t)full_width; - param2.arrayDesc.Height = (size_t)full_height, param2.arrayDesc.Depth = 0; - param2.arrayDesc.Format = CU_AD_FORMAT_UNSIGNED_INT32, param2.arrayDesc.NumChannels = 1; - param2.arrayDesc.Flags = 0; // CUDA_ARRAY3D_SURFACE_LDST, - param2.numLevels = 1; - CU_CHECK(cuExternalMemoryGetMappedMipmappedArray(&this->images[i].cuda_image, extmem, ¶m2)); - CU_CHECK(cuMipmappedArrayGetLevel(&this->images[i].cuda_array, this->images[i].cuda_image, 0)); + CUDA_EXTERNAL_MEMORY_BUFFER_DESC map_param{ + .offset = 0, + .size = buffer_size, + .flags = 0, + }; + CU_CHECK(cuExternalMemoryGetMappedBuffer(&frame, extmem, &map_param)); } - CU_CHECK(cuMemAllocPitch(&frame, &pitch, width * 4, height, 4)); - NV_ENC_REGISTER_RESOURCE param3{}; param3.version = NV_ENC_REGISTER_RESOURCE_VER; param3.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_CUDADEVICEPTR; - param3.width = width; - param3.height = height; + param3.width = rect.extent.width; + param3.height = rect.extent.height; param3.pitch = pitch; param3.resourceToRegister = (void *)frame; - param3.bufferFormat = NV_ENC_BUFFER_FORMAT_ARGB; + param3.bufferFormat = NV_ENC_BUFFER_FORMAT_NV12; param3.bufferUsage = NV_ENC_INPUT_IMAGE; NVENC_CHECK(fn.nvEncRegisterResource(session_handle, ¶m3)); nvenc_resource = param3.registeredResource; CU_CHECK(cuCtxPopCurrent(NULL)); } -void VideoEncoderNvenc::Encode(int index, bool idr, std::chrono::steady_clock::time_point pts) +void VideoEncoderNvenc::PresentImage(yuv_converter & src_yuv, vk::raii::CommandBuffer & cmd_buf) +{ + cmd_buf.copyImageToBuffer( + src_yuv.luma, + vk::ImageLayout::eTransferSrcOptimal, + *yuv_buffer, + vk::BufferImageCopy{ + .bufferRowLength = uint32_t(pitch), + .imageSubresource = { + .aspectMask = vk::ImageAspectFlagBits::eColor, + .layerCount = 1, + }, + .imageOffset = { + .x = rect.offset.x, + .y = rect.offset.y, + }, + .imageExtent = { + .width = rect.extent.width, + .height = rect.extent.height, + .depth = 1, + }}); + cmd_buf.copyImageToBuffer( + src_yuv.chroma, + vk::ImageLayout::eTransferSrcOptimal, + *yuv_buffer, + vk::BufferImageCopy{ + .bufferOffset = pitch * rect.extent.height, + .bufferRowLength = uint32_t(pitch/2), + .imageSubresource = { + .aspectMask = vk::ImageAspectFlagBits::eColor, + .layerCount = 1, + }, + .imageOffset = { + .x = rect.offset.x / 2, + .y = rect.offset.y / 2, + }, + .imageExtent = { + .width = rect.extent.width / 2, + .height = rect.extent.height / 2, + .depth = 1, + }}); + return; +} + +void VideoEncoderNvenc::Encode(bool idr, std::chrono::steady_clock::time_point pts) { CU_CHECK(cuCtxPushCurrent(cuda)); - CUDA_MEMCPY2D copy{}; - copy.srcXInBytes = offset_x * 4; - copy.srcY = offset_y; - copy.srcMemoryType = CU_MEMORYTYPE_ARRAY; - copy.srcArray = images[index].cuda_array; - copy.dstMemoryType = CU_MEMORYTYPE_DEVICE; - copy.dstDevice = frame; - copy.dstPitch = pitch; - copy.WidthInBytes = width * 4; - copy.Height = height; - CU_CHECK(cuMemcpy2D(©)); NV_ENC_MAP_INPUT_RESOURCE param4{}; param4.version = NV_ENC_MAP_INPUT_RESOURCE_VER; @@ -263,9 +315,9 @@ void VideoEncoderNvenc::Encode(int index, bool idr, std::chrono::steady_clock::t NV_ENC_PIC_PARAMS param{}; param.version = NV_ENC_PIC_PARAMS_VER; - param.inputWidth = width; - param.inputHeight = height; - param.inputPitch = width; + param.inputWidth = rect.extent.width; + param.inputHeight = rect.extent.height; + param.inputPitch = pitch; param.encodePicFlags = (uint32_t)(idr ? NV_ENC_PIC_TYPE_IDR : NV_ENC_PIC_TYPE_P); param.frameIdx = 0; param.inputTimeStamp = 0; diff --git a/server/encoder/video_encoder_nvenc.h b/server/encoder/video_encoder_nvenc.h index b62ea61b..db783678 100644 --- a/server/encoder/video_encoder_nvenc.h +++ b/server/encoder/video_encoder_nvenc.h @@ -1,7 +1,7 @@ /* * WiVRn VR streaming - * Copyright (C) 2022 Guillaume Meunier - * Copyright (C) 2022 Patrick Nicolas + * Copyright (C) 2022-2024 Guillaume Meunier + * Copyright (C) 2022-2024 Patrick Nicolas * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -22,51 +22,39 @@ #include "nvEncodeAPI.h" #include "video_encoder.h" #include +#include namespace xrt::drivers::wivrn { class VideoEncoderNvenc : public VideoEncoder { - vk_bundle * vk; + wivrn_vk_bundle& vk; // relevant part of the input image to encode - int offset_x; - int offset_y; - int width; - int height; + vk::Rect2D rect; NV_ENCODE_API_FUNCTION_LIST fn; CUcontext cuda; void * session_handle; NV_ENC_OUTPUT_PTR bitstreamBuffer; - struct image_data - { - CUmipmappedArray cuda_image; - CUarray cuda_array; - }; - std::vector images; + vk::raii::Buffer yuv_buffer = nullptr; + vk::raii::DeviceMemory mem = nullptr; + CUexternalMemory extmem; + + vk::Image luma; + vk::Image chroma; CUdeviceptr frame; size_t pitch; NV_ENC_REGISTERED_PTR nvenc_resource; - video_codec codec; float fps; int bitrate; - bool supports_frame_invalidation; - public: - VideoEncoderNvenc(vk_bundle * vk, const encoder_settings & settings, float fps); + VideoEncoderNvenc(wivrn_vk_bundle& vk, const encoder_settings & settings, float fps); - void SetImages(int width, - int height, - VkFormat format, - int num_images, - VkImage * images, - VkImageView * views, - VkDeviceMemory * memory) override; - - void Encode(int index, bool idr, std::chrono::steady_clock::time_point pts) override; + void PresentImage(yuv_converter & src_yuv, vk::raii::CommandBuffer & cmd_buf) override; + void Encode( bool idr, std::chrono::steady_clock::time_point pts) override; }; } // namespace xrt::drivers::wivrn diff --git a/server/encoder/video_encoder_x264.cpp b/server/encoder/video_encoder_x264.cpp index 586d5f27..269dbe21 100644 --- a/server/encoder/video_encoder_x264.cpp +++ b/server/encoder/video_encoder_x264.cpp @@ -19,6 +19,9 @@ #include "video_encoder_x264.h" +#include "util/u_logging.h" +#include "utils/wivrn_vk_bundle.h" +#include "yuv_converter.h" #include namespace xrt::drivers::wivrn @@ -82,13 +85,9 @@ void VideoEncoderX264::InsertInPendingNal(pending_nal && nal) } VideoEncoderX264::VideoEncoderX264( - vk_bundle * vk, - vk_cmd_pool & pool, + wivrn_vk_bundle & vk, encoder_settings & settings, - int input_width, - int input_height, - float fps) : - vk(vk) + float fps) { if (settings.codec != h264) { @@ -99,18 +98,41 @@ VideoEncoderX264::VideoEncoderX264( // encoder requires width and height to be even settings.video_width += settings.video_width % 2; settings.video_height += settings.video_height % 2; + chroma_width = settings.video_width / 2; - num_mb = ((settings.video_width + 15) / 16) - * ((settings.video_height + 15) / 16); + // FIXME: enforce even values + rect = vk::Rect2D{ + .offset = { + .x = settings.offset_x, + .y = settings.offset_y, + }, + .extent = { + .width = settings.width, + .height = settings.height, + }, + }; - converter = std::make_unique( - vk, - pool, - VkExtent3D{uint32_t(settings.video_width), uint32_t(settings.video_height), 1}, - settings.offset_x, - settings.offset_y, - input_width, - input_height); + num_mb = ((settings.video_width + 15) / 16) * ((settings.video_height + 15) / 16); + + luma = buffer_allocation( + vk.device, + { + .size = vk::DeviceSize(settings.video_width * settings.video_height), + .usage = vk::BufferUsageFlagBits::eTransferDst, + }, + { + .flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT, + .usage = VMA_MEMORY_USAGE_AUTO, + }); + chroma = buffer_allocation( + vk.device, { + .size = vk::DeviceSize(settings.video_width * settings.video_height / 2), + .usage = vk::BufferUsageFlagBits::eTransferDst, + }, + { + .flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT, + .usage = VMA_MEMORY_USAGE_AUTO, + }); x264_param_default_preset(¶m, "ultrafast", "zerolatency"); param.nalu_process = &ProcessCb; @@ -151,23 +173,55 @@ VideoEncoderX264::VideoEncoderX264( pic.img.i_csp = X264_CSP_NV12; pic.img.i_plane = 2; - pic.img.i_stride[0] = converter->y.stride; - pic.img.plane[0] = (uint8_t *)converter->y.mapped_memory; - pic.img.i_stride[1] = converter->uv.stride; - pic.img.plane[1] = (uint8_t *)converter->uv.mapped_memory; + pic.img.i_stride[0] = settings.video_width; + pic.img.plane[0] = (uint8_t *)luma.map(); + pic.img.i_stride[1] = settings.video_width; + pic.img.plane[1] = (uint8_t *)chroma.map(); } -void VideoEncoderX264::SetImages(int width, int height, VkFormat format, int num_images, VkImage * images, VkImageView * views, VkDeviceMemory * memory) +void VideoEncoderX264::PresentImage(yuv_converter & src_yuv, vk::raii::CommandBuffer & cmd_buf) { - converter->SetImages(num_images, images, views); + cmd_buf.copyImageToBuffer( + src_yuv.luma, + vk::ImageLayout::eTransferSrcOptimal, + luma, + vk::BufferImageCopy{ + .bufferRowLength = chroma_width * 2, + .imageSubresource = { + .aspectMask = vk::ImageAspectFlagBits::eColor, + .layerCount = 1, + }, + .imageOffset = { + .x = rect.offset.x, + .y = rect.offset.y, + }, + .imageExtent = { + .width = rect.extent.width, + .height = rect.extent.height, + .depth = 1, + }}); + cmd_buf.copyImageToBuffer( + src_yuv.chroma, + vk::ImageLayout::eTransferSrcOptimal, + chroma, + vk::BufferImageCopy{ + .bufferRowLength = chroma_width, + .imageSubresource = { + .aspectMask = vk::ImageAspectFlagBits::eColor, + .layerCount = 1, + }, + .imageOffset = { + .x = rect.offset.x / 2, + .y = rect.offset.y / 2, + }, + .imageExtent = { + .width = rect.extent.width / 2, + .height = rect.extent.height / 2, + .depth = 1, + }}); } -void VideoEncoderX264::PresentImage(int index, VkCommandBuffer * out_buffer) -{ - *out_buffer = converter->command_buffers[index]; -} - -void VideoEncoderX264::Encode(int index, bool idr, std::chrono::steady_clock::time_point pts) +void VideoEncoderX264::Encode(bool idr, std::chrono::steady_clock::time_point pts) { int num_nal; x264_nal_t * nal; diff --git a/server/encoder/video_encoder_x264.h b/server/encoder/video_encoder_x264.h index 31bee5b8..557409a7 100644 --- a/server/encoder/video_encoder_x264.h +++ b/server/encoder/video_encoder_x264.h @@ -20,11 +20,12 @@ #pragma once #include "video_encoder.h" +#include "vk/allocation.h" #include "x264.h" -#include "yuv_converter.h" #include #include +#include namespace xrt::drivers::wivrn { @@ -34,10 +35,14 @@ class VideoEncoderX264 : public VideoEncoder x264_param_t param = {}; x264_t * enc; - vk_bundle * vk; x264_picture_t pic_in; x264_picture_t pic_out = {}; - std::unique_ptr converter; + + buffer_allocation luma; + buffer_allocation chroma; + uint32_t chroma_width; + + vk::Rect2D rect; struct pending_nal { @@ -52,19 +57,11 @@ class VideoEncoderX264 : public VideoEncoder std::list pending_nals; public: - VideoEncoderX264(vk_bundle * vk, vk_cmd_pool & pool, encoder_settings & settings, int input_width, int input_height, float fps); + VideoEncoderX264(wivrn_vk_bundle& vk, encoder_settings & settings, float fps); - void SetImages(int width, - int height, - VkFormat format, - int num_images, - VkImage * images, - VkImageView * views, - VkDeviceMemory * memory) override; + void PresentImage(yuv_converter & src_yuv, vk::raii::CommandBuffer & cmd_buf) override; - void PresentImage(int index, VkCommandBuffer * out_buffer) override; - - void Encode(int index, bool idr, std::chrono::steady_clock::time_point pts) override; + void Encode(bool idr, std::chrono::steady_clock::time_point pts) override; ~VideoEncoderX264(); diff --git a/server/encoder/yuv_converter.cpp b/server/encoder/yuv_converter.cpp index 08d5593a..322afac6 100644 --- a/server/encoder/yuv_converter.cpp +++ b/server/encoder/yuv_converter.cpp @@ -1,7 +1,7 @@ /* * WiVRn VR streaming - * Copyright (C) 2022 Guillaume Meunier - * Copyright (C) 2022 Patrick Nicolas + * Copyright (C) 2022-2024 Guillaume Meunier + * Copyright (C) 2022-2024 Patrick Nicolas * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -18,395 +18,383 @@ */ #include "yuv_converter.h" -#include + #include -#include -#include -#include #include extern const std::map> shaders; -static const VkFormat y_format = VK_FORMAT_R8_UNORM; -static const VkFormat uv_format = VK_FORMAT_R8G8_UNORM; +// clang-format off +#define SHADER_BGRA 1 +#if SHADER_BGRA +const float COLORSPACE_BT709[3][4] = { +// B G R A +/* Y */{ 0.0722, 0.7152, 0.2126, 0.0}, +/* Cb*/{ 0.5 , -0.3854, -0.1146, 0.0}, +/* Cr*/{-0.0458, -0.4542, 0.5 , 0.0}, +//clang-format: on +}; +#else +const float COLORSPACE_BT709[3][4] = { +// R G B A +/* Y */ { 0.2126, 0.7152, 0.0722, 0.0}, +/* Cb*/ {-0.1146, -0.3854, 0.5 , 0.0}, +/* Cr*/ { 0.5 , -0.4542, -0.0458, 0.0}, +}; +#endif -static int bytes_per_pixel(VkFormat format) +static vk::Format view_format(vk::Format image_format) { - switch (format) + switch (image_format) { - case VK_FORMAT_R8_SRGB: - case VK_FORMAT_R8_UNORM: - return 1; - case VK_FORMAT_R8G8_UNORM: - return 2; + case vk::Format::eB8G8R8A8Srgb: + case vk::Format::eB8G8R8A8Unorm: + // Intel anv appears to get the order wrong + // swizzle components in the colorspace + return vk::Format::eR8G8B8A8Unorm; default: - assert(false); - return 0; - } + throw std::runtime_error("YUV conversion not implemented for " + vk::to_string(image_format)); + }; } -static VkResult create_image(vk_bundle & vk_, VkExtent2D extent, VkFormat format, YuvConverter::image_bundle & bundle) +yuv_converter::yuv_converter() {} +yuv_converter::yuv_converter(vk::PhysicalDevice physical_device, vk::raii::Device & device, vk::Image rgb, vk::Format fmt, vk::Extent2D extent) : + extent(extent), rgb(rgb) { - auto vk = &vk_; - VkResult res = vk_create_image_simple(vk, extent, format, VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, &bundle.image_memory, &bundle.image); - VK_CHK_AND_RET(res, "vk_create_image_simple"); + auto view_fmt = view_format(fmt); - bundle.stride = extent.width * bytes_per_pixel(format); - - if (!vk_buffer_init(vk, extent.height * bundle.stride, VK_BUFFER_USAGE_TRANSFER_DST_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT | VK_MEMORY_PROPERTY_HOST_CACHED_BIT, &bundle.buffer, &bundle.buffer_memory)) + struct plane_t { - return VK_ERROR_OUT_OF_DEVICE_MEMORY; + vk::Format format; + vk::Extent3D extent; + image_allocation & image; + vk::raii::ImageView & view; + }; + + // Description of planes for 4:2:0 subsampling + std::array planes = { + plane_t{ + .format = vk::Format::eR8Unorm, + .extent = {extent.width, extent.height, 1}, + .image = luma, + .view = view_luma, + }, + plane_t{ + .format = vk::Format::eR8G8Unorm, + .extent = {extent.width / 2, extent.height / 2, 1}, + .image = chroma, + .view = view_chroma, + }, + }; + + // Input image view + { + vk::ImageViewUsageCreateInfo usage{ + .usage = vk::ImageUsageFlagBits::eStorage, + }; + view_rgb = device.createImageView( + { + .pNext = &usage, + .image = rgb, + .viewType = vk::ImageViewType::e2D, + .format = view_fmt, + .subresourceRange = { + .aspectMask = vk::ImageAspectFlagBits::eColor, + .levelCount = 1, + .layerCount = 1, + }, + }); } - res = vk->vkMapMemory(vk->device, bundle.buffer_memory, 0, VK_WHOLE_SIZE, 0, &bundle.mapped_memory); - VK_CHK_AND_RET(res, "vkMapMemory"); - - VkImageSubresourceRange subresource_range{}; - subresource_range.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - subresource_range.baseMipLevel = 0; - subresource_range.levelCount = 1; - subresource_range.baseArrayLayer = 0; - subresource_range.layerCount = 1; - - res = vk_create_view(vk, bundle.image, VK_IMAGE_VIEW_TYPE_2D, format, subresource_range, &bundle.view); - VK_CHK_AND_RET(res, "vk_create_view"); - return VK_SUCCESS; -} - -static VkResult shader_load(struct vk_bundle * vk, const std::vector & code, VkShaderModule * out_module) -{ - VkResult ret; - - VkShaderModuleCreateInfo info{}; - info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; - info.codeSize = code.size() * sizeof(uint32_t); - info.pCode = code.data(); - - VkShaderModule module; - ret = vk->vkCreateShaderModule(vk->device, // - &info, // - NULL, // - &module); // - if (ret != VK_SUCCESS) + // Output images + for (auto & plane: planes) { - VK_ERROR(vk, "vkCreateShaderModule failed: %s", vk_result_string(ret)); - return ret; - } - - *out_module = module; - - return VK_SUCCESS; -} - -static void destroy_all(YuvConverter * ptr) -{ - auto vk = &ptr->vk; - vk->vkDestroyDescriptorPool(vk->device, ptr->descriptor_pool, nullptr); - vk->vkDestroyDescriptorSetLayout(vk->device, ptr->descriptor_set_layout, nullptr); - for (auto & comp: {ptr->y, ptr->uv}) - { - vk->vkDestroyPipeline(vk->device, comp.pipeline, nullptr); - vk->vkDestroyFramebuffer(vk->device, comp.frame_buffer, nullptr); - vk->vkDestroyRenderPass(vk->device, comp.render_pass, nullptr); - vk->vkDestroyShaderModule(vk->device, comp.frag, nullptr); - - vk->vkUnmapMemory(vk->device, comp.buffer_memory); - vk->vkDestroyBuffer(vk->device, comp.buffer, nullptr); - vk->vkFreeMemory(vk->device, comp.buffer_memory, nullptr); - vk->vkDestroyImageView(vk->device, comp.view, nullptr); - vk->vkDestroyImage(vk->device, comp.image, nullptr); - vk->vkFreeMemory(vk->device, comp.image_memory, nullptr); - } - vk->vkDestroyPipelineLayout(vk->device, ptr->pipeline_layout, nullptr); - - vk->vkDestroyShaderModule(vk->device, ptr->vert, nullptr); -} - -#define vk_check_throw(fun, res) \ - do \ - { \ - if (res != VK_SUCCESS) \ - { \ - vk_print_result(&this->vk, __FILE__, __LINE__, __func__, res, fun); \ - throw std::runtime_error(fun "failed"); \ - } \ - } while (0) - -YuvConverter::YuvConverter(vk_bundle * vk, vk_cmd_pool & pool, VkExtent3D extent, int offset_x, int offset_y, int input_width, int input_height) : - vk(*vk), pool(pool) -{ - std::unique_ptr deleter(this, destroy_all); - - y.extent = {extent.width, extent.height}; - uv.extent = {extent.width / 2, extent.height / 2}; - - assert(y_format != VK_FORMAT_UNDEFINED); - assert(uv_format != VK_FORMAT_UNDEFINED); - - VkResult res = create_image(*vk, y.extent, y_format, y); - vk_check_throw("create_image (y)", res); - - res = create_image(*vk, uv.extent, uv_format, uv); - vk_check_throw("create_image (uv)", res); - - VkDescriptorSetLayoutBinding samplerLayoutBinding{}; - samplerLayoutBinding.binding = 0; - samplerLayoutBinding.descriptorCount = 1; - samplerLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; - samplerLayoutBinding.pImmutableSamplers = nullptr; - samplerLayoutBinding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT; - - VkDescriptorSetLayoutCreateInfo layoutInfo{}; - layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; - layoutInfo.bindingCount = 1; - layoutInfo.pBindings = &samplerLayoutBinding; - - res = vk->vkCreateDescriptorSetLayout(vk->device, &layoutInfo, nullptr, &descriptor_set_layout); - vk_check_throw("vkCreateDescriptorSetLayout", res); - - VkPipelineLayoutCreateInfo pipelineLayoutInfo{}; - pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; - pipelineLayoutInfo.pSetLayouts = &descriptor_set_layout; - pipelineLayoutInfo.setLayoutCount = 1; - res = vk->vkCreatePipelineLayout(vk->device, &pipelineLayoutInfo, nullptr, &pipeline_layout); - vk_check_throw("vkCreatePipelineLayout", res); - - res = shader_load(vk, shaders.at("yuv_converter.vert"), &vert); - vk_check_throw("shader_load", res); - - res = shader_load(vk, shaders.at("yuv_converter.y.frag"), &y.frag); - vk_check_throw("shader_load", res); - res = - shader_load(vk, shaders.at("yuv_converter.uv.frag"), &uv.frag); - vk_check_throw("shader_load", res); - - for (int i = 0; i < 2; ++i) - { - VkAttachmentDescription colorAttachment{}; - VkAttachmentReference colorAttachmentRef{}; - auto & comp = (i == 0) ? y : uv; - double scale = (i == 0) ? 1.0 : 0.5; - colorAttachment.samples = VK_SAMPLE_COUNT_1_BIT; - colorAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; - colorAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE; - colorAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; - colorAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; - colorAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; - colorAttachment.finalLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; - - colorAttachmentRef.attachment = 0; - colorAttachmentRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; - - colorAttachment.format = (i == 0) ? y_format : uv_format; - - VkSubpassDescription subpass{}; - subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; - subpass.colorAttachmentCount = 1; - subpass.pColorAttachments = &colorAttachmentRef; - - VkRenderPassCreateInfo renderPassInfo{}; - renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO; - renderPassInfo.attachmentCount = 1; - renderPassInfo.pAttachments = &colorAttachment; - renderPassInfo.subpassCount = 1; - renderPassInfo.pSubpasses = &subpass; - - res = vk->vkCreateRenderPass(vk->device, &renderPassInfo, nullptr, &comp.render_pass); - vk_check_throw("vkCreateRenderPass", res); - - VkFramebufferCreateInfo framebufferInfo{}; - framebufferInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO; - framebufferInfo.renderPass = comp.render_pass; - framebufferInfo.attachmentCount = 1; - framebufferInfo.pAttachments = &comp.view; - framebufferInfo.width = comp.extent.width; - framebufferInfo.height = comp.extent.height; - framebufferInfo.layers = 1; - - res = vk->vkCreateFramebuffer(vk->device, &framebufferInfo, nullptr, &comp.frame_buffer); - vk_check_throw("vkCreateFramebuffer", res); - - VkPipelineShaderStageCreateInfo shaderStages[2] = {}; - - shaderStages[0].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; - shaderStages[0].stage = VK_SHADER_STAGE_VERTEX_BIT; - shaderStages[0].module = vert; - shaderStages[0].pName = "main"; - - shaderStages[1].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; - shaderStages[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT; - shaderStages[1].module = comp.frag; - shaderStages[1].pName = "main"; - - VkPipelineVertexInputStateCreateInfo vertexInputInfo{}; - vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; - vertexInputInfo.vertexBindingDescriptionCount = 0; - vertexInputInfo.vertexAttributeDescriptionCount = 0; - - VkPipelineInputAssemblyStateCreateInfo inputAssembly{}; - inputAssembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; - inputAssembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; - inputAssembly.primitiveRestartEnable = VK_FALSE; - - VkViewport viewport{}; - viewport.x = -offset_x * scale; - viewport.y = -offset_y * scale; - viewport.width = input_width * scale; - viewport.height = input_height * scale; - viewport.minDepth = 0.0f; - viewport.maxDepth = 1.0f; - - VkRect2D scissor{}; - scissor.offset = {0, 0}; - scissor.extent = comp.extent; - - VkPipelineViewportStateCreateInfo viewportState{}; - viewportState.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; - viewportState.viewportCount = 1; - viewportState.pViewports = &viewport; - viewportState.scissorCount = 1; - viewportState.pScissors = &scissor; - - VkPipelineRasterizationStateCreateInfo rasterizer{}; - rasterizer.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; - rasterizer.depthClampEnable = VK_FALSE; - rasterizer.polygonMode = VK_POLYGON_MODE_FILL; - rasterizer.lineWidth = 1.0f; - - VkPipelineMultisampleStateCreateInfo multisampling{}; - multisampling.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; - multisampling.sampleShadingEnable = VK_FALSE; - multisampling.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; - - VkPipelineColorBlendAttachmentState colorBlendAttachment{}; - colorBlendAttachment.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT; - colorBlendAttachment.blendEnable = VK_FALSE; - - VkPipelineColorBlendStateCreateInfo colorBlending{}; - colorBlending.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; - colorBlending.logicOpEnable = VK_FALSE; - colorBlending.attachmentCount = 1; - colorBlending.pAttachments = &colorBlendAttachment; - - VkGraphicsPipelineCreateInfo pipelineInfo{}; - pipelineInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; - pipelineInfo.stageCount = std::size(shaderStages); - pipelineInfo.pStages = shaderStages; - pipelineInfo.pVertexInputState = &vertexInputInfo; - pipelineInfo.pInputAssemblyState = &inputAssembly; - pipelineInfo.pViewportState = &viewportState; - pipelineInfo.pRasterizationState = &rasterizer; - pipelineInfo.pMultisampleState = &multisampling; - pipelineInfo.pColorBlendState = &colorBlending; - pipelineInfo.layout = pipeline_layout; - pipelineInfo.renderPass = comp.render_pass; - pipelineInfo.subpass = 0; - - res = vk->vkCreateGraphicsPipelines(vk->device, VK_NULL_HANDLE, 1, &pipelineInfo, nullptr, &comp.pipeline); - vk_check_throw("vkCreateGraphicsPipelines", res); - } - - VkSamplerCreateInfo samplerInfo{}; - samplerInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO; - samplerInfo.magFilter = VK_FILTER_LINEAR; - samplerInfo.minFilter = VK_FILTER_LINEAR; - samplerInfo.anisotropyEnable = VK_FALSE; - res = vk->vkCreateSampler(vk->device, &samplerInfo, nullptr, &sampler); - vk_check_throw("vkCreateSampler", res); - - (void)deleter.release(); -} - -YuvConverter::~YuvConverter() -{ - destroy_all(this); -} - -void YuvConverter::SetImages(int num_images, VkImage * images, VkImageView * views) -{ - // os_mutex_lock(&vk.cmd_pool_mutex); - assert(command_buffers.empty()); - assert(descriptor_sets.empty()); - descriptor_sets.resize(num_images); - VkDescriptorPoolSize poolSize{}; - poolSize.type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; - poolSize.descriptorCount = num_images; - - VkDescriptorPoolCreateInfo poolInfo{}; - poolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; - poolInfo.poolSizeCount = 1; - poolInfo.pPoolSizes = &poolSize; - poolInfo.maxSets = num_images; - VkResult res = vk.vkCreateDescriptorPool(vk.device, &poolInfo, nullptr, &descriptor_pool); - vk_check_throw("vkCreateDescriptorPool", res); - for (int i = 0; i < num_images; ++i) - { - const auto & view = views[i]; - auto & descriptor_set = descriptor_sets[i]; - - VkDescriptorSetAllocateInfo allocInfo{}; - allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; - allocInfo.descriptorPool = descriptor_pool; - allocInfo.descriptorSetCount = 1; - allocInfo.pSetLayouts = &descriptor_set_layout; - res = vk.vkAllocateDescriptorSets(vk.device, &allocInfo, &descriptor_set); - vk_check_throw("vkAllocateDescriptorSets", res); - - VkDescriptorImageInfo imageInfo{}; - imageInfo.imageLayout = VK_IMAGE_LAYOUT_GENERAL; - imageInfo.imageView = view; - imageInfo.sampler = sampler; - - VkWriteDescriptorSet descriptorWrite{}; - descriptorWrite.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; - descriptorWrite.dstSet = descriptor_set; - descriptorWrite.dstBinding = 0; - descriptorWrite.dstArrayElement = 0; - descriptorWrite.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; - descriptorWrite.descriptorCount = 1; - descriptorWrite.pImageInfo = &imageInfo; - - vk.vkUpdateDescriptorSets(vk.device, 1, &descriptorWrite, 0, nullptr); - - VkCommandBuffer cmdBuffer; - res = vk_cmd_pool_create_and_begin_cmd_buffer(&vk, &pool, VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, &cmdBuffer); - vk_check_throw("vk_cmd_pool_create_and_begin_cmd_buffer", res); - - for (auto & comp: {y, uv}) - { - VkRenderPassBeginInfo render_pass_info{}; - render_pass_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; - render_pass_info.renderPass = comp.render_pass; - render_pass_info.framebuffer = comp.frame_buffer; - render_pass_info.renderArea.extent = comp.extent; - - vk.vkCmdBeginRenderPass(cmdBuffer, &render_pass_info, VK_SUBPASS_CONTENTS_INLINE); - vk.vkCmdBindPipeline(cmdBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, comp.pipeline); - vk.vkCmdBindDescriptorSets(cmdBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layout, 0, 1, &descriptor_set, 0, nullptr); - vk.vkCmdDraw(cmdBuffer, 3, 1, 0, 0); - vk.vkCmdEndRenderPass(cmdBuffer); - - if (comp.buffer != VK_NULL_HANDLE) + plane.image = image_allocation( + device, + { + .imageType = vk::ImageType::e2D, + .format = plane.format, + .extent = plane.extent, + .mipLevels = 1, + .arrayLayers = 1, + .samples = vk::SampleCountFlagBits::e1, + .tiling = vk::ImageTiling::eOptimal, + .usage = vk::ImageUsageFlagBits::eStorage | + vk::ImageUsageFlagBits::eTransferSrc, + .sharingMode = vk::SharingMode::eExclusive, + }, { - VkBufferImageCopy copy{}; - copy.bufferOffset = 0; - copy.bufferRowLength = 0; - copy.bufferImageHeight = 0; - copy.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - copy.imageSubresource.mipLevel = 0; - copy.imageSubresource.baseArrayLayer = 0; - copy.imageSubresource.layerCount = 1; - copy.imageOffset = {0, 0, 0}; - copy.imageExtent = {comp.extent.width, comp.extent.height, 1}; - // TODO synchronisation? - vk.vkCmdCopyImageToBuffer(cmdBuffer, comp.image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, comp.buffer, 1, ©); - } - } - - res = vk.vkEndCommandBuffer(cmdBuffer); - vk_check_throw("vkEndCommandBuffer", res); - - command_buffers.push_back(cmdBuffer); + .usage = VMA_MEMORY_USAGE_AUTO, + }); } - // os_mutex_unlock(&vk.cmd_pool_mutex); + + // Output image views + for (auto & plane: planes) + { + plane.view = device.createImageView( + { + .image = plane.image, + .viewType = vk::ImageViewType::e2D, + .format = plane.format, + .subresourceRange = {.aspectMask = vk::ImageAspectFlagBits::eColor, + .baseMipLevel = 0, + .levelCount = 1, + .baseArrayLayer = 0, + .layerCount = 1}, + }); + } + + // Descriptor sets + { + std::array ds_layout_binding{ + vk::DescriptorSetLayoutBinding{ + .binding = 0, + .descriptorType = vk::DescriptorType::eStorageImage, + .descriptorCount = 1, + .stageFlags = vk::ShaderStageFlagBits::eCompute, + }, + vk::DescriptorSetLayoutBinding{ + .binding = 1, + .descriptorType = vk::DescriptorType::eStorageImage, + .descriptorCount = 1, + .stageFlags = vk::ShaderStageFlagBits::eCompute, + }, + vk::DescriptorSetLayoutBinding{ + .binding = 2, + .descriptorType = vk::DescriptorType::eStorageImage, + .descriptorCount = 1, + .stageFlags = vk::ShaderStageFlagBits::eCompute, + }, + }; + ds_layout = device.createDescriptorSetLayout({ + .bindingCount = ds_layout_binding.size(), + .pBindings = ds_layout_binding.data(), + }); + } + + // Pipeline layout + { + vk::PushConstantRange push_constant_range{ + .stageFlags = vk::ShaderStageFlagBits::eCompute, + .offset = 0, + .size = sizeof(COLORSPACE_BT709), + }; + layout = device.createPipelineLayout({ + .setLayoutCount = 1, + .pSetLayouts = &*ds_layout, + .pushConstantRangeCount = 1, + .pPushConstantRanges = &push_constant_range, + }); + } + + // Pipeline + { + auto & spirv = shaders.at("yuv.comp"); + vk::raii::ShaderModule shader(device, { + .codeSize = spirv.size() * sizeof(uint32_t), + .pCode = spirv.data(), + }); + + pipeline = vk::raii::Pipeline(device, nullptr, vk::ComputePipelineCreateInfo{ + .stage = { + .stage = vk::ShaderStageFlagBits::eCompute, + .module = *shader, + .pName = "main", + }, + .layout = *layout, + }); + } + + // Descriptor pool + { + std::array pool_size{ + vk::DescriptorPoolSize{ + .type = vk::DescriptorType::eSampledImage, + .descriptorCount = 1, + }, + vk::DescriptorPoolSize{ + .type = vk::DescriptorType::eStorageImage, + .descriptorCount = 2, + }}; + + dp = device.createDescriptorPool({ + .maxSets = 2, + .poolSizeCount = pool_size.size(), + .pPoolSizes = pool_size.data(), + }); + } + + // Descriptor set + ds = std::move(device.allocateDescriptorSets({ + .descriptorPool = *dp, + .descriptorSetCount = 1, + .pSetLayouts = &*ds_layout, + })[0]); + + vk::DescriptorImageInfo rgb_desc_image_info{ + .imageView = *view_rgb, + .imageLayout = vk::ImageLayout::eGeneral, + }; + vk::DescriptorImageInfo luma_desc_img_info_{ + .imageView = *view_luma, + .imageLayout = vk::ImageLayout::eGeneral, + }; + vk::DescriptorImageInfo chroma_desc_img_info{ + .imageView = *view_chroma, + .imageLayout = vk::ImageLayout::eGeneral, + }; + + device.updateDescriptorSets( + { + vk::WriteDescriptorSet{ + .dstSet = *ds, + .dstBinding = 0, + .descriptorCount = 1, + .descriptorType = vk::DescriptorType::eStorageImage, + .pImageInfo = &rgb_desc_image_info, + }, + vk::WriteDescriptorSet{ + .dstSet = *ds, + .dstBinding = 1, + .descriptorCount = 1, + .descriptorType = vk::DescriptorType::eStorageImage, + .pImageInfo = &luma_desc_img_info_, + }, + vk::WriteDescriptorSet{ + .dstSet = *ds, + .dstBinding = 2, + .descriptorCount = 1, + .descriptorType = vk::DescriptorType::eStorageImage, + .pImageInfo = &chroma_desc_img_info, + }, + }, + nullptr); +} + +void yuv_converter::record_draw_commands( + vk::raii::CommandBuffer & cmd_buf) +{ + std::array im_barriers = { + vk::ImageMemoryBarrier{ + .srcAccessMask = vk::AccessFlagBits::eNone, + .dstAccessMask = vk::AccessFlagBits::eMemoryWrite, + .oldLayout = vk::ImageLayout::eUndefined, + .newLayout = vk::ImageLayout::eGeneral, + .image = luma, + .subresourceRange = {.aspectMask = vk::ImageAspectFlagBits::eColor, + .baseMipLevel = 0, + .levelCount = 1, + .baseArrayLayer = 0, + .layerCount = 1}, + }, + vk::ImageMemoryBarrier{ + .srcAccessMask = vk::AccessFlagBits::eNone, + .dstAccessMask = vk::AccessFlagBits::eMemoryWrite, + .oldLayout = vk::ImageLayout::eUndefined, + .newLayout = vk::ImageLayout::eGeneral, + .image = chroma, + .subresourceRange = {.aspectMask = vk::ImageAspectFlagBits::eColor, + .baseMipLevel = 0, + .levelCount = 1, + .baseArrayLayer = 0, + .layerCount = 1}, + }, + vk::ImageMemoryBarrier{ + .srcAccessMask = vk::AccessFlagBits::eMemoryWrite, + .dstAccessMask = vk::AccessFlagBits::eMemoryRead, + .oldLayout = vk::ImageLayout::ePresentSrcKHR, + .newLayout = vk::ImageLayout::eGeneral, + .image = rgb, + .subresourceRange = {.aspectMask = vk::ImageAspectFlagBits::eColor, + .baseMipLevel = 0, + .levelCount = 1, + .baseArrayLayer = 0, + .layerCount = 1}, + }, + }; + cmd_buf.pipelineBarrier( + vk::PipelineStageFlagBits::eAllCommands, + vk::PipelineStageFlagBits::eComputeShader, + {}, + nullptr, + nullptr, + im_barriers); + + cmd_buf.bindPipeline(vk::PipelineBindPoint::eCompute, *pipeline); + cmd_buf.bindDescriptorSets(vk::PipelineBindPoint::eCompute, *layout, 0, *ds, {}); + cmd_buf.pushConstants(*layout, vk::ShaderStageFlagBits::eCompute, 0, COLORSPACE_BT709); + cmd_buf.dispatch(extent.width / 16, extent.height / 16, 1); + + for (auto & barrier: im_barriers) + { + barrier.srcAccessMask = vk::AccessFlagBits::eMemoryWrite; + barrier.dstAccessMask = vk::AccessFlagBits::eTransferRead; + barrier.oldLayout = vk::ImageLayout::eGeneral; + barrier.newLayout = vk::ImageLayout::eTransferSrcOptimal; + } + cmd_buf.pipelineBarrier( + vk::PipelineStageFlagBits::eComputeShader, + vk::PipelineStageFlagBits::eTransfer, + {}, + nullptr, + nullptr, + std::span{im_barriers.begin(), 2}); +} + +void yuv_converter::assemble_planes(vk::Rect2D rect, vk::raii::CommandBuffer & cmd_buf, vk::Image target) +{ + vk::ImageMemoryBarrier target_barrier{ + .srcAccessMask = vk::AccessFlagBits::eNone, + .dstAccessMask = vk::AccessFlagBits::eMemoryWrite, + .oldLayout = vk::ImageLayout::eUndefined, + .newLayout = vk::ImageLayout::eTransferDstOptimal, + .image = target, + .subresourceRange = {.aspectMask = vk::ImageAspectFlagBits::eColor, + .baseMipLevel = 0, + .levelCount = 1, + .baseArrayLayer = 0, + .layerCount = 1}, + }; + cmd_buf.pipelineBarrier( + vk::PipelineStageFlagBits::eNone, + vk::PipelineStageFlagBits::eTransfer, + {}, + nullptr, + nullptr, + target_barrier); + + cmd_buf.copyImage( + luma, + vk::ImageLayout::eTransferSrcOptimal, + target, + vk::ImageLayout::eTransferDstOptimal, + vk::ImageCopy{ + .srcSubresource = { + .aspectMask = vk::ImageAspectFlagBits::eColor, + .layerCount = 1, + }, + .srcOffset = {rect.offset.x, rect.offset.y, 0}, + .dstSubresource = { + .aspectMask = vk::ImageAspectFlagBits::ePlane0, + .layerCount = 1, + }, + .extent = {extent.width, extent.height, 1}, + }); + cmd_buf.copyImage( + chroma, + vk::ImageLayout::eTransferSrcOptimal, + target, + vk::ImageLayout::eTransferDstOptimal, + vk::ImageCopy{ + .srcSubresource = { + .aspectMask = vk::ImageAspectFlagBits::eColor, + .layerCount = 1, + }, + .srcOffset = {rect.offset.x / 2, rect.offset.y / 2, 0}, + .dstSubresource = { + .aspectMask = vk::ImageAspectFlagBits::ePlane1, + .layerCount = 1, + }, + .extent = {extent.width / 2, extent.height / 2, 1}, + }); } diff --git a/server/encoder/yuv_converter.h b/server/encoder/yuv_converter.h index 0aec44ad..9d38d35d 100644 --- a/server/encoder/yuv_converter.h +++ b/server/encoder/yuv_converter.h @@ -1,7 +1,7 @@ /* * WiVRn VR streaming - * Copyright (C) 2022 Guillaume Meunier - * Copyright (C) 2022 Patrick Nicolas + * Copyright (C) 2022-2024 Guillaume Meunier + * Copyright (C) 2022-2024 Patrick Nicolas * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -19,46 +19,38 @@ #pragma once -#include "vk/vk_cmd_pool.h" -#include "vk/vk_helpers.h" +#include "vk/allocation.h" #include -#include +#include -class YuvConverter +class yuv_converter { + vk::Extent2D extent; + + vk::Image rgb; public: - struct image_bundle - { - VkDeviceMemory image_memory = VK_NULL_HANDLE; - VkImage image = VK_NULL_HANDLE; - VkImageView view = VK_NULL_HANDLE; - VkDeviceMemory buffer_memory = VK_NULL_HANDLE; - VkBuffer buffer = VK_NULL_HANDLE; - void * mapped_memory = nullptr; - VkRenderPass render_pass = VK_NULL_HANDLE; - VkFramebuffer frame_buffer = VK_NULL_HANDLE; - VkShaderModule frag = VK_NULL_HANDLE; - VkPipeline pipeline = VK_NULL_HANDLE; - VkExtent2D extent; - int stride; - }; - vk_bundle & vk; - vk_cmd_pool & pool; - image_bundle y; - image_bundle uv; - VkSampler sampler = VK_NULL_HANDLE; - VkDescriptorSetLayout descriptor_set_layout = VK_NULL_HANDLE; - VkDescriptorPool descriptor_pool = VK_NULL_HANDLE; + image_allocation luma; + image_allocation chroma; +private: + vk::raii::ImageView view_rgb = nullptr; + vk::raii::ImageView view_luma = nullptr; + vk::raii::ImageView view_chroma = nullptr; - VkShaderModule vert = VK_NULL_HANDLE; + vk::raii::DescriptorSetLayout ds_layout = nullptr; + vk::raii::PipelineLayout layout = nullptr; + vk::raii::Pipeline pipeline = nullptr; + vk::raii::DescriptorPool dp = nullptr; + vk::raii::DescriptorSet ds = nullptr; - VkPipelineLayout pipeline_layout = VK_NULL_HANDLE; + std::vector mem; - std::vector command_buffers; - std::vector descriptor_sets; + public: + yuv_converter(); + yuv_converter(vk::PhysicalDevice, vk::raii::Device& device, vk::Image rgb, vk::Format format, vk::Extent2D extent); - YuvConverter(vk_bundle * vk, vk_cmd_pool & pool, VkExtent3D extent, int offset_x, int offset_y, int input_width, int input_height); - ~YuvConverter(); + // Converts the given image to yuv, stored in luma and chroma images. + // The output images will be in transfer src optimal layout + void record_draw_commands(vk::raii::CommandBuffer& cmd_buf); - void SetImages(int num_images, VkImage * images, VkImageView * views); + void assemble_planes(vk::Rect2D, vk::raii::CommandBuffer&, vk::Image target); }; diff --git a/server/utils/wivrn_vk_bundle.cpp b/server/utils/wivrn_vk_bundle.cpp new file mode 100644 index 00000000..ffcc76a0 --- /dev/null +++ b/server/utils/wivrn_vk_bundle.cpp @@ -0,0 +1,163 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2024 Guillaume Meunier + * Copyright (C) 2024 Patrick Nicolas + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include "vk/vk_helpers.h" + +#include "wivrn_vk_bundle.h" + +#include + +wivrn_vk_bundle::wivrn_vk_bundle(vk_bundle & vk, std::span requested_instance_extensions, std::span requested_device_extensions) : + instance(vk_ctx, vk.instance), + physical_device(instance, vk.physical_device), + device(physical_device, vk.device), + allocator({ + .physicalDevice = vk.physical_device, + .device = vk.device, + .instance = vk.instance, + .vulkanApiVersion = VK_MAKE_VERSION(1, 0, 0), // FIXME: sync with wivrn_session.cpp + }), + queue(device, vk.queue_family_index, vk.queue_index), + queue_family_index(vk.queue_family_index) +{ + // This is manually synced with monado code + + // Instance extensions +#ifdef VK_EXT_display_surface_counter + if (vk.has_EXT_display_surface_counter) + instance_extensions.push_back(VK_EXT_DISPLAY_SURFACE_COUNTER_EXTENSION_NAME); +#endif +#ifdef VK_EXT_swapchain_colorspace + if (vk.has_EXT_swapchain_colorspace) + instance_extensions.push_back(VK_EXT_SWAPCHAIN_COLORSPACE_EXTENSION_NAME); +#endif +#ifdef VK_EXT_debug_utils + if (vk.has_EXT_debug_utils) + instance_extensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME); +#endif + for (auto & ext: vk_ctx.enumerateInstanceExtensionProperties()) + { + for (const char * requested: requested_instance_extensions) + { + if (ext.extensionName == std::string(requested)) + { + instance_extensions.push_back(requested); + break; + } + } + } + + // Device extensions +#ifdef VK_KHR_external_fence_fd + if (vk.has_KHR_external_fence_fd) + device_extensions.push_back(VK_KHR_EXTERNAL_FENCE_FD_EXTENSION_NAME); +#endif +#ifdef VK_KHR_external_semaphore_fd + if (vk.has_KHR_external_semaphore_fd) + device_extensions.push_back(VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME); +#endif +#ifdef VK_KHR_format_feature_flags2 + if (vk.has_KHR_format_feature_flags2) + device_extensions.push_back(VK_KHR_FORMAT_FEATURE_FLAGS_2_EXTENSION_NAME); +#endif +#ifdef VK_KHR_global_priority + if (vk.has_KHR_global_priority) + device_extensions.push_back(VK_KHR_GLOBAL_PRIORITY_EXTENSION_NAME); +#endif +#ifdef VK_KHR_image_format_list + if (vk.has_KHR_image_format_list) + device_extensions.push_back(VK_KHR_IMAGE_FORMAT_LIST_EXTENSION_NAME); +#endif +#ifdef VK_KHR_maintenance1 + if (vk.has_KHR_maintenance1) + device_extensions.push_back(VK_KHR_MAINTENANCE_1_EXTENSION_NAME); +#endif +#ifdef VK_KHR_maintenance2 + if (vk.has_KHR_maintenance2) + device_extensions.push_back(VK_KHR_MAINTENANCE_2_EXTENSION_NAME); +#endif +#ifdef VK_KHR_maintenance3 + if (vk.has_KHR_maintenance3) + device_extensions.push_back(VK_KHR_MAINTENANCE_3_EXTENSION_NAME); +#endif +#ifdef VK_KHR_maintenance4 + if (vk.has_KHR_maintenance4) + device_extensions.push_back(VK_KHR_MAINTENANCE_4_EXTENSION_NAME); +#endif +#ifdef VK_KHR_timeline_semaphore + if (vk.has_KHR_timeline_semaphore) + device_extensions.push_back(VK_KHR_TIMELINE_SEMAPHORE_EXTENSION_NAME); +#endif +#ifdef VK_EXT_calibrated_timestamps + if (vk.has_EXT_calibrated_timestamps) + device_extensions.push_back(VK_EXT_CALIBRATED_TIMESTAMPS_EXTENSION_NAME); +#endif +#ifdef VK_EXT_display_control + if (vk.has_EXT_display_control) + device_extensions.push_back(VK_EXT_DISPLAY_CONTROL_EXTENSION_NAME); +#endif +#ifdef VK_EXT_external_memory_dma_buf + if (vk.has_EXT_external_memory_dma_buf) + device_extensions.push_back(VK_EXT_EXTERNAL_MEMORY_DMA_BUF_EXTENSION_NAME); +#endif +#ifdef VK_EXT_global_priority + if (vk.has_EXT_global_priority) + device_extensions.push_back(VK_EXT_GLOBAL_PRIORITY_EXTENSION_NAME); +#endif +#ifdef VK_EXT_image_drm_format_modifier + if (vk.has_EXT_image_drm_format_modifier) + device_extensions.push_back(VK_EXT_IMAGE_DRM_FORMAT_MODIFIER_EXTENSION_NAME); +#endif +#ifdef VK_EXT_robustness2 + if (vk.has_EXT_robustness2) + device_extensions.push_back(VK_EXT_ROBUSTNESS_2_EXTENSION_NAME); +#endif +#ifdef VK_GOOGLE_display_timing + if (vk.has_GOOGLE_display_timing) + device_extensions.push_back(VK_GOOGLE_DISPLAY_TIMING_EXTENSION_NAME); +#endif + + for (auto & ext: physical_device.enumerateDeviceExtensionProperties()) + { + for (const char * requested: requested_device_extensions) + { + if (ext.extensionName == std::string(requested)) + { + device_extensions.push_back(requested); + break; + } + } + } +} + +uint32_t wivrn_vk_bundle::get_memory_type(uint32_t type_bits, vk::MemoryPropertyFlags memory_props) +{ + auto mem_prop = physical_device.getMemoryProperties(); + + for (uint32_t i = 0; i < mem_prop.memoryTypeCount; ++i) + { + if ((type_bits >> i) & 1) + { + if ((mem_prop.memoryTypes[i].propertyFlags & memory_props) == + memory_props) + return i; + } + } + throw std::runtime_error("Failed to get memory type"); +} diff --git a/server/utils/wivrn_vk_bundle.h b/server/utils/wivrn_vk_bundle.h new file mode 100644 index 00000000..584594e4 --- /dev/null +++ b/server/utils/wivrn_vk_bundle.h @@ -0,0 +1,69 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2024 Guillaume Meunier + * Copyright (C) 2024 Patrick Nicolas + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#pragma once + +#include "vk/vk_allocator.h" +#include +#include +#include +#include + +struct vk_bundle; + +// to use vk::raii we need a vk::raii::{Instance,PhysicalDevice,Device} +// however we don't own it, so deactivate the destructor +struct raii_instance : public vk::raii::Instance +{ + raii_instance(vk::raii::Context &ctx, VkInstance i) : + vk::raii::Instance(ctx, i) {} + raii_instance & operator=(raii_instance &&) noexcept = default; + ~raii_instance() + { + release(); + } +}; +struct raii_device : public vk::raii::Device +{ + raii_device(vk::raii::PhysicalDevice & p, VkDevice d) : + vk::raii::Device(p, d) {} + raii_device & operator=(raii_device &&) noexcept = default; + ~raii_device() + { + release(); + } +}; + +struct wivrn_vk_bundle +{ + vk::raii::Context vk_ctx; + raii_instance instance; + vk::raii::PhysicalDevice physical_device; + raii_device device; + vk_allocator allocator; + vk::raii::Queue queue; + uint32_t queue_family_index; + + std::vector instance_extensions; + std::vector device_extensions; + + wivrn_vk_bundle(vk_bundle& vk, std::span requested_instance_extensions, std::span requested_device_extensions); + + uint32_t get_memory_type(uint32_t type_bits, vk::MemoryPropertyFlags memory_props); +};