From 9f8cd1f627dbc4b553d1287e1413ab16b1024492 Mon Sep 17 00:00:00 2001 From: Patrick Nicolas Date: Sat, 2 Aug 2025 22:56:50 +0200 Subject: [PATCH] WIP pyrowave --- client/CMakeLists.txt | 8 +- client/application.cpp | 19 +- client/application.h | 2 +- client/decoder/pyrowave/decoder.cpp | 273 +++ client/decoder/pyrowave/decoder.h | 140 ++ client/decoder/shard_accumulator.cpp | 26 +- client/decoder/shard_accumulator.h | 8 +- client/scenes/stream.cpp | 2 +- cmake/CompileGLSL.cmake | 30 +- common/CMakeLists.txt | 5 + common/pyrowave/CMakeLists.txt | 15 + common/pyrowave/pyrowave_common.cpp | 256 +++ common/pyrowave/pyrowave_common.h | 264 +++ common/pyrowave/pyrowave_decoder.cpp | 825 +++++++++ common/pyrowave/pyrowave_decoder.h | 58 + common/pyrowave/pyrowave_encoder.cpp | 1647 +++++++++++++++++ common/pyrowave/pyrowave_encoder.h | 90 + .../shaders/analyze_rate_control.comp | 222 +++ .../analyze_rate_control_finalize.comp | 39 + common/pyrowave/shaders/block_packing.comp | 380 ++++ common/pyrowave/shaders/constants.h | 10 + common/pyrowave/shaders/dwt.h | 241 +++ common/pyrowave/shaders/dwt_0.comp | 10 + common/pyrowave/shaders/dwt_1.comp | 10 + common/pyrowave/shaders/dwt_2.comp | 10 + common/pyrowave/shaders/dwt_common.h | 52 + common/pyrowave/shaders/dwt_quant_scale.h | 21 + common/pyrowave/shaders/dwt_swizzle.h | 23 + common/pyrowave/shaders/idwt.h | 206 +++ common/pyrowave/shaders/idwt_0.comp | 13 + common/pyrowave/shaders/idwt_1.comp | 13 + common/pyrowave/shaders/idwt_2.comp | 13 + common/pyrowave/shaders/power_to_db.comp | 33 + .../shaders/resolve_rate_control.comp | 80 + common/pyrowave/shaders/wavelet_dequant.comp | 263 +++ common/pyrowave/shaders/wavelet_quant.comp | 317 ++++ common/pyrowave/shaders/yuv2rgb.frag | 60 + common/wivrn_packets.h | 1 + server/CMakeLists.txt | 6 + server/driver/configuration.cpp | 2 + server/driver/wivrn_comp_target.cpp | 1 + server/encoder/encoder_settings.cpp | 18 + server/encoder/ffmpeg/video_encoder_va.cpp | 4 + server/encoder/video_encoder.cpp | 11 + server/encoder/video_encoder.h | 1 + server/encoder/video_encoder_nvenc.cpp | 4 + server/encoder/video_encoder_pyrowave.cpp | 173 ++ server/encoder/video_encoder_pyrowave.h | 51 + 48 files changed, 5933 insertions(+), 23 deletions(-) create mode 100644 client/decoder/pyrowave/decoder.cpp create mode 100644 client/decoder/pyrowave/decoder.h create mode 100644 common/pyrowave/CMakeLists.txt create mode 100644 common/pyrowave/pyrowave_common.cpp create mode 100644 common/pyrowave/pyrowave_common.h create mode 100644 common/pyrowave/pyrowave_decoder.cpp create mode 100644 common/pyrowave/pyrowave_decoder.h create mode 100644 common/pyrowave/pyrowave_encoder.cpp create mode 100644 common/pyrowave/pyrowave_encoder.h create mode 100644 common/pyrowave/shaders/analyze_rate_control.comp create mode 100644 common/pyrowave/shaders/analyze_rate_control_finalize.comp create mode 100644 common/pyrowave/shaders/block_packing.comp create mode 100644 common/pyrowave/shaders/constants.h create mode 100644 common/pyrowave/shaders/dwt.h create mode 100644 common/pyrowave/shaders/dwt_0.comp create mode 100644 common/pyrowave/shaders/dwt_1.comp create mode 100644 common/pyrowave/shaders/dwt_2.comp create mode 100644 common/pyrowave/shaders/dwt_common.h create mode 100644 common/pyrowave/shaders/dwt_quant_scale.h create mode 100644 common/pyrowave/shaders/dwt_swizzle.h create mode 100644 common/pyrowave/shaders/idwt.h create mode 100644 common/pyrowave/shaders/idwt_0.comp create mode 100644 common/pyrowave/shaders/idwt_1.comp create mode 100644 common/pyrowave/shaders/idwt_2.comp create mode 100644 common/pyrowave/shaders/power_to_db.comp create mode 100644 common/pyrowave/shaders/resolve_rate_control.comp create mode 100644 common/pyrowave/shaders/wavelet_dequant.comp create mode 100644 common/pyrowave/shaders/wavelet_quant.comp create mode 100644 common/pyrowave/shaders/yuv2rgb.frag create mode 100644 server/encoder/video_encoder_pyrowave.cpp create mode 100644 server/encoder/video_encoder_pyrowave.h diff --git a/client/CMakeLists.txt b/client/CMakeLists.txt index 1311f36d..1bb2e9c6 100644 --- a/client/CMakeLists.txt +++ b/client/CMakeLists.txt @@ -45,7 +45,7 @@ if(ANDROID) file(GLOB PLATFORM_SOURCE CONFIGURE_DEPENDS "android/*.cpp" "audio/android/*.cpp" - "decoder/android/*.cpp" + #"decoder/android/*.cpp" ) target_sources(wivrn PRIVATE ${PLATFORM_SOURCE}) else() @@ -63,7 +63,7 @@ else() file(GLOB PLATFORM_SOURCE CONFIGURE_DEPENDS "decoder/ffmpeg/*.cpp") - target_sources(wivrn PRIVATE ${PLATFORM_SOURCE}) + #target_sources(wivrn PRIVATE ${PLATFORM_SOURCE}) file(CREATE_LINK ${CMAKE_CURRENT_BINARY_DIR}/share ${CMAKE_BINARY_DIR}/share SYMBOLIC) endif() @@ -80,6 +80,7 @@ set_target_properties(wivrn PROPERTIES CXX_VISIBILITY_PRESET hidden) file(GLOB LOCAL_SOURCE CONFIGURE_DEPENDS "*.cpp" "decoder/*.cpp" + "decoder/pyrowave/*.cpp" "scenes/*.cpp" "utils/*.cpp" "vk/*.cpp" @@ -89,7 +90,7 @@ file(GLOB LOCAL_SOURCE CONFIGURE_DEPENDS file(GLOB_RECURSE VULKAN_SHADERS CONFIGURE_DEPENDS "*.glsl") target_sources(wivrn PRIVATE ${LOCAL_SOURCE} ${VULKAN_SHADERS}) -wivrn_compile_glsl(wivrn ${VULKAN_SHADERS}) +wivrn_compile_glsl(wivrn SHADERS ${VULKAN_SHADERS}) target_link_libraries(wivrn Boost::locale @@ -106,6 +107,7 @@ target_link_libraries(wivrn Vulkan::Vulkan wivrn-common wivrn-external + pyrowave ) if (WIVRN_USE_LIBKTX) diff --git a/client/application.cpp b/client/application.cpp index 22de1aee..d174a59b 100644 --- a/client/application.cpp +++ b/client/application.cpp @@ -758,6 +758,10 @@ void application::initialize_vulkan() spdlog::info(" {} (version {})", extension_name, spec_version); vk_device_extensions.push_back(VK_KHR_PUSH_DESCRIPTOR_EXTENSION_NAME); + vk_device_extensions.push_back(VK_KHR_8BIT_STORAGE_EXTENSION_NAME); + vk_device_extensions.push_back(VK_KHR_16BIT_STORAGE_EXTENSION_NAME); + vk_device_extensions.push_back(VK_EXT_SUBGROUP_SIZE_CONTROL_EXTENSION_NAME); + vk_device_extensions.push_back(VK_KHR_SHADER_FLOAT16_INT8_EXTENSION_NAME); optional_device_extensions.emplace(VK_IMG_FILTER_CUBIC_EXTENSION_NAME); optional_device_extensions.emplace(VK_KHR_CREATE_RENDERPASS_2_EXTENSION_NAME); optional_device_extensions.emplace(VK_KHR_FRAGMENT_SHADING_RATE_EXTENSION_NAME); @@ -880,11 +884,22 @@ void application::initialize_vulkan() .pEnabledFeatures = &device_features, }, vk::PhysicalDeviceFragmentShadingRateFeaturesKHR{}, -#ifdef __ANDROID__ vk::PhysicalDeviceSamplerYcbcrConversionFeaturesKHR{ .samplerYcbcrConversion = VK_TRUE, }, -#endif + vk::PhysicalDevice8BitStorageFeatures{ + .storageBuffer8BitAccess = true, + }, + vk::PhysicalDevice16BitStorageFeatures{ + .storageBuffer16BitAccess = true, + }, + vk::PhysicalDeviceSubgroupSizeControlFeaturesEXT{ + .subgroupSizeControl = true, + .computeFullSubgroups = true, + }, + vk::PhysicalDeviceFloat16Int8FeaturesKHR{ + .shaderFloat16 = true, + }, }; if (utils::contains(vk_device_extensions, VK_KHR_CREATE_RENDERPASS_2_EXTENSION_NAME) and diff --git a/client/application.h b/client/application.h index 368983fa..b81af158 100644 --- a/client/application.h +++ b/client/application.h @@ -62,7 +62,7 @@ struct application_info int version = VK_MAKE_VERSION(1, 0, 0); XrFormFactor formfactor = XR_FORM_FACTOR_HEAD_MOUNTED_DISPLAY; XrViewConfigurationType viewconfig = XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO; - XrVersion min_vulkan_version = XR_MAKE_VERSION(1, 1, 0); + XrVersion min_vulkan_version = XR_MAKE_VERSION(1, 3, 0); #ifdef __ANDROID__ android_app * native_app; diff --git a/client/decoder/pyrowave/decoder.cpp b/client/decoder/pyrowave/decoder.cpp new file mode 100644 index 00000000..2dc66c3f --- /dev/null +++ b/client/decoder/pyrowave/decoder.cpp @@ -0,0 +1,273 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2025 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 "decoder.h" + +#include "application.h" +#include "scenes/stream.h" + +namespace wivrn +{ +decoder::decoder( + vk::raii::Device & device, + vk::raii::PhysicalDevice & physical_device, + uint32_t vk_queue_family_index, + const wivrn::to_headset::video_stream_description::item & description, + float fps, + uint8_t stream_index, + std::weak_ptr scene, + shard_accumulator * accumulator) : + ycbcr_conversion(device, { + .format = vk::Format::eG8B8R83Plane420Unorm, + .ycbcrModel = vk::SamplerYcbcrModelConversion(description.color_model.value_or(VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_709)), + .ycbcrRange = vk::SamplerYcbcrRange(description.range.value_or(VK_SAMPLER_YCBCR_RANGE_ITU_FULL)), + .chromaFilter = vk::Filter::eNearest, + }), + sampler_(device, vk::StructureChain{ + vk::SamplerCreateInfo{ + .magFilter = vk::Filter::eNearest, + .minFilter = vk::Filter::eNearest, + .mipmapMode = vk::SamplerMipmapMode::eNearest, + .addressModeU = vk::SamplerAddressMode::eClampToEdge, + .addressModeV = vk::SamplerAddressMode::eClampToEdge, + .addressModeW = vk::SamplerAddressMode::eClampToEdge, + .maxAnisotropy = 1, + }, + vk::SamplerYcbcrConversionInfo{ + .conversion = *ycbcr_conversion, + }, + } + .get()), + description(description), + weak_scene(scene), + accumulator(accumulator), + command_pool(device, vk::CommandPoolCreateInfo{ + .flags = vk::CommandPoolCreateFlagBits::eResetCommandBuffer, + .queueFamilyIndex = vk_queue_family_index, + }), + cmd_buf(std::move(device.allocateCommandBuffers(vk::CommandBufferAllocateInfo{ + .commandPool = *command_pool, + .commandBufferCount = 1, + })[0])), + fence(device, vk::FenceCreateInfo{.flags = vk::FenceCreateFlagBits::eSignaled}), + dec(physical_device, device, description.width, description.height, PyroWave::ChromaSubsampling::Chroma420) +{ + std::array formats = { + vk::Format::eR8Unorm, + vk::Format::eG8B8R83Plane420Unorm, + }; + vk::ImageFormatListCreateInfo formats_info{ + .viewFormatCount = formats.size(), + .pViewFormats = formats.data(), + }; + size_t i = 0; + for (auto & item: image_pool) + { + item.image = image_allocation( + device, + vk::ImageCreateInfo{ + .pNext = &formats_info, + .flags = vk::ImageCreateFlagBits::eExtendedUsage | vk::ImageCreateFlagBits::eMutableFormat, + .imageType = vk::ImageType::e2D, + .format = formats.back(), + .extent = { + .width = description.width, + .height = description.height, + .depth = 1, + }, + .mipLevels = 1, + .arrayLayers = 1, + .tiling = vk::ImageTiling::eOptimal, + .usage = vk::ImageUsageFlagBits::eSampled | vk::ImageUsageFlagBits::eStorage, + }, + { + .usage = VMA_MEMORY_USAGE_AUTO, + }, + std::format("pyrowave decoder {} image {}", stream_index, i)); + + vk::SamplerYcbcrConversionInfo conv{ + .conversion = *ycbcr_conversion, + }; + vk::ImageViewUsageCreateInfo usage{ + .pNext = &conv, + .usage = vk::ImageUsageFlagBits::eSampled, + }; + vk::ImageViewCreateInfo view_info{ + .pNext = &usage, + .image = item.image, + .viewType = vk::ImageViewType::e2D, + .format = formats.back(), + .subresourceRange = { + .aspectMask = vk::ImageAspectFlagBits::eColor, + .levelCount = 1, + .layerCount = 1, + }, + }; + item.view_full = vk::raii::ImageView(device, view_info); + + usage.pNext = nullptr; + usage.usage |= vk::ImageUsageFlagBits::eStorage; + view_info.format = formats[0]; + view_info.subresourceRange.aspectMask = vk::ImageAspectFlagBits::ePlane0; + item.view_y = vk::raii::ImageView(device, view_info); + view_info.subresourceRange.aspectMask = vk::ImageAspectFlagBits::ePlane1; + item.view_cb = vk::raii::ImageView(device, view_info); + view_info.subresourceRange.aspectMask = vk::ImageAspectFlagBits::ePlane2; + + item.view_cr = vk::raii::ImageView(device, view_info); + ++i; + } + + worker = std::thread([&] { worker_function(); }); +} + +decoder::~decoder() +{ + exiting = true; + pending.lock().notify_all(); + if (worker.joinable()) + worker.join(); +} + +void decoder::push_data(std::span> data, uint64_t frame_index, bool partial) +{ + if (data.size() == 1) + { + dec.push_packet(data[0].data(), data[0].size()); + return; + } + // FIXME: accept sparse data in push_packet + std::vector flat; + for (const auto & i: data) + flat.insert(flat.end(), i.begin(), i.end()); + dec.push_packet(flat.data(), flat.size()); +} + +void decoder::frame_completed( + const from_headset::feedback & feedback, + const to_headset::video_stream_data_shard::view_info_t & view_info) +{ + auto item = get_free(); + if (not item) + { + spdlog::warn("No image available in pool, discard frame"); + dec.clear(); + return; + } + std::array views{*item->view_y, *item->view_cb, *item->view_cr}; + auto res = dec.device.waitForFences(*fence, true, UINT64_MAX); + if (res != vk::Result::eSuccess) + spdlog::warn("waitForFences failed"); + auto locked = pending.lock(); + dec.device.resetFences(*fence); + cmd_buf.reset(); + cmd_buf.begin({.flags = vk::CommandBufferUsageFlagBits::eOneTimeSubmit}); + + if (item->current_layout != vk::ImageLayout::eGeneral) + { + item->current_layout = vk::ImageLayout::eGeneral; + vk::ImageMemoryBarrier barrier{ + .srcAccessMask = vk::AccessFlagBits::eNone, + .dstAccessMask = vk::AccessFlagBits::eMemoryWrite, + .oldLayout = vk::ImageLayout::eUndefined, + .newLayout = vk::ImageLayout::eGeneral, + .image = item->image, + .subresourceRange = { + .aspectMask = vk::ImageAspectFlagBits::eColor, + .levelCount = 1, + .layerCount = 1, + }, + }; + cmd_buf.pipelineBarrier( + vk::PipelineStageFlagBits::eAllCommands, + vk::PipelineStageFlagBits::eTransfer, + {}, + {}, + {}, + barrier); + } + dec.decode(cmd_buf, views); + cmd_buf.end(); + + application::get_queue().lock()->submit( + vk::SubmitInfo{ + .commandBufferCount = 1, + .pCommandBuffers = &*cmd_buf, + }, + *fence); + + *locked = { + .feedback = feedback, + .view_info = view_info, + .img = item, + }; + locked.notify_all(); +} + +decoder::image * decoder::get_free() +{ + for (auto & item: image_pool) + { + if (item.free.exchange(false)) + return &item; + } + return nullptr; +} + +void decoder::worker_function() +{ + while (not exiting) + { + auto locked = pending.lock(); + locked.wait([&]() { return exiting or locked->img != nullptr; }); + if (exiting) + return; + + try + { + auto res = dec.device.waitForFences(*fence, true, UINT64_MAX); + if (res != vk::Result::eSuccess) + spdlog::warn("waitForFences failed"); + + auto scene = weak_scene.lock(); + scene->push_blit_handle( + accumulator, + std::make_shared( + locked->feedback, + locked->view_info, + locked->img->view_full, + locked->img->image, + &locked->img->current_layout, + locked->img->free)); + } + catch (...) + {} + locked->img = nullptr; + } +} + +std::vector decoder::supported_codecs() +{ + return {video_codec::pyrowave}; +} + +decoder::blit_handle::~blit_handle() +{ + free = true; +} +} // namespace wivrn diff --git a/client/decoder/pyrowave/decoder.h b/client/decoder/pyrowave/decoder.h new file mode 100644 index 00000000..3ce7dc1f --- /dev/null +++ b/client/decoder/pyrowave/decoder.h @@ -0,0 +1,140 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2025 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 "pyrowave/pyrowave_decoder.h" +#include "utils/thread_safe.h" +#include "vk/allocation.h" +#include "wivrn_packets.h" +#include +#include +#include +#include +#include + +namespace wivrn +{ +class shard_accumulator; +} + +namespace scenes +{ +class stream; +} + +namespace wivrn +{ +class decoder +{ +public: + struct blit_handle + { + wivrn::from_headset::feedback feedback; + wivrn::to_headset::video_stream_data_shard::view_info_t view_info; + vk::raii::ImageView & image_view; + vk::Image image = nullptr; + vk::ImageLayout * current_layout = nullptr; + + std::atomic_bool & free; + + ~blit_handle(); + }; + +private: + static const int image_count = 12; + struct image + { + image_allocation image; + vk::raii::ImageView view_full = nullptr; + vk::raii::ImageView view_y = nullptr; + vk::raii::ImageView view_cb = nullptr; + vk::raii::ImageView view_cr = nullptr; + vk::ImageLayout current_layout = vk::ImageLayout::eUndefined; + std::atomic_bool free = true; + }; + + vk::raii::SamplerYcbcrConversion ycbcr_conversion; + vk::raii::Sampler sampler_; + + std::array image_pool; + + wivrn::to_headset::video_stream_description::item description; + + std::weak_ptr weak_scene; + shard_accumulator * accumulator; + + vk::raii::CommandPool command_pool; + vk::raii::CommandBuffer cmd_buf; + vk::raii::Fence fence; + + PyroWave::Decoder dec; + + struct pending_data + { + from_headset::feedback feedback; + to_headset::video_stream_data_shard::view_info_t view_info; + image * img = nullptr; + }; + thread_safe_notifyable pending; + std::thread worker; + std::atomic_bool exiting = false; + +public: + decoder(vk::raii::Device & device, + vk::raii::PhysicalDevice & physical_device, + uint32_t vk_queue_family_index, + const wivrn::to_headset::video_stream_description::item & description, + float fps, + uint8_t stream_index, + std::weak_ptr scene, + shard_accumulator * accumulator); + + ~decoder(); + + void push_data(std::span> data, uint64_t frame_index, bool partial); + + void frame_completed( + const wivrn::from_headset::feedback & feedback, + const wivrn::to_headset::video_stream_data_shard::view_info_t & view_info); + + const auto & desc() const + { + return description; + } + + vk::Sampler sampler() + { + return *sampler_; + } + + vk::Extent2D image_size() + { + return { + description.width, + description.height, + }; + } + + static std::vector supported_codecs(); + +private: + image * get_free(); + void worker_function(); +}; +} // namespace wivrn diff --git a/client/decoder/shard_accumulator.cpp b/client/decoder/shard_accumulator.cpp index 900c05ee..b00435c6 100644 --- a/client/decoder/shard_accumulator.cpp +++ b/client/decoder/shard_accumulator.cpp @@ -169,23 +169,35 @@ void shard_accumulator::try_submit_frame(uint16_t shard_idx) { auto & data_shards = current.data; + // Don't send if there is missing data before the current shard for (size_t idx = 0; idx < shard_idx; ++idx) if (not data_shards[idx]) return; - uint16_t last_idx = shard_idx + 1; - for (size_t size = data_shards.size(); - last_idx < size and data_shards[last_idx]; - ++last_idx) + // Find the beginning of the slice + size_t begin = shard_idx; + while (begin > 0 and not(data_shards[begin]->flags & video_stream_data_shard::start_of_slice)) + --begin; + // And the end + size_t end = shard_idx; + for (;; ++end) { + // We don't have the end yet + if (end == data_shards.size() or not data_shards[end]) + return; + if (data_shards[end]->flags & video_stream_data_shard::end_of_slice) + break; } + if (not(data_shards[end]->flags & video_stream_data_shard::end_of_slice)) + return; + std::vector> payload; - payload.reserve(last_idx - shard_idx); - for (size_t idx = shard_idx; idx < last_idx; ++idx) + payload.reserve(1 + end - begin); + for (size_t idx = begin; idx <= end; ++idx) payload.emplace_back(data_shards[idx]->payload); - bool frame_complete = last_idx == data_shards.size() and data_shards.back()->flags & video_stream_data_shard::end_of_frame; + bool frame_complete = data_shards[end]->flags & video_stream_data_shard::end_of_frame; decoder->push_data(payload, data_shards[shard_idx]->frame_idx, not frame_complete); if (not frame_complete) diff --git a/client/decoder/shard_accumulator.h b/client/decoder/shard_accumulator.h index 406c0c49..fb18dd17 100644 --- a/client/decoder/shard_accumulator.h +++ b/client/decoder/shard_accumulator.h @@ -22,6 +22,10 @@ #include #include +#if 1 +#include "decoder/pyrowave/decoder.h" +using decoder_impl = ::wivrn::decoder; +#else #ifdef __ANDROID__ #include "decoder/android/android_decoder.h" using decoder_impl = ::wivrn::android::decoder; @@ -29,6 +33,7 @@ using decoder_impl = ::wivrn::android::decoder; #include "decoder/ffmpeg/ffmpeg_decoder.h" using decoder_impl = ::wivrn::ffmpeg::decoder; #endif +#endif #include "wivrn_packets.h" #include @@ -81,12 +86,13 @@ public: explicit shard_accumulator( vk::raii::Device & device, vk::raii::PhysicalDevice & physical_device, + uint32_t vk_queue_family_index, xr::instance & instance, const wivrn::to_headset::video_stream_description::item & description, float fps, std::weak_ptr scene, uint8_t stream_index) : - decoder(std::make_shared(device, physical_device, description, fps, stream_index, scene, this)), + decoder(std::make_shared(device, physical_device, vk_queue_family_index, description, fps, stream_index, scene, this)), current(stream_index), next(stream_index), weak_scene(scene), diff --git a/client/scenes/stream.cpp b/client/scenes/stream.cpp index aba0b167..e3daeb93 100644 --- a/client/scenes/stream.cpp +++ b/client/scenes/stream.cpp @@ -1105,7 +1105,7 @@ void scenes::stream::setup(const to_headset::video_stream_description & descript spdlog::info("Creating decoder size {}x{} offset {},{}", item.width, item.height, item.offset_x, item.offset_y); decoders.push_back(accumulator_images{ - .decoder = std::make_unique(device, physical_device, instance, item, description.fps, shared_from_this(), stream_index), + .decoder = std::make_unique(device, physical_device, queue_family_index, instance, item, description.fps, shared_from_this(), stream_index), }); } } diff --git a/cmake/CompileGLSL.cmake b/cmake/CompileGLSL.cmake index 4e05cf80..8c9705a0 100644 --- a/cmake/CompileGLSL.cmake +++ b/cmake/CompileGLSL.cmake @@ -1,5 +1,5 @@ -function(compile_glsl_aux shader_stage shader_name glsl_filename output) +function(compile_glsl_aux shader_stage shader_name glsl_filename output target_env) string(TOUPPER ${shader_stage} shader_stage_upper) cmake_path(REPLACE_FILENAME output "${shader_name}.spv" OUTPUT_VARIABLE SPV_FILE) @@ -12,7 +12,7 @@ function(compile_glsl_aux shader_stage shader_name glsl_filename output) add_custom_command( OUTPUT "${SPV_FILE}" - COMMAND Vulkan::glslangValidator -V -S ${shader_stage} -D${shader_stage_upper}_SHADER ${in_file} -x -o "${SPV_FILE}" + COMMAND Vulkan::glslangValidator -V --target-env ${target_env} -S ${shader_stage} -D${shader_stage_upper}_SHADER ${in_file} -x -o "${SPV_FILE}" DEPENDS "${glsl_filename}" VERBATIM ) @@ -30,6 +30,19 @@ endfunction() function(wivrn_compile_glsl target) + set(options) + set(oneValueArgs TARGET_ENV NAMESPACE) + set(multiValueArgs SHADERS) + cmake_parse_arguments(_args "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN}) + + if(NOT _args_TARGET_ENV) + set(_args_TARGET_ENV vulkan1.0) + endif() + + if (_args_NAMESPACE) + set(_namespace_begin "namespace ${_args_NAMESPACE} {") + set(_namespace_end "}") + endif() cmake_path(APPEND OUTPUT "${CMAKE_CURRENT_BINARY_DIR}" "${target}_shaders.cpp") @@ -38,24 +51,25 @@ function(wivrn_compile_glsl target) #include #include #include +${_namespace_begin} extern const std::map> shaders = { ") - foreach(in_file IN LISTS ARGN) - if (in_file MATCHES "\.\(vert|frag|tesc|tese|geom|comp\)\.glsl$") + foreach(in_file IN LISTS _args_SHADERS) + if (in_file MATCHES "\.\(vert|frag|tesc|tese|geom|comp\)\(\.glsl\)?$") set(shader_stage ${CMAKE_MATCH_1}) cmake_path(GET in_file STEM LAST_ONLY shader_name) - compile_glsl_aux(${shader_stage} ${shader_name} ${in_file} ${OUTPUT}) + compile_glsl_aux(${shader_stage} ${shader_name} ${in_file} ${OUTPUT} ${_args_TARGET_ENV}) else() cmake_path(GET in_file STEM LAST_ONLY shader_name) - compile_glsl_aux(vert ${shader_name}.vert ${in_file} ${OUTPUT}) - compile_glsl_aux(frag ${shader_name}.frag ${in_file} ${OUTPUT}) + compile_glsl_aux(vert ${shader_name}.vert ${in_file} ${OUTPUT} ${_args_TARGET_ENV}) + compile_glsl_aux(frag ${shader_name}.frag ${in_file} ${OUTPUT} ${_args_TARGET_ENV}) endif() endforeach() - file(APPEND ${OUTPUT} "};") + file(APPEND ${OUTPUT} "};${_namespace_end}") target_sources(${target} PRIVATE ${OUTPUT}) diff --git a/common/CMakeLists.txt b/common/CMakeLists.txt index fa2db43c..2f87ffad 100644 --- a/common/CMakeLists.txt +++ b/common/CMakeLists.txt @@ -126,6 +126,9 @@ if(ANDROID) add_library(OpenSSL::Crypto STATIC IMPORTED) set_property(TARGET OpenSSL::Crypto PROPERTY IMPORTED_LOCATION ${CMAKE_BINARY_DIR}/openssl/lib/libcrypto.so) target_include_directories(OpenSSL::Crypto INTERFACE ${CMAKE_BINARY_DIR}/openssl/include) + + FetchContent_MakeAvailable(glm) + target_link_libraries(wivrn-common PUBLIC glm::glm) else() target_link_libraries(wivrn-common PUBLIC Vulkan::Headers) endif() @@ -133,3 +136,5 @@ endif() target_include_directories(wivrn-common-base PUBLIC ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_BINARY_DIR}) target_link_libraries(wivrn-common PUBLIC Boost::pfr OpenSSL::Crypto wivrn-external wivrn-common-base) target_compile_definitions(wivrn-common PUBLIC VULKAN_HPP_NO_STRUCT_CONSTRUCTORS) + +add_subdirectory(pyrowave) diff --git a/common/pyrowave/CMakeLists.txt b/common/pyrowave/CMakeLists.txt new file mode 100644 index 00000000..1efc0b74 --- /dev/null +++ b/common/pyrowave/CMakeLists.txt @@ -0,0 +1,15 @@ +include(CompileGLSL) + +add_library(pyrowave STATIC + pyrowave_common.cpp + pyrowave_encoder.cpp + pyrowave_decoder.cpp +) + +file(GLOB_RECURSE VULKAN_SHADERS CONFIGURE_DEPENDS "shaders/*.comp") +wivrn_compile_glsl(pyrowave TARGET_ENV vulkan1.3 SHADERS ${VULKAN_SHADERS} NAMESPACE pyrowave) + +target_compile_definitions(pyrowave PUBLIC VULKAN_HPP_NO_STRUCT_CONSTRUCTORS) + +target_link_libraries(pyrowave PRIVATE wivrn-common) +target_include_directories(pyrowave PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) diff --git a/common/pyrowave/pyrowave_common.cpp b/common/pyrowave/pyrowave_common.cpp new file mode 100644 index 00000000..4b29cbce --- /dev/null +++ b/common/pyrowave/pyrowave_common.cpp @@ -0,0 +1,256 @@ +// Copyright (c) 2025 Hans-Kristian Arntzen +// SPDX-License-Identifier: MIT +#include "pyrowave_common.h" +#include + +#if PYROWAVE_PRECISION < 0 || PYROWAVE_PRECISION > 2 +#error "PYROWAVE_PRECISION must be in range [0, 2]." +#endif + +constexpr int WaveletFP16Levels = 2; + +namespace pyrowave +{ +extern const std::map> shaders; +} + +namespace PyroWave +{ + +vk::raii::ShaderModule load_shader(vk::raii::Device & device, const std::string & name) +{ + const auto & spirv = pyrowave::shaders.at(name); + vk::ShaderModuleCreateInfo create_info{ + .codeSize = spirv.size() * sizeof(uint32_t), + .pCode = data(spirv), + }; + + return vk::raii::ShaderModule{device, create_info}; +} + +bool supports_subgroup_size_log2( + vk::PhysicalDeviceVulkan13Properties const & prop13, + bool subgroup_full_group, + uint8_t subgroup_minimum_size_log2, + uint8_t subgroup_maximum_size_log2, + vk::ShaderStageFlagBits stage) +{ + uint32_t min_subgroups = 1u << subgroup_minimum_size_log2; + uint32_t max_subgroups = 1u << subgroup_maximum_size_log2; + + bool full_range = min_subgroups <= prop13.minSubgroupSize && + max_subgroups >= prop13.maxSubgroupSize; + + // We can use VARYING size. + if (full_range) + return true; + + if (min_subgroups > prop13.maxSubgroupSize || + max_subgroups < prop13.minSubgroupSize) + { + // No overlap in requested subgroup size and available subgroup size. + return false; + } + + // We need requiredSubgroupSizeStages support here. + return (prop13.requiredSubgroupSizeStages & stage) != vk::ShaderStageFlags{}; +} + +Configuration::Configuration() +{ + precision = PYROWAVE_PRECISION; + if (const char * env = getenv("PYROWAVE_PRECISION")) + precision = int(strtol(env, nullptr, 0)); + + if (precision < 0 || precision > 2) + { + fprintf(stderr, "pyrowave: precision must be in range [0, 2].\n"); + precision = PYROWAVE_PRECISION; + } +} + +Configuration & Configuration::get() +{ + static Configuration config; + return config; +} + +int Configuration::get_precision() const +{ + return precision; +} + +void WaveletBuffers::accumulate_block_mapping(int blocks_x_8x8, int blocks_y_8x8) +{ + int blocks_x_32x32 = (blocks_x_8x8 + 3) / 4; + int blocks_y_32x32 = (blocks_y_8x8 + 3) / 4; + + for (int y = 0; y < blocks_y_32x32; y++) + { + for (int x = 0; x < blocks_x_32x32; x++) + { + BlockMapping mapping = {}; + mapping.block_offset_8x8 = block_count_8x8 + 4 * y * blocks_x_8x8 + 4 * x; + mapping.block_stride_8x8 = blocks_x_8x8; + mapping.block_width_8x8 = std::min(4, blocks_x_8x8 - 4 * x); + mapping.block_height_8x8 = std::min(4, blocks_y_8x8 - 4 * y); + block_32x32_to_8x8_mapping.push_back(mapping); + block_count_32x32++; + } + } + + block_count_8x8 += blocks_x_8x8 * blocks_y_8x8; +} + +void WaveletBuffers::init_block_meta() +{ + for (int level = DecompositionLevels - 1; level >= 0; level--) + { + for (int component = 0; component < NumComponents; component++) + { + // Ignore top-level CbCr when doing 420 subsampling. + if (level == 0 && component != 0 && chroma == ChromaSubsampling::Chroma420) + continue; + + for (int band = (level == DecompositionLevels - 1 ? 0 : 1); band < 4; band++) + { + uint32_t level_width = get_width(wavelet_img_high_res, level); + uint32_t level_height = get_height(wavelet_img_high_res, level); + + int blocks_x_8x8 = (level_width + 7) / 8; + int blocks_y_8x8 = (level_height + 7) / 8; + int blocks_x_32x32 = (level_width + 31) / 32; + + block_meta[component][level][band] = { + block_count_8x8, + blocks_x_8x8, + block_count_32x32, + blocks_x_32x32, + }; + + accumulate_block_mapping(blocks_x_8x8, blocks_y_8x8); + } + } + } +} + +WaveletBuffers::WaveletBuffers(vk::raii::Device & device, int width, int height, ChromaSubsampling chroma) : + device(device), + + mirror_repeat_sampler( + device, + vk::SamplerCreateInfo{ + .addressModeU = vk::SamplerAddressMode::eMirroredRepeat, + .addressModeV = vk::SamplerAddressMode::eMirroredRepeat, + .addressModeW = vk::SamplerAddressMode::eMirroredRepeat, + }), + + border_sampler( + device, + vk::SamplerCreateInfo{ + .addressModeU = vk::SamplerAddressMode::eClampToBorder, + .addressModeV = vk::SamplerAddressMode::eClampToBorder, + .addressModeW = vk::SamplerAddressMode::eClampToBorder, + .borderColor = vk::BorderColor::eFloatTransparentBlack, + }), + + component_layer_views{{nullptr, nullptr, nullptr, nullptr, nullptr}, {nullptr, nullptr, nullptr, nullptr, nullptr}, {nullptr, nullptr, nullptr, nullptr, nullptr}}, + component_ll_views{{nullptr, nullptr, nullptr, nullptr, nullptr}, {nullptr, nullptr, nullptr, nullptr, nullptr}, {nullptr, nullptr, nullptr, nullptr, nullptr}}, + + width(width), + height(height), + aligned_width(std::max(align(width, Alignment), MinimumImageSize)), + aligned_height(std::max(align(height, Alignment), MinimumImageSize)), + chroma(chroma) +{ + vk::ImageCreateInfo info{ + .imageType = vk::ImageType::e2D, + .format = Configuration::get().get_precision() == 2 ? vk::Format::eR32Sfloat : vk::Format::eR16Sfloat, + .extent = { + .width = aligned_width / 2, + .height = aligned_height / 2, + .depth = 1, + }, + .mipLevels = uint32_t(Configuration::get().get_precision() != 1 ? DecompositionLevels : WaveletFP16Levels), + .arrayLayers = NumFrequencyBandsPerLevel * NumComponents, + .usage = vk::ImageUsageFlagBits::eSampled | vk::ImageUsageFlagBits::eStorage | vk::ImageUsageFlagBits::eTransferSrc | vk::ImageUsageFlagBits::eTransferDst, + }; + + wavelet_img_high_res = image_allocation( + device, + info, + { + .usage = VMA_MEMORY_USAGE_AUTO, + }, + "wavelet_img_high_res"); + // FIXME: transition to general layout + + if (Configuration::get().get_precision() == 1) + { + // For the lowest level bands, we want to maintain precision as much as possible and bandwidth here is trivial. + info.mipLevels = DecompositionLevels - info.mipLevels; + info.format = vk::Format::eR32Sfloat; + info.extent.width >>= WaveletFP16Levels; + info.extent.height >>= WaveletFP16Levels; + wavelet_img_low_res = image_allocation( + device, + info, + { + .usage = VMA_MEMORY_USAGE_AUTO, + }, + "wavelet_img_low_res"); + // FIXME: transition to general layout + } + + for (int level = 0; level < DecompositionLevels; level++) + { + vk::ImageViewCreateInfo view_info{ + .viewType = vk::ImageViewType::e2D, + .subresourceRange = { + .aspectMask = vk::ImageAspectFlagBits::eColor, + .levelCount = 1, + }, + }; + image_allocation * image = nullptr; + if (Configuration::get().get_precision() != 1 || level < WaveletFP16Levels) + { + view_info.subresourceRange.baseMipLevel = level; + image = &wavelet_img_high_res; + view_info.image = vk::Image(wavelet_img_high_res); + view_info.format = wavelet_img_high_res.info().format; + } + else + { + view_info.subresourceRange.baseMipLevel = level - WaveletFP16Levels; + image = &wavelet_img_low_res; + view_info.image = vk::Image(wavelet_img_low_res); + view_info.format = wavelet_img_low_res.info().format; + } + + for (int component = 0; component < NumComponents; component++) + { + view_info.subresourceRange.baseArrayLayer = 4 * component; + + view_info.viewType = vk::ImageViewType::e2DArray; + view_info.subresourceRange.layerCount = 4; + component_layer_views[component][level] = device.createImageView(view_info); + + view_info.viewType = vk::ImageViewType::e2D; + view_info.subresourceRange.layerCount = 1; + component_ll_views[component][level] = device.createImageView(view_info); + component_ll_dim[component][level].width = get_width(*image, view_info.subresourceRange.baseMipLevel); + component_ll_dim[component][level].height = get_height(*image, view_info.subresourceRange.baseMipLevel); + } + } +} +void WaveletBuffers::begin_label(vk::raii::CommandBuffer & cmd, const char * label) +{ + if (has_debug_ext) + cmd.beginDebugUtilsLabelEXT({.pLabelName = label}); +} +void WaveletBuffers::end_label(vk::raii::CommandBuffer & cmd) +{ + if (has_debug_ext) + cmd.endDebugUtilsLabelEXT(); +} +} // namespace PyroWave diff --git a/common/pyrowave/pyrowave_common.h b/common/pyrowave/pyrowave_common.h new file mode 100644 index 00000000..dc7db8d7 --- /dev/null +++ b/common/pyrowave/pyrowave_common.h @@ -0,0 +1,264 @@ +// Copyright (c) 2025 Hans-Kristian Arntzen +// SPDX-License-Identifier: MIT +#pragma once + +#define PYROWAVE_PRECISION 1 + +#include +#include +#include + +#include "vk/allocation.h" + +#include + +namespace PyroWave +{ + +enum class ChromaSubsampling +{ + Chroma420, + Chroma444 +}; + +struct BitstreamPacket +{ + uint32_t offset_u32; + uint32_t num_words; +}; + +struct BitstreamHeader +{ + uint16_t ballot; + uint16_t payload_words : 12; + uint16_t sequence : 3; + uint16_t extended : 1; + uint32_t quant_code : 8; + uint32_t block_index : 24; +}; + +static_assert(sizeof(BitstreamHeader) == 8, "BitstreamHeader is not 8 bytes."); + +enum +{ + BITSTREAM_EXTENDED_CODE_START_OF_FRAME = 0, +}; + +enum +{ + CHROMA_RESOLUTION_420 = 0, + CHROMA_RESOLUTION_444 = 1 +}; + +enum +{ + CHROMA_SITING_CENTER = 0, + CHROMA_SITING_LEFT = 1 +}; + +enum +{ + YCBCR_RANGE_FULL = 0, + YCBCR_RANGE_LIMITED = 1 +}; + +enum +{ + COLOR_PRIMARIES_BT709 = 0, + COLOR_PRIMARIES_BT2020 = 1 +}; + +enum +{ + YCBCR_TRANSFORM_BT709 = 0, + YCBCR_TRANSFORM_BT2020 = 1 +}; + +enum +{ + TRANSFER_FUNCTION_BT709 = 0, + TRANSFER_FUNCTION_PQ = 1 +}; + +static constexpr uint32_t SequenceCountMask = 0x7; + +struct BitstreamSequenceHeader +{ + uint32_t width_minus_1 : 14; + uint32_t height_minus_1 : 14; + uint32_t sequence : 3; + uint32_t extended : 1; + uint32_t total_blocks : 24; + uint32_t code : 2; + uint32_t chroma_resolution : 1; + uint32_t color_primaries : 1; + uint32_t transfer_function : 1; + uint32_t ycbcr_transform : 1; + uint32_t ycbcr_range : 1; + uint32_t chroma_siting : 1; +}; + +static_assert(sizeof(BitstreamSequenceHeader) == 8, "BitstreamSequenceHeader is not 8 bytes."); + +struct QuantStats +{ + uint16_t square_error_fp16; + uint16_t encode_cost_bits; +}; + +struct BlockStats +{ + uint32_t num_planes; + QuantStats stats[15]; +}; +static_assert(sizeof(BlockStats) == 64, "BlockStats is not 64 bytes."); + +struct BlockMeta +{ + uint32_t code_word; + uint32_t offset; +}; + +static constexpr int DecompositionLevels = 5; +static constexpr int Alignment = 1 << DecompositionLevels; +// If the final decomposition band is too small, the mirroring will break since it starts double mirroring. +static constexpr int MinimumImageSize = 4 << DecompositionLevels; +static constexpr int NumComponents = 3; +static constexpr int NumFrequencyBandsPerLevel = 4; + +static inline int align(int value, int align) +{ + return (value + align - 1) & ~(align - 1); +} + +static constexpr int MaxScaleExp = 4; + +static inline float decode_quant(uint8_t quant_code) +{ + // Custom FP formulation for numbers in (0, 2) range. + int e = MaxScaleExp - (quant_code >> 3); + int m = quant_code & 0x7; + float inv_quant = (1.0f / (8.0f * 1024.0f * 1024.0f)) * float((8 + m) * (1 << (20 + e))); + return inv_quant; +} + +static inline uint8_t encode_quant(float decoder_q_scale) +{ + uint32_t v; + memcpy(&v, &decoder_q_scale, sizeof(decoder_q_scale)); + + int e = ((v >> 23) & 0xff) - 127 - MaxScaleExp; + int m = (v >> 20) & 0x7; + e = -e; + assert(e >= 0 && e <= 20); + return (e << 3) | m; +} + +static inline auto get_width(const image_allocation & img, uint32_t lod = 0) +{ + return std::max(1u, img.info().extent.width >> lod); +} +static inline auto get_height(const image_allocation & img, uint32_t lod = 0) +{ + return std::max(1u, img.info().extent.height >> lod); +} + +bool supports_subgroup_size_log2( + vk::PhysicalDeviceVulkan13Properties const & prop13, + bool subgroup_full_group, + uint8_t subgroup_minimum_size_log2, + uint8_t subgroup_maximum_size_log2, + vk::ShaderStageFlagBits stage = vk::ShaderStageFlagBits::eCompute); + +vk::raii::ShaderModule load_shader(vk::raii::Device & device, const std::string & name); + +struct pipeline_subgroup_info +{ + vk::PipelineShaderStageRequiredSubgroupSizeCreateInfo info{}; + + void set_subgroup_size( + vk::PhysicalDeviceVulkan13Properties const & prop13, + vk::ComputePipelineCreateInfo & pipeline_info, + uint8_t subgroup_minimum_size_log2, + uint8_t subgroup_maximum_size_log2) + { + const uint32_t min_subgroups = 1u << subgroup_minimum_size_log2; + const uint32_t max_subgroups = 1u << subgroup_maximum_size_log2; + if (min_subgroups <= prop13.minSubgroupSize and max_subgroups >= prop13.maxSubgroupSize) + { + pipeline_info.stage.flags |= vk::PipelineShaderStageCreateFlagBits::eAllowVaryingSubgroupSize; + } + else + { + info.pNext = const_cast(pipeline_info.stage.pNext); + pipeline_info.stage.pNext = &info; + // Pick a fixed subgroup size. Prefer smallest subgroup size. + if (min_subgroups < prop13.minSubgroupSize) + info.requiredSubgroupSize = prop13.minSubgroupSize; + else + info.requiredSubgroupSize = min_subgroups; + } + } +}; + +class Configuration +{ +public: + static Configuration & get(); + int get_precision() const; + +private: + Configuration(); + int precision; +}; + +struct WaveletBuffers +{ + WaveletBuffers(vk::raii::Device & device, int width, int height, ChromaSubsampling chroma); + + vk::raii::Device & device; + image_allocation wavelet_img_low_res; + image_allocation wavelet_img_high_res; + vk::raii::Sampler mirror_repeat_sampler; + vk::raii::Sampler border_sampler; + vk::raii::ImageView component_layer_views[NumComponents][DecompositionLevels]; + vk::raii::ImageView component_ll_views[NumComponents][DecompositionLevels]; + vk::Extent2D component_ll_dim[NumComponents][DecompositionLevels]; + + struct BlockInfo + { + int block_offset_8x8; + int block_stride_8x8; + int block_offset_32x32; + int block_stride_32x32; + }; + BlockInfo block_meta[NumComponents][DecompositionLevels][4] = {}; + + struct BlockMapping + { + int block_offset_8x8; + int block_stride_8x8; + int block_width_8x8; + int block_height_8x8; + }; + std::vector block_32x32_to_8x8_mapping; + + int block_count_8x8 = 0; + int block_count_32x32 = 0; + + int width = 0; + int height = 0; + uint32_t aligned_width = 0; + uint32_t aligned_height = 0; + +protected: + bool has_debug_ext = false; + void init_block_meta(); + void begin_label(vk::raii::CommandBuffer &, const char * label); + void end_label(vk::raii::CommandBuffer &); + ChromaSubsampling chroma; + +private: + void accumulate_block_mapping(int blocks_x_8x8, int blocks_y_8x8); +}; +} // namespace PyroWave diff --git a/common/pyrowave/pyrowave_decoder.cpp b/common/pyrowave/pyrowave_decoder.cpp new file mode 100644 index 00000000..85546190 --- /dev/null +++ b/common/pyrowave/pyrowave_decoder.cpp @@ -0,0 +1,825 @@ +// Copyright (c) 2025 Hans-Kristian Arntzen +// SPDX-License-Identifier: MIT +#include "pyrowave_decoder.h" + +#include +#include +#include +#include +#include +#include + +#define XSTR(s) STR(s) +#define STR(s) #s + +namespace PyroWave +{ + +struct DequantizerPushData +{ + glm::ivec2 resolution; + int32_t output_layer; + int32_t block_offset_32x32; + int32_t block_stride_32x32; +}; +struct IDwtPushData +{ + glm::ivec2 resolution; + glm::vec2 inv_resolution; +}; +static vk::raii::DescriptorPool make_descriptor_pool(vk::raii::Device & device) +{ + std::array pool_sizes{ + vk::DescriptorPoolSize{ + .type = vk::DescriptorType::eStorageBuffer, + .descriptorCount = + 2 * NumComponents * DecompositionLevels, // dequant + }, + vk::DescriptorPoolSize{ + .type = vk::DescriptorType::eCombinedImageSampler, + .descriptorCount = 2 * NumComponents * DecompositionLevels, // dequant + iwt + }, + vk::DescriptorPoolSize{ + .type = vk::DescriptorType::eStorageImage, + .descriptorCount = NumComponents * DecompositionLevels, // idwt + }, + }; + return {device, + vk::DescriptorPoolCreateInfo{ + .maxSets = 2 * NumComponents * DecompositionLevels, // dequant + iwt + .poolSizeCount = pool_sizes.size(), + .pPoolSizes = pool_sizes.data(), + }}; +} + +Decoder::Decoder(vk::raii::PhysicalDevice & phys_dev, vk::raii::Device & device, int width, int height, ChromaSubsampling chroma) : + WaveletBuffers(device, width, height, chroma), + ds_pool(make_descriptor_pool(device)) +{ + auto [prop, prop11, prop13] = phys_dev.getProperties2(); + auto ops = prop11.subgroupSupportedOperations; + constexpr auto required_features = + vk::SubgroupFeatureFlagBits::eVote | + vk::SubgroupFeatureFlagBits::eQuad | + vk::SubgroupFeatureFlagBits::eBallot | + vk::SubgroupFeatureFlagBits::eArithmetic | + vk::SubgroupFeatureFlagBits::eShuffle | + vk::SubgroupFeatureFlagBits::eShuffleRelative | + vk::SubgroupFeatureFlagBits::eBasic; + + if ((ops & required_features) != required_features) + { + throw std::runtime_error("There are missing subgroup features. Device supports " + vk::to_string(ops) + ", but requires " + vk::to_string(required_features) + "."); + } + + auto [feat, feat12, feat13] = phys_dev.getFeatures2(); + + // The decoder is more lenient. + if (!supports_subgroup_size_log2(prop13, true, 4, 6)) + throw std::runtime_error("Device does not have the required subgroup properties"); + + if (not feat12.storageBuffer8BitAccess) + throw std::runtime_error("Missing storageBuffer8BitAccess feature"); + + if (not feat12.shaderFloat16) + throw std::runtime_error("Missing shaderFloat16 feature"); + + init_block_meta(); + vk::BufferCreateInfo info{ + .usage = vk::BufferUsageFlagBits::eStorageBuffer | vk::BufferUsageFlagBits::eTransferDst, + }; + + info.size = block_count_32x32 * sizeof(uint32_t); + dequant_offset_buffer = buffer_allocation( + device, + info, + { + .flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_ALLOW_TRANSFER_INSTEAD_BIT | VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT, + .usage = VMA_MEMORY_USAGE_AUTO, + }, + "dequant_offset_buffer"); + if (not(dequant_offset_buffer.properties() & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT)) + { + info.usage = vk::BufferUsageFlagBits::eTransferSrc; + dequant_staging = buffer_allocation( + device, + info, + { + .flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT, + .usage = VMA_MEMORY_USAGE_AUTO, + }, + "dequant staging"); + } + dequant_offset_buffer_cpu.resize(block_count_32x32); + + payload_data_cpu.reserve(1024 * 1024); + clear(); + + // dequant pipeline + { + std::array bindings{ + vk::DescriptorSetLayoutBinding{ + .binding = 0, + .descriptorType = vk::DescriptorType::eStorageImage, + .descriptorCount = 1, + .stageFlags = vk::ShaderStageFlagBits::eCompute, + }, + vk::DescriptorSetLayoutBinding{ + .binding = 1, + .descriptorType = vk::DescriptorType::eStorageBuffer, + .descriptorCount = 1, + .stageFlags = vk::ShaderStageFlagBits::eCompute, + }, + vk::DescriptorSetLayoutBinding{ + .binding = 2, + .descriptorType = vk::DescriptorType::eStorageBuffer, + .descriptorCount = 1, + .stageFlags = vk::ShaderStageFlagBits::eCompute, + }, + }; + dequant_.ds_layout = device.createDescriptorSetLayout({ + .bindingCount = bindings.size(), + .pBindings = bindings.data(), + }); + + vk::PushConstantRange pc{ + .stageFlags = vk::ShaderStageFlagBits::eCompute, + .size = sizeof(DequantizerPushData), + }; + + dequant_.layout = device.createPipelineLayout({ + .setLayoutCount = 1, + .pSetLayouts = &*dequant_.ds_layout, + .pushConstantRangeCount = 1, + .pPushConstantRanges = &pc, + }); + + vk::PipelineShaderStageRequiredSubgroupSizeCreateInfoEXT subgroup_size{}; + auto shader = load_shader(device, "wavelet_dequant"); + vk::ComputePipelineCreateInfo info{ + .stage = { + .flags = vk::PipelineShaderStageCreateFlagBits::eRequireFullSubgroups, + .stage = vk::ShaderStageFlagBits::eCompute, + .module = *shader, + .pName = "main", + }, + .layout = *dequant_.layout, + }; + pipeline_subgroup_info psi; + psi.set_subgroup_size(prop13, info, 4, 6); + dequant_.pipeline = device.createComputePipeline( + nullptr, // FIXME: cache + info); + + for (int level = 0; level < DecompositionLevels; level++) + { + for (int component = 0; component < NumComponents; component++) + { + dequant_.ds[component][level] = device.allocateDescriptorSets({ + .descriptorPool = *ds_pool, + .descriptorSetCount = 1, + .pSetLayouts = &*dequant_.ds_layout, + })[0] + .release(); + std::array image_info{ + vk::DescriptorImageInfo{ + .sampler = *border_sampler, + .imageView = *component_layer_views[component][level], + .imageLayout = vk::ImageLayout::eGeneral, + }, + }; + std::array buffer_info{ + vk::DescriptorBufferInfo{ + .buffer = dequant_offset_buffer, + .range = vk::WholeSize, + }, + }; + + std::array descriptor_writes{ + vk::WriteDescriptorSet{ + .dstSet = dequant_.ds[component][level], + .dstBinding = 0, + .descriptorCount = image_info.size(), + .descriptorType = vk::DescriptorType::eStorageImage, + .pImageInfo = image_info.data(), + }, + vk::WriteDescriptorSet{ + .dstSet = dequant_.ds[component][level], + .dstBinding = 1, + .descriptorCount = buffer_info.size(), + .descriptorType = vk::DescriptorType::eStorageBuffer, + .pBufferInfo = buffer_info.data(), + }, + }; + device.updateDescriptorSets(descriptor_writes, {}); + } + } + } + + // idwt pipeline + { + std::array bindings{ + vk::DescriptorSetLayoutBinding{ + .binding = 0, + .descriptorType = vk::DescriptorType::eCombinedImageSampler, + .descriptorCount = 1, + .stageFlags = vk::ShaderStageFlagBits::eCompute, + }, + vk::DescriptorSetLayoutBinding{ + .binding = 1, + .descriptorType = vk::DescriptorType::eStorageImage, + .descriptorCount = 1, + .stageFlags = vk::ShaderStageFlagBits::eCompute, + }, + }; + idwt_.ds_layout = device.createDescriptorSetLayout({ + .bindingCount = bindings.size(), + .pBindings = bindings.data(), + }); + + vk::PushConstantRange pc{ + .stageFlags = vk::ShaderStageFlagBits::eCompute, + .size = sizeof(IDwtPushData), + }; + + idwt_.layout = device.createPipelineLayout({ + .setLayoutCount = 1, + .pSetLayouts = &*idwt_.ds_layout, + .pushConstantRangeCount = 1, + .pPushConstantRanges = &pc, + }); + VkBool32 dc_shift = false; + vk::SpecializationMapEntry sp_entry{ + .constantID = 0, + .size = sizeof(dc_shift), + }; + vk::SpecializationInfo sp{ + .mapEntryCount = 1, + .pMapEntries = &sp_entry, + .dataSize = sizeof(dc_shift), + .pData = &dc_shift, + }; + auto shader = load_shader(device, "idwt_" XSTR(PYROWAVE_PRECISION)); + vk::ComputePipelineCreateInfo info{ + .stage = { + .flags = vk::PipelineShaderStageCreateFlagBits::eRequireFullSubgroups, + .stage = vk::ShaderStageFlagBits::eCompute, + .module = *shader, + .pName = "main", + .pSpecializationInfo = &sp, + }, + .layout = *idwt_.layout, + }; + pipeline_subgroup_info psi; + psi.set_subgroup_size(prop13, info, 2, 6); + idwt_.pipeline = device.createComputePipeline( + nullptr, // FIXME: cache + info); + + dc_shift = true; + idwt_dcshift = device.createComputePipeline( + nullptr, // FIXME: cache + info); + + for (int input_level = DecompositionLevels - 1; input_level >= 0; input_level--) + { + for (int c = 0; c < NumComponents; c++) + { + idwt_.ds[c][input_level] = device.allocateDescriptorSets({ + .descriptorPool = *ds_pool, + .descriptorSetCount = 1, + .pSetLayouts = &*idwt_.ds_layout, + })[0] + .release(); + + vk::DescriptorImageInfo texture{ + .sampler = *mirror_repeat_sampler, + .imageView = *component_layer_views[c][input_level], + .imageLayout = vk::ImageLayout::eGeneral, + }; + vk::WriteDescriptorSet descriptor_write{ + .dstSet = idwt_.ds[c][input_level], + .dstBinding = 0, + .descriptorCount = 1, + .descriptorType = vk::DescriptorType::eCombinedImageSampler, + .pImageInfo = &texture, + }; + device.updateDescriptorSets(descriptor_write, {}); + + // Updated with output image + if (input_level == 0) + continue; + if (input_level == 1 and c > 0 and chroma == ChromaSubsampling::Chroma420) + continue; + + vk::DescriptorImageInfo storage{ + .imageView = *component_ll_views[c][input_level - 1], + .imageLayout = vk::ImageLayout::eGeneral, + }; + + descriptor_write = { + .dstSet = idwt_.ds[c][input_level], + .dstBinding = 1, + .descriptorCount = 1, + .descriptorType = vk::DescriptorType::eStorageImage, + .pImageInfo = &storage, + }; + + device.updateDescriptorSets(descriptor_write, {}); + } + } + } +} + +Decoder::~Decoder() +{ +} + +void Decoder::upload_payload(vk::raii::CommandBuffer & cmd) +{ + VkDeviceSize required_size = payload_data_cpu.size() * sizeof(uint32_t); + + // Avoid edge case OOB access without robustness on the payload buffer during dequant. + VkDeviceSize required_size_padded = required_size + 16; + + if (!payload_data || required_size_padded > payload_data.info().size) + { + vk::BufferCreateInfo info{ + .size = std::max(64 * 1024, required_size_padded * 2), + .usage = vk::BufferUsageFlagBits::eStorageBuffer | vk::BufferUsageFlagBits::eTransferDst + //| vk::BufferUsageFlagBits::eTransferSrc // DEBUG + , + }; + payload_data = buffer_allocation( + device, + info, + { + .flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_ALLOW_TRANSFER_INSTEAD_BIT | VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT, + .usage = VMA_MEMORY_USAGE_AUTO, + }, + "payload_data"); + + if (not(payload_data.properties() & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT)) + { + info.usage = vk::BufferUsageFlagBits::eTransferSrc; + payload_staging = buffer_allocation( + device, + info, + { + .flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT, + .usage = VMA_MEMORY_USAGE_AUTO, + }, + "payload_data staging"); + } + for (auto & x: dequant_.ds) + { + for (auto ds: x) + { + vk::DescriptorBufferInfo info{ + .buffer = payload_data, + .range = vk::WholeSize, + }; + + device.updateDescriptorSets(vk::WriteDescriptorSet{ + .dstSet = ds, + .dstBinding = 2, + .descriptorCount = 1, + .descriptorType = vk::DescriptorType::eStorageBuffer, + .pBufferInfo = &info, + }, + {}); + } + } + } + + if (payload_staging) + { + std::ranges::copy(payload_data_cpu, (uint32_t *)payload_staging.map()); + cmd.copyBuffer(payload_staging, payload_data, vk::BufferCopy{.size = required_size}); + } + else + { + std::ranges::copy(payload_data_cpu, (uint32_t *)payload_data.map()); + } +} + +bool Decoder::decode_packet(const BitstreamHeader * header) +{ + auto & offset = dequant_offset_buffer_cpu[header->block_index]; + if (offset == UINT32_MAX) + { + decoded_blocks++; + offset = payload_data_cpu.size(); + } + else + { + std::println(std::cerr, "block_index {} is already decoded, skipping.", header->block_index); + return true; + } + + auto * payload_words = reinterpret_cast(header); + + if (sizeof(*header) / sizeof(uint32_t) > header->payload_words) + { + std::println(std::cerr, "payload_words is not large enough."); + return false; + } + + payload_data_cpu.insert( + payload_data_cpu.end(), + payload_words, + payload_words + header->payload_words); + return true; +} + +bool Decoder::push_packet(const void * data_, size_t size) +{ + auto * data = static_cast(data_); + while (size >= sizeof(BitstreamHeader)) + { + auto * header = reinterpret_cast(data); + + if (header->extended != 0) + { + auto * seq = reinterpret_cast(header); + + if (sizeof(*header) > size) + { + std::print(std::cerr, "Parsing sequence header, but only {} bytes left to parse.", size); + return false; + } + + if (seq->chroma_resolution != int(chroma)) + { + std::print(std::cerr, "Chroma resolution mismatch!"); + return false; + } + + uint8_t diff = (header->sequence - last_seq) & SequenceCountMask; + if (last_seq != UINT32_MAX && diff > (SequenceCountMask / 2)) + { + // All sequences in a packet must be the same. + std::print(std::cerr, "Backwards sequence detected, discarding."); + return true; + } + + if (last_seq == UINT32_MAX || diff != 0) + { + clear(); + last_seq = header->sequence; + } + + if (seq->code == BITSTREAM_EXTENDED_CODE_START_OF_FRAME) + { + if (seq->width_minus_1 + 1 != width || seq->height_minus_1 + 1 != height) + { + std::print(std::cerr, "Dimension mismatch in seq packet, ({}, {}) != ({}, {})", seq->width_minus_1 + 1, seq->height_minus_1 + 1, width, height); + return false; + } + + total_blocks_in_sequence = int(seq->total_blocks); + } + else + { + std::print(std::cerr, "Unrecognized sequence header mode {}.", seq->code); + return false; + } + + data += sizeof(*header); + size -= sizeof(*header); + + continue; + } + + size_t packet_size = header->payload_words * sizeof(uint32_t); + + if (packet_size > size) + { + std::print(std::cerr, "Packet header states {} bytes, but only {} bytes left to parse.", packet_size, size); + return false; + } + + bool restart; + + if (last_seq == UINT32_MAX) + { + restart = true; + } + else + { + uint8_t diff = (header->sequence - last_seq) & SequenceCountMask; + if (diff > (SequenceCountMask / 2)) + { + // All sequences in a packet must be the same. + std::print(std::cerr, "Backwards sequence detected, discarding."); + return true; + } + restart = diff != 0; + } + + if (restart) + { + clear(); + last_seq = header->sequence; + } + + if (header->block_index >= uint32_t(block_count_32x32)) + { + std::print(std::cerr, "block_index {} is out of bounds (>= {}).", header->block_index, block_count_32x32); + return false; + } + + if (!decode_packet(header)) + return false; + + data += packet_size; + size -= packet_size; + } + + if (size != 0) + { + std::print(std::cerr, "Did not consume packet completely."); + return false; + } + + return true; +} + +bool Decoder::dequant(vk::raii::CommandBuffer & cmd) +{ + DequantizerPushData push = {}; + + cmd.bindPipeline(vk::PipelineBindPoint::eCompute, *dequant_.pipeline); + begin_label(cmd, "DWT dequant"); + // auto start_dequant = cmd.write_timestamp(VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT); + + vk::ImageMemoryBarrier image_barrier{ + .srcAccessMask = vk::AccessFlagBits::eNone, + .dstAccessMask = vk::AccessFlagBits::eShaderWrite, + .oldLayout = vk::ImageLayout::eUndefined, + .newLayout = vk::ImageLayout::eGeneral, + .image = wavelet_img_high_res, + .subresourceRange = { + .aspectMask = vk::ImageAspectFlagBits::eColor, + .levelCount = VK_REMAINING_MIP_LEVELS, + .layerCount = VK_REMAINING_ARRAY_LAYERS, + }, + }; + cmd.pipelineBarrier( + vk::PipelineStageFlagBits::eComputeShader, + vk::PipelineStageFlagBits::eComputeShader, + {}, + {}, + {}, + image_barrier); + + if (wavelet_img_low_res) + { + image_barrier.image = vk::Image(wavelet_img_low_res); + cmd.pipelineBarrier( + vk::PipelineStageFlagBits::eComputeShader, + vk::PipelineStageFlagBits::eComputeShader, + {}, + {}, + {}, + image_barrier); + } + + // De-quantize + for (int level = 0; level < DecompositionLevels; level++) + { + for (int component = 0; component < NumComponents; component++) + { + // Ignore top-level CbCr when doing 420 subsampling. + if (level == 0 && component != 0 && chroma == ChromaSubsampling::Chroma420) + continue; + + begin_label(cmd, std::format("level {} - component {}", level, component).c_str()); + + for (int band = (level == DecompositionLevels - 1 ? 0 : 1); band < 4; band++) + { + push.resolution.x = get_width(wavelet_img_high_res, level); + push.resolution.y = get_width(wavelet_img_high_res, level); + push.output_layer = band; + push.block_offset_32x32 = block_meta[component][level][band].block_offset_32x32; + push.block_stride_32x32 = block_meta[component][level][band].block_stride_32x32; + cmd.pushConstants(*dequant_.layout, vk::ShaderStageFlagBits::eCompute, 0, push); + + cmd.bindDescriptorSets(vk::PipelineBindPoint::eCompute, *dequant_.layout, 0, dequant_.ds[component][level], {}); + cmd.dispatch((push.resolution.x + 31) / 32, (push.resolution.y + 31) / 32, 1); + } + + end_label(cmd); + } + } + + vk::MemoryBarrier barrier{ + .srcAccessMask = vk::AccessFlagBits::eShaderWrite, + .dstAccessMask = vk::AccessFlagBits::eShaderRead, + }; + cmd.pipelineBarrier( + vk::PipelineStageFlagBits::eComputeShader, + vk::PipelineStageFlagBits::eComputeShader, + {}, + barrier, + {}, + {}); + + // auto end_dequant = cmd.write_timestamp(VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT); + end_label(cmd); + // device->register_time_interval("GPU", std::move(start_dequant), std::move(end_dequant), "Dequant"); + + return true; +} + +bool Decoder::idwt(vk::raii::CommandBuffer & cmd, const ViewBuffers & views) +{ + // auto start_idwt = cmd.write_timestamp(VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT); + + IDwtPushData push{}; + + for (int input_level = DecompositionLevels - 1; input_level >= 0; input_level--) + { + // Transposed. + push.resolution.x = component_ll_dim[0][input_level].height; + push.resolution.y = component_ll_dim[0][input_level].width; + push.inv_resolution.x = 1.0f / float(push.resolution.x); + push.inv_resolution.y = 1.0f / float(push.resolution.y); + cmd.pushConstants(*idwt_.layout, vk::ShaderStageFlagBits::eCompute, 0, push); + + if (input_level == 0) + { + cmd.bindPipeline(vk::PipelineBindPoint::eCompute, *idwt_dcshift); + if (chroma == ChromaSubsampling::Chroma444) + { + for (int c = 0; c < NumComponents; c++) + { + begin_label(cmd, std::format("iDWT final, component {}", c).c_str()); + vk::DescriptorImageInfo storage{ + .imageView = views[c], + .imageLayout = vk::ImageLayout::eGeneral, + }; + vk::WriteDescriptorSet descriptor_write{ + .dstSet = idwt_.ds[c][input_level], + .dstBinding = 1, + .descriptorCount = 1, + .descriptorType = vk::DescriptorType::eStorageImage, + .pImageInfo = &storage, + }; + device.updateDescriptorSets(descriptor_write, {}); + cmd.bindDescriptorSets(vk::PipelineBindPoint::eCompute, *idwt_.layout, 0, idwt_.ds[c][input_level], {}); + cmd.dispatch((push.resolution.x + 15) / 16, (push.resolution.y + 15) / 16, 1); + end_label(cmd); + } + } + else + { + begin_label(cmd, "iDWT final"); + vk::DescriptorImageInfo storage{ + .imageView = views[0], + .imageLayout = vk::ImageLayout::eGeneral, + }; + vk::WriteDescriptorSet descriptor_write{ + .dstSet = idwt_.ds[0][input_level], + .dstBinding = 1, + .descriptorCount = 1, + .descriptorType = vk::DescriptorType::eStorageImage, + .pImageInfo = &storage, + }; + device.updateDescriptorSets(descriptor_write, {}); + cmd.bindDescriptorSets(vk::PipelineBindPoint::eCompute, *idwt_.layout, 0, idwt_.ds[0][input_level], {}); + cmd.dispatch((push.resolution.x + 15) / 16, (push.resolution.y + 15) / 16, 1); + end_label(cmd); + } + } + else + { + for (int c = 0; c < NumComponents; c++) + { + begin_label(cmd, std::format("iDWT level {}, component {}", input_level, c).c_str()); + + if (chroma == ChromaSubsampling::Chroma420 && c != 0 && input_level == 1) + { + vk::DescriptorImageInfo storage{ + .imageView = views[c], + .imageLayout = vk::ImageLayout::eGeneral, + }; + vk::WriteDescriptorSet descriptor_write{ + .dstSet = idwt_.ds[c][input_level], + .dstBinding = 1, + .descriptorCount = 1, + .descriptorType = vk::DescriptorType::eStorageImage, + .pImageInfo = &storage, + }; + device.updateDescriptorSets(descriptor_write, {}); + cmd.bindPipeline(vk::PipelineBindPoint::eCompute, *idwt_dcshift); + } + else + { + cmd.bindPipeline(vk::PipelineBindPoint::eCompute, *idwt_.pipeline); + } + + cmd.bindDescriptorSets(vk::PipelineBindPoint::eCompute, *idwt_.layout, 0, idwt_.ds[c][input_level], {}); + cmd.dispatch((push.resolution.x + 15) / 16, (push.resolution.y + 15) / 16, 1); + end_label(cmd); + } + } + + vk::MemoryBarrier barrier{ + .srcAccessMask = vk::AccessFlagBits::eMemoryWrite, + .dstAccessMask = vk::AccessFlagBits::eMemoryRead, + }; + cmd.pipelineBarrier( + vk::PipelineStageFlagBits::eComputeShader, + vk::PipelineStageFlagBits::eComputeShader, + {}, + barrier, + {}, + {}); + } + + // auto end_idwt = cmd.write_timestamp(VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT); + // device->register_time_interval("GPU", std::move(start_idwt), std::move(end_idwt), "iDWT"); + return true; +} + +bool Decoder::decode_is_ready(bool allow_partial_frame) const +{ + if (decoded_frame_for_current_sequence) + return false; + + // Need at least half of the frame decoded to accept, otherwise we assume the frame is complete garbage. + if (decoded_blocks < total_blocks_in_sequence) + if (!allow_partial_frame || decoded_blocks <= total_blocks_in_sequence / 2) + return false; + + return true; +} + +bool Decoder::decode(vk::raii::CommandBuffer & cmd, const ViewBuffers & views) +{ + begin_label(cmd, "Decode uploads"); + { + upload_payload(cmd); + + if (dequant_staging) + { + std::ranges::copy(dequant_offset_buffer_cpu, (uint32_t *)dequant_staging.map()); + cmd.copyBuffer( + dequant_staging, + dequant_offset_buffer, + vk::BufferCopy{ + .size = dequant_offset_buffer_cpu.size() * sizeof(dequant_offset_buffer_cpu.front()), + }); + } + else + { + std::ranges::copy(dequant_offset_buffer_cpu, (uint32_t *)dequant_offset_buffer.map()); + } + + vk::MemoryBarrier barrier{ + .srcAccessMask = vk::AccessFlagBits::eMemoryWrite, + .dstAccessMask = vk::AccessFlagBits::eMemoryRead, + }; + cmd.pipelineBarrier( + vk::PipelineStageFlagBits::eTransfer, + vk::PipelineStageFlagBits::eComputeShader, + {}, + barrier, + {}, + {}); + } + end_label(cmd); + + if (!dequant(cmd)) + return false; + + vk::MemoryBarrier barrier{ + .srcAccessMask = vk::AccessFlagBits::eNone, + .dstAccessMask = vk::AccessFlagBits::eNone, + }; + cmd.pipelineBarrier( + vk::PipelineStageFlagBits::eComputeShader, + vk::PipelineStageFlagBits::eTransfer, + {}, + barrier, + {}, + {}); + + if (!idwt(cmd, views)) + return false; + + decoded_frame_for_current_sequence = true; + return true; +} + +void Decoder::clear() +{ + std::fill(dequant_offset_buffer_cpu.begin(), dequant_offset_buffer_cpu.end(), UINT32_MAX); + decoded_blocks = 0; + decoded_frame_for_current_sequence = false; + total_blocks_in_sequence = block_count_32x32; + payload_data_cpu.clear(); +} + +} // namespace PyroWave diff --git a/common/pyrowave/pyrowave_decoder.h b/common/pyrowave/pyrowave_decoder.h new file mode 100644 index 00000000..49d724c8 --- /dev/null +++ b/common/pyrowave/pyrowave_decoder.h @@ -0,0 +1,58 @@ +// Copyright (c) 2025 Hans-Kristian Arntzen +// SPDX-License-Identifier: MIT +#pragma once + +#include +#include +#include +#include +#include + +#include "pyrowave_common.h" + +namespace PyroWave +{ +class Decoder : public WaveletBuffers +{ + vk::raii::DescriptorPool ds_pool; + struct pipeline + { + vk::raii::DescriptorSetLayout ds_layout = nullptr; + vk::DescriptorSet ds[NumComponents][DecompositionLevels]; + vk::raii::PipelineLayout layout = nullptr; + vk::raii::Pipeline pipeline = nullptr; + }; + + buffer_allocation dequant_offset_buffer, payload_data, payload_staging, dequant_staging; + + pipeline dequant_; + pipeline idwt_; + vk::raii::Pipeline idwt_dcshift = nullptr; + + std::vector dequant_offset_buffer_cpu; + std::vector payload_data_cpu; + int decoded_blocks = 0; + int total_blocks_in_sequence = 0; + uint32_t last_seq = UINT32_MAX; + bool decoded_frame_for_current_sequence = false; + +public: + using ViewBuffers = std::array; + + Decoder(vk::raii::PhysicalDevice & phys_dev, vk::raii::Device & device, int width, int height, ChromaSubsampling chroma); + ~Decoder(); + + void clear(); + bool push_packet(const void * data, size_t size); + bool decode(vk::raii::CommandBuffer & cmd, const ViewBuffers & views); + bool decode_is_ready(bool allow_partial_frame) const; + +private: + bool decode_packet(const BitstreamHeader * header); + + bool dequant(vk::raii::CommandBuffer & cmd); + bool idwt(vk::raii::CommandBuffer & cmd, const ViewBuffers & views); + + void upload_payload(vk::raii::CommandBuffer & cmd); +}; +} // namespace PyroWave diff --git a/common/pyrowave/pyrowave_encoder.cpp b/common/pyrowave/pyrowave_encoder.cpp new file mode 100644 index 00000000..50d5f423 --- /dev/null +++ b/common/pyrowave/pyrowave_encoder.cpp @@ -0,0 +1,1647 @@ +// Copyright (c) 2025 Hans-Kristian Arntzen +// SPDX-License-Identifier: MIT +#include "pyrowave_encoder.h" +#include "pyrowave_common.h" +#include +#include +#include +#include + +#include +#include + +#define XSTR(s) STR(s) +#define STR(s) #s + +inline uint32_t next_pow2(uint32_t v) +{ + v--; + v |= v >> 16; + v |= v >> 8; + v |= v >> 4; + v |= v >> 2; + v |= v >> 1; + return v + 1; +} + +#define popcount32_(x) __builtin_popcount(x) +#define leading_zeroes_(x) ((x) == 0 ? 32 : __builtin_clz(x)) +#define trailing_zeroes_(x) ((x) == 0 ? 32 : __builtin_ctz(x)) +static inline uint32_t leading_zeroes(uint32_t x) +{ + return leading_zeroes_(x); +} +static inline uint32_t popcount32(uint32_t x) +{ + return popcount32_(x); +} +inline uint32_t floor_log2(uint32_t v) +{ + return 31 - leading_zeroes(v); +} +static inline uint32_t trailing_zeroes(uint32_t x) +{ + return trailing_zeroes_(x); +} + +template +inline void for_each_bit(uint32_t value, const T & func) +{ + while (value) + { + uint32_t bit = trailing_zeroes(value); + func(bit); + value &= ~(1u << bit); + } +} + +namespace PyroWave +{ + +static constexpr int BlockSpaceSubdivision = 16; +static constexpr int NumRDOBuckets = 128; +static constexpr int RDOBucketOffset = 64; + +static int compute_block_count_per_subdivision(int num_blocks) +{ + int per_subdivision = align(num_blocks, BlockSpaceSubdivision) / BlockSpaceSubdivision; + per_subdivision = int(next_pow2(per_subdivision)); + return per_subdivision; +} + +struct QuantizerPushData +{ + glm::ivec2 resolution; + glm::ivec2 resolution_8x8_blocks; + glm::vec2 inv_resolution; + float input_layer; + float quant_resolution; + int32_t block_offset; + int32_t block_stride; + float rdo_distortion_scale; +}; + +struct BlockPackingPushData +{ + glm::ivec2 resolution; + glm::ivec2 resolution_32x32_blocks; + glm::ivec2 resolution_8x8_blocks; + uint32_t quant_resolution_code; + uint32_t sequence_count; + uint32_t block_offset_32x32; + uint32_t block_stride_32x32; + uint32_t block_offset_8x8; + uint32_t block_stride_8x8; +}; + +struct AnalyzeRateControlPushData +{ + glm::ivec2 resolution; + glm::ivec2 resolution_8x8_blocks; + int32_t block_offset_8x8; + int32_t block_stride_8x8; + int32_t block_offset_32x32; + int32_t block_stride_32x32; + uint32_t total_wg_count; + uint32_t num_blocks_aligned; + uint32_t block_index_shamt; +}; +struct DwtPushData +{ + glm::uvec2 resolution; + glm::vec2 inv_resolution; + glm::uvec2 aligned_resolution; +}; + +struct RDOperation +{ + int32_t quant; + uint16_t block_offset; + uint16_t block_saving; +}; + +static vk::raii::DescriptorPool make_descriptor_pool(vk::raii::Device & device) +{ + std::array pool_sizes{ + vk::DescriptorPoolSize{ + .type = vk::DescriptorType::eStorageBuffer, + .descriptorCount = + 6 // block_packing + + 2 // resolve_rdo + + 2 // analyze_rdo / analyze_rdo_finalize + + 3 * NumComponents * DecompositionLevels // quant + }, + vk::DescriptorPoolSize{ + .type = vk::DescriptorType::eCombinedImageSampler, + .descriptorCount = + 2 * NumComponents * DecompositionLevels // quant + dwt + }, + vk::DescriptorPoolSize{ + .type = vk::DescriptorType::eStorageImage, + .descriptorCount = + NumComponents * DecompositionLevels // dwt + }, + }; + return {device, + vk::DescriptorPoolCreateInfo{ + .maxSets = + 3 // block_packing, resolve_rdo, (analyze_rdo / analyze_rdo_finalize) + + 2 * NumComponents * DecompositionLevels // quant + dwt + , + .poolSizeCount = pool_sizes.size(), + .pPoolSizes = pool_sizes.data(), + }}; +} + +Encoder::Encoder(vk::raii::PhysicalDevice & phys_dev, vk::raii::Device & device, int width, int height, ChromaSubsampling chroma) : + WaveletBuffers(device, width, height, chroma), + ds_pool(make_descriptor_pool(device)) +{ + auto [prop, prop11, prop13] = phys_dev.getProperties2(); + auto ops = prop11.subgroupSupportedOperations; + constexpr auto required_features = + vk::SubgroupFeatureFlagBits::eArithmetic | + vk::SubgroupFeatureFlagBits::eShuffle | + vk::SubgroupFeatureFlagBits::eShuffleRelative | + vk::SubgroupFeatureFlagBits::eVote | + vk::SubgroupFeatureFlagBits::eQuad | + vk::SubgroupFeatureFlagBits::eBallot | + vk::SubgroupFeatureFlagBits::eClustered | + vk::SubgroupFeatureFlagBits::eBasic; + + if ((ops & required_features) != required_features) + { + throw std::runtime_error("There are missing subgroup features. Device supports " + vk::to_string(ops) + ", but requires " + vk::to_string(required_features) + "."); + } + + auto [feat, feat12, feat13] = phys_dev.getFeatures2(); + + if (not feat12.subgroupBroadcastDynamicId) + throw std::runtime_error("Missing subgroupBroadcastDynamicId feature"); + + if (not feat12.storageBuffer8BitAccess) + throw std::runtime_error("Missing storageBuffer8BitAccess feature"); + + if (not feat12.shaderFloat16) + throw std::runtime_error("Missing shaderFloat16 feature"); + + if (not feat.features.shaderInt16) + throw std::runtime_error("Missing shaderInt16 feature"); + + if (not feat13.computeFullSubgroups) + throw std::runtime_error("Missing computeFullSubgroups feature"); + + // This should cover any HW I care about. + if (!supports_subgroup_size_log2(prop13, true, 4, 4) && + !supports_subgroup_size_log2(prop13, true, 5, 5) && + !supports_subgroup_size_log2(prop13, true, 6, 6)) + throw std::runtime_error("Device does not have the required subgroup properties"); + + // init block meta + { + init_block_meta(); + vk::BufferCreateInfo info{ + .usage = vk::BufferUsageFlagBits::eStorageBuffer | vk::BufferUsageFlagBits::eTransferDst + //| vk::BufferUsageFlagBits::eTransferSrc // DEBUG + , + }; + + info.size = block_count_8x8 * sizeof(BlockStats); + block_stat_buffer = buffer_allocation(device, info, {.usage = VMA_MEMORY_USAGE_AUTO}, "block_stat_buffer"); + // device->set_name(*block_stat_buffer, "block-stat-buffer"); + + info.size = block_count_8x8 * sizeof(BlockMeta); + meta_buffer = buffer_allocation(device, info, {.usage = VMA_MEMORY_USAGE_AUTO}, "meta_buffer"); + // device->set_name(*meta_buffer, "meta-buffer"); + + // Worst case estimate. + info.size = aligned_width * aligned_height * 2; + payload_data = buffer_allocation(device, info, {.usage = VMA_MEMORY_USAGE_AUTO}, "payload_data"); + // device->set_name(*payload_data, "payload-data"); + + info.size = block_count_32x32 * sizeof(uint32_t); + quant_buffer = buffer_allocation(device, info, {.usage = VMA_MEMORY_USAGE_AUTO}, "quant_buffer"); + // device->set_name(*quant_buffer, "quant-buffer"); + + info.size = RDOBucketOffset; + info.size += NumRDOBuckets * BlockSpaceSubdivision * sizeof(uint32_t); + info.size += NumRDOBuckets * compute_block_count_per_subdivision(block_count_32x32) * + BlockSpaceSubdivision * sizeof(RDOperation); + bucket_buffer = buffer_allocation(device, info, {.usage = VMA_MEMORY_USAGE_AUTO}, "bucket_buffer"); + // device->set_name(*bucket_buffer, "bucket-buffer"); + } + + // block_packing pipeline + { + std::array bindings{ + vk::DescriptorSetLayoutBinding{ + .binding = 0, + .descriptorType = vk::DescriptorType::eStorageBuffer, + .descriptorCount = 1, + .stageFlags = vk::ShaderStageFlagBits::eCompute, + }, + vk::DescriptorSetLayoutBinding{ + .binding = 1, + .descriptorType = vk::DescriptorType::eStorageBuffer, + .descriptorCount = 1, + .stageFlags = vk::ShaderStageFlagBits::eCompute, + }, + vk::DescriptorSetLayoutBinding{ + .binding = 2, + .descriptorType = vk::DescriptorType::eStorageBuffer, + .descriptorCount = 1, + .stageFlags = vk::ShaderStageFlagBits::eCompute, + }, + vk::DescriptorSetLayoutBinding{ + .binding = 3, + .descriptorType = vk::DescriptorType::eStorageBuffer, + .descriptorCount = 1, + .stageFlags = vk::ShaderStageFlagBits::eCompute, + }, + vk::DescriptorSetLayoutBinding{ + .binding = 4, + .descriptorType = vk::DescriptorType::eStorageBuffer, + .descriptorCount = 1, + .stageFlags = vk::ShaderStageFlagBits::eCompute, + }, + vk::DescriptorSetLayoutBinding{ + .binding = 5, + .descriptorType = vk::DescriptorType::eStorageBuffer, + .descriptorCount = 1, + .stageFlags = vk::ShaderStageFlagBits::eCompute, + }, + }; + block_packing_.ds_layout = device.createDescriptorSetLayout({ + .bindingCount = bindings.size(), + .pBindings = bindings.data(), + }); + + block_packing_.ds = device.allocateDescriptorSets({ + .descriptorPool = *ds_pool, + .descriptorSetCount = 1, + .pSetLayouts = &*block_packing_.ds_layout, + })[0] + .release(); + + vk::PushConstantRange pc{ + .stageFlags = vk::ShaderStageFlagBits::eCompute, + .size = sizeof(BlockPackingPushData), + }; + + block_packing_.layout = device.createPipelineLayout({ + .setLayoutCount = 1, + .pSetLayouts = &*block_packing_.ds_layout, + .pushConstantRangeCount = 1, + .pPushConstantRanges = &pc, + }); + const uint32_t min_subgroups = 1u << 4; + const uint32_t max_subgroups = 1u << 6; + + vk::PipelineShaderStageRequiredSubgroupSizeCreateInfoEXT subgroup_size{}; + auto shader = load_shader(device, "block_packing"); + vk::ComputePipelineCreateInfo info{ + .stage = { + .flags = vk::PipelineShaderStageCreateFlagBits::eRequireFullSubgroups, + .stage = vk::ShaderStageFlagBits::eCompute, + .module = *shader, + .pName = "main", + }, + .layout = *block_packing_.layout, + }; + pipeline_subgroup_info psi; + psi.set_subgroup_size(prop13, info, 4, 6); + block_packing_.pipeline = device.createComputePipeline( + nullptr, // FIXME: cache + info); + + std::array buffer_info{ + vk::DescriptorBufferInfo{ + .buffer = meta_buffer, + .range = vk::WholeSize, + }, + vk::DescriptorBufferInfo{ + .buffer = payload_data, + .range = vk::WholeSize, + }, + vk::DescriptorBufferInfo{ + .buffer = block_stat_buffer, + .range = vk::WholeSize, + }, + vk::DescriptorBufferInfo{ + .buffer = quant_buffer, + .range = vk::WholeSize, + }, + }; + + std::array descriptor_writes{ + vk::WriteDescriptorSet{ + .dstSet = block_packing_.ds, + .dstBinding = 2, + .descriptorCount = buffer_info.size(), + .descriptorType = vk::DescriptorType::eStorageBuffer, + .pBufferInfo = buffer_info.data(), + }, + }; + device.updateDescriptorSets(descriptor_writes, {}); + } + + // resolve rdo pipeline + { + std::array bindings{ + vk::DescriptorSetLayoutBinding{ + .binding = 0, + .descriptorType = vk::DescriptorType::eStorageBuffer, + .descriptorCount = 1, + .stageFlags = vk::ShaderStageFlagBits::eCompute, + }, + vk::DescriptorSetLayoutBinding{ + .binding = 1, + .descriptorType = vk::DescriptorType::eStorageBuffer, + .descriptorCount = 1, + .stageFlags = vk::ShaderStageFlagBits::eCompute, + }, + }; + resolve_rdo_.ds_layout = device.createDescriptorSetLayout({ + .bindingCount = bindings.size(), + .pBindings = bindings.data(), + }); + + resolve_rdo_.ds = device.allocateDescriptorSets({ + .descriptorPool = *ds_pool, + .descriptorSetCount = 1, + .pSetLayouts = &*resolve_rdo_.ds_layout, + })[0] + .release(); + + vk::PushConstantRange pc{ + .stageFlags = vk::ShaderStageFlagBits::eCompute, + .size = sizeof(uint32_t) * 2, + }; + + resolve_rdo_.layout = device.createPipelineLayout({ + .setLayoutCount = 1, + .pSetLayouts = &*resolve_rdo_.ds_layout, + .pushConstantRangeCount = 1, + .pPushConstantRanges = &pc, + }); + uint32_t block_space_subdivision; + vk::SpecializationMapEntry sp_entry{ + .constantID = 0, + .size = sizeof(block_space_subdivision), + }; + vk::SpecializationInfo sp{ + .mapEntryCount = 1, + .pMapEntries = &sp_entry, + .dataSize = sizeof(block_space_subdivision), + .pData = &block_space_subdivision, + }; + auto shader = load_shader(device, "resolve_rate_control"); + vk::ComputePipelineCreateInfo info{ + .stage = { + .flags = vk::PipelineShaderStageCreateFlagBits::eRequireFullSubgroups, + .stage = vk::ShaderStageFlagBits::eCompute, + .module = *shader, + .pName = "main", + .pSpecializationInfo = &sp, + }, + .layout = *resolve_rdo_.layout, + }; + pipeline_subgroup_info psi; + if (supports_subgroup_size_log2(prop13, true, 6, 6)) + { + block_space_subdivision = 64; + psi.set_subgroup_size(prop13, info, 6, 6); + } + else if (supports_subgroup_size_log2(prop13, true, 4, 4)) + { + block_space_subdivision = 16; + psi.set_subgroup_size(prop13, info, 4, 4); + } + else if (supports_subgroup_size_log2(prop13, true, 5, 5)) + { + block_space_subdivision = 32; + psi.set_subgroup_size(prop13, info, 5, 5); + } + else + { + assert(false); + } + resolve_rdo_.pipeline = device.createComputePipeline( + nullptr, // FIXME: cache + info); + + std::array buffer_info{ + vk::DescriptorBufferInfo{ + .buffer = bucket_buffer, + .range = vk::WholeSize, + }, + vk::DescriptorBufferInfo{ + .buffer = quant_buffer, + .range = vk::WholeSize, + }, + }; + + std::array descriptor_writes{ + vk::WriteDescriptorSet{ + .dstSet = resolve_rdo_.ds, + .dstBinding = 0, + .descriptorCount = buffer_info.size(), + .descriptorType = vk::DescriptorType::eStorageBuffer, + .pBufferInfo = buffer_info.data(), + }, + }; + device.updateDescriptorSets(descriptor_writes, {}); + } + + // analyze rdo pipeline + { + std::array bindings{ + vk::DescriptorSetLayoutBinding{ + .binding = 0, + .descriptorType = vk::DescriptorType::eStorageBuffer, + .descriptorCount = 1, + .stageFlags = vk::ShaderStageFlagBits::eCompute, + }, + vk::DescriptorSetLayoutBinding{ + .binding = 1, + .descriptorType = vk::DescriptorType::eStorageBuffer, + .descriptorCount = 1, + .stageFlags = vk::ShaderStageFlagBits::eCompute, + }, + }; + analyze_rdo_.ds_layout = device.createDescriptorSetLayout({ + .bindingCount = bindings.size(), + .pBindings = bindings.data(), + }); + + analyze_rdo_.ds = device.allocateDescriptorSets({ + .descriptorPool = *ds_pool, + .descriptorSetCount = 1, + .pSetLayouts = &*analyze_rdo_.ds_layout, + })[0] + .release(); + + vk::PushConstantRange pc{ + .stageFlags = vk::ShaderStageFlagBits::eCompute, + .size = sizeof(AnalyzeRateControlPushData), + }; + + analyze_rdo_.layout = device.createPipelineLayout({ + .setLayoutCount = 1, + .pSetLayouts = &*analyze_rdo_.ds_layout, + .pushConstantRangeCount = 1, + .pPushConstantRanges = &pc, + }); + auto shader = load_shader(device, "analyze_rate_control"); + vk::ComputePipelineCreateInfo info{ + .stage = { + .flags = vk::PipelineShaderStageCreateFlagBits::eRequireFullSubgroups, + .stage = vk::ShaderStageFlagBits::eCompute, + .module = *shader, + .pName = "main", + }, + .layout = *analyze_rdo_.layout, + }; + pipeline_subgroup_info psi; + if (supports_subgroup_size_log2(prop13, true, 4, 6)) + { + psi.set_subgroup_size(prop13, info, 4, 6); + } + else + { + assert(false); + } + analyze_rdo_.pipeline = device.createComputePipeline( + nullptr, // FIXME: cache + info); + + std::array buffer_info{ + vk::DescriptorBufferInfo{ + .buffer = bucket_buffer, + .range = vk::WholeSize, + }, + vk::DescriptorBufferInfo{ + .buffer = block_stat_buffer, + .range = vk::WholeSize, + }, + }; + + std::array descriptor_writes{ + vk::WriteDescriptorSet{ + .dstSet = analyze_rdo_.ds, + .dstBinding = 0, + .descriptorCount = buffer_info.size(), + .descriptorType = vk::DescriptorType::eStorageBuffer, + .pBufferInfo = buffer_info.data(), + }, + }; + device.updateDescriptorSets(descriptor_writes, {}); + } + + // analyze rdo finalize pipeline + { + vk::PushConstantRange pc{ + .stageFlags = vk::ShaderStageFlagBits::eCompute, + .size = sizeof(AnalyzeRateControlPushData), + }; + + analyze_rdo_finalize.layout = device.createPipelineLayout({ + .setLayoutCount = 1, + .pSetLayouts = &*analyze_rdo_.ds_layout, + .pushConstantRangeCount = 1, + .pPushConstantRanges = &pc, + }); + auto shader = load_shader(device, "analyze_rate_control_finalize"); + vk::ComputePipelineCreateInfo info{ + .stage = { + .stage = vk::ShaderStageFlagBits::eCompute, + .module = *shader, + .pName = "main", + }, + .layout = *analyze_rdo_finalize.layout, + }; + analyze_rdo_finalize.pipeline = device.createComputePipeline( + nullptr, // FIXME: cache + info); + } + + // quant pipeline + { + std::array bindings{ + vk::DescriptorSetLayoutBinding{ + .binding = 0, + .descriptorType = vk::DescriptorType::eCombinedImageSampler, + .descriptorCount = 1, + .stageFlags = vk::ShaderStageFlagBits::eCompute, + }, + vk::DescriptorSetLayoutBinding{ + .binding = 1, + .descriptorType = vk::DescriptorType::eStorageBuffer, + .descriptorCount = 1, + .stageFlags = vk::ShaderStageFlagBits::eCompute, + }, + vk::DescriptorSetLayoutBinding{ + .binding = 2, + .descriptorType = vk::DescriptorType::eStorageBuffer, + .descriptorCount = 1, + .stageFlags = vk::ShaderStageFlagBits::eCompute, + }, + vk::DescriptorSetLayoutBinding{ + .binding = 3, + .descriptorType = vk::DescriptorType::eStorageBuffer, + .descriptorCount = 1, + .stageFlags = vk::ShaderStageFlagBits::eCompute, + }, + }; + quant_.ds_layout = device.createDescriptorSetLayout({ + .bindingCount = bindings.size(), + .pBindings = bindings.data(), + }); + + vk::PushConstantRange pc{ + .stageFlags = vk::ShaderStageFlagBits::eCompute, + .size = sizeof(QuantizerPushData), + }; + + quant_.layout = device.createPipelineLayout({ + .setLayoutCount = 1, + .pSetLayouts = &*quant_.ds_layout, + .pushConstantRangeCount = 1, + .pPushConstantRanges = &pc, + }); + auto shader = load_shader(device, "wavelet_quant"); + vk::ComputePipelineCreateInfo info{ + .stage = { + .flags = vk::PipelineShaderStageCreateFlagBits::eRequireFullSubgroups, + .stage = vk::ShaderStageFlagBits::eCompute, + .module = *shader, + .pName = "main", + }, + .layout = *quant_.layout, + }; + assert(supports_subgroup_size_log2(prop13, true, 3, 7)); + pipeline_subgroup_info psi; + psi.set_subgroup_size(prop13, info, 3, 7); + quant_.pipeline = device.createComputePipeline( + nullptr, // FIXME: cache + info); + + for (int level = 0; level < DecompositionLevels; level++) + { + for (int component = 0; component < NumComponents; component++) + { + quant_ds[component][level] = device.allocateDescriptorSets({ + .descriptorPool = *ds_pool, + .descriptorSetCount = 1, + .pSetLayouts = &*quant_.ds_layout, + })[0] + .release(); + std::array image_info{ + vk::DescriptorImageInfo{ + .sampler = *border_sampler, + .imageView = *component_layer_views[component][level], + .imageLayout = vk::ImageLayout::eGeneral, + }, + }; + std::array buffer_info{ + vk::DescriptorBufferInfo{ + .buffer = meta_buffer, + .range = vk::WholeSize, + }, + vk::DescriptorBufferInfo{ + .buffer = block_stat_buffer, + .range = vk::WholeSize, + }, + vk::DescriptorBufferInfo{ + .buffer = payload_data, + .range = vk::WholeSize, + }, + }; + + std::array descriptor_writes{ + vk::WriteDescriptorSet{ + .dstSet = quant_ds[component][level], + .dstBinding = 0, + .descriptorCount = image_info.size(), + .descriptorType = vk::DescriptorType::eCombinedImageSampler, + .pImageInfo = image_info.data(), + }, + vk::WriteDescriptorSet{ + .dstSet = quant_ds[component][level], + .dstBinding = 1, + .descriptorCount = buffer_info.size(), + .descriptorType = vk::DescriptorType::eStorageBuffer, + .pBufferInfo = buffer_info.data(), + }, + }; + device.updateDescriptorSets(descriptor_writes, {}); + } + } + } + + // dwt pipeline + { + std::array bindings{ + vk::DescriptorSetLayoutBinding{ + .binding = 0, + .descriptorType = vk::DescriptorType::eCombinedImageSampler, + .descriptorCount = 1, + .stageFlags = vk::ShaderStageFlagBits::eCompute, + }, + vk::DescriptorSetLayoutBinding{ + .binding = 1, + .descriptorType = vk::DescriptorType::eStorageImage, + .descriptorCount = 1, + .stageFlags = vk::ShaderStageFlagBits::eCompute, + }, + }; + dwt_.ds_layout = device.createDescriptorSetLayout({ + .bindingCount = bindings.size(), + .pBindings = bindings.data(), + }); + + vk::PushConstantRange pc{ + .stageFlags = vk::ShaderStageFlagBits::eCompute, + .size = sizeof(DwtPushData), + }; + + dwt_.layout = device.createPipelineLayout({ + .setLayoutCount = 1, + .pSetLayouts = &*dwt_.ds_layout, + .pushConstantRangeCount = 1, + .pPushConstantRanges = &pc, + }); + VkBool32 dc_shift = false; + vk::SpecializationMapEntry sp_entry{ + .constantID = 0, + .size = sizeof(dc_shift), + }; + vk::SpecializationInfo sp{ + .mapEntryCount = 1, + .pMapEntries = &sp_entry, + .dataSize = sizeof(dc_shift), + .pData = &dc_shift, + }; + auto shader = load_shader(device, "dwt_" XSTR(PYROWAVE_PRECISION)); + vk::ComputePipelineCreateInfo info{ + .stage = { + .flags = vk::PipelineShaderStageCreateFlagBits::eRequireFullSubgroups, + .stage = vk::ShaderStageFlagBits::eCompute, + .module = *shader, + .pName = "main", + .pSpecializationInfo = &sp, + }, + .layout = *dwt_.layout, + }; + pipeline_subgroup_info psi; + // Only need simple 2-lane swaps. + psi.set_subgroup_size(prop13, info, 2, 7); + dwt_.pipeline = device.createComputePipeline( + nullptr, // FIXME: cache + info); + + dc_shift = true; + dwt_dcshift = device.createComputePipeline( + nullptr, // FIXME: cache + info); + + for (int level = 0; level < DecompositionLevels; level++) + { + for (int component = 0; component < NumComponents; component++) + { + dwt_ds[component][level] = device.allocateDescriptorSets({ + .descriptorPool = *ds_pool, + .descriptorSetCount = 1, + .pSetLayouts = &*dwt_.ds_layout, + })[0] + .release(); + + vk::DescriptorImageInfo storage{ + .imageView = *component_layer_views[component][level], + .imageLayout = vk::ImageLayout::eGeneral, + }; + vk::WriteDescriptorSet descriptor_write{ + .dstSet = dwt_ds[component][level], + .dstBinding = 1, + .descriptorCount = 1, + .descriptorType = vk::DescriptorType::eStorageImage, + .pImageInfo = &storage, + }; + device.updateDescriptorSets(descriptor_write, {}); + + // Updated with input image + if (level == 0) + continue; + if (level == 1 and component > 0 and chroma == ChromaSubsampling::Chroma420) + continue; + + vk::DescriptorImageInfo sampled{ + .sampler = *mirror_repeat_sampler, + .imageView = *component_ll_views[component][level - 1], + .imageLayout = vk::ImageLayout::eGeneral, + }; + + descriptor_write = { + .dstSet = dwt_ds[component][level], + .dstBinding = 0, + .descriptorCount = 1, + .descriptorType = vk::DescriptorType::eCombinedImageSampler, + .pImageInfo = &sampled, + }; + + device.updateDescriptorSets(descriptor_write, {}); + } + } + } + + /* + { + vk::BufferCreateInfo info{ + .size = vk::DeviceSize(width * height * 4), + .usage = vk::BufferUsageFlagBits::eStorageBuffer | vk::BufferUsageFlagBits::eTransferDst, + }; + debug_buffer = buffer_allocation(device, info, {.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT, .usage = VMA_MEMORY_USAGE_AUTO}, "block_stat_buffer"); + } + */ +} + +float Encoder::get_quant_rdo_distortion_scale(int level, int component, int band) const +{ + // From my Linelet master thesis. Copy paste 11 years later, ah yes :D + float horiz_midpoint = (band & 1) ? 0.75f : 0.25f; + float vert_midpoint = (band & 2) ? 0.75f : 0.25f; + + // Normal PC monitors. + constexpr float dpi = 96.0f; + // Compromise between couch gaming and desktop. + constexpr float viewing_distance = 1.0f; + constexpr float cpd_nyquist = 0.34f * viewing_distance * dpi; + + float cpd = std::sqrt(horiz_midpoint * horiz_midpoint + vert_midpoint * vert_midpoint) * + cpd_nyquist * std::exp2(-float(level)); + + // Don't allow a situation where we're quantizing LL band hard. + cpd = std::max(cpd, 8.0f); + + float csf = 2.6f * (0.0192f + 0.114f * cpd) * std::exp(-std::pow(0.114f * cpd, 1.1f)); + + // Heavily discount chroma quality. + if (component != 0 && level != DecompositionLevels - 1) + { + // Consider chroma a little more important if we're not subsampling. + if (chroma == ChromaSubsampling::Chroma420) + csf *= 0.6f; + } + + // Due to filtering, distortion in lower bands will result in more noise power. + // By scaling the distortion by this factor, we ensure uniform results. + float resolution = get_noise_power_normalized_quant_resolution(level, component, band); + float weighted_resolution = csf * resolution; + + // The distortion is scaled in terms of power, not amplitude. + return weighted_resolution * weighted_resolution; +} + +float Encoder::get_quant_resolution(int level, int component, int band) const +{ + // FP16 range is limited, and this is more than a good enough initial estimate. + return std::min( + Configuration::get().get_precision() >= 1 ? 4096.0f : 512.0f, + get_noise_power_normalized_quant_resolution(level, component, band)); +} + +float Encoder::get_noise_power_normalized_quant_resolution(int level, int component, int band) const +{ + // The initial quantization resolution aims for a flat spectrum with noise power normalization. + // The low-pass gain for CDF 9/7 is 6 dB (1 bit). Every decomposition level subtracts 6 dB. + + // Maybe make this based on the max rate to have a decent initial estimate. + int bits = Configuration::get().get_precision() >= 1 ? 8 : 6; + + if (band == 0) + bits += 2; + else if (band < 3) + bits += 1; + + bits += level; + + // Chroma starts at level 1, subtract one bit. + if (component != 0) + bits--; + + return float(1 << bits); +} + +bool Encoder::block_packing(vk::raii::CommandBuffer & cmd, const BitstreamBuffers & buffers, float quant_scale) +{ + // debug utils + begin_label(cmd, "DWT block packing"); + + // timing + // auto start_packing = cmd.write_timestamp(VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT); + + std::array ds_buffers{ + vk::DescriptorBufferInfo{ + .buffer = buffers.bitstream.buffer, + .offset = buffers.bitstream.offset, + .range = buffers.bitstream.size, + }, + vk::DescriptorBufferInfo{ + .buffer = buffers.meta.buffer, + .offset = buffers.meta.offset, + .range = buffers.meta.size, + }, + }; + vk::WriteDescriptorSet descriptor_write{ + .dstSet = block_packing_.ds, + .dstBinding = 0, + .descriptorCount = ds_buffers.size(), + .descriptorType = vk::DescriptorType::eStorageBuffer, + .pBufferInfo = ds_buffers.data(), + }; + device.updateDescriptorSets(descriptor_write, {}); + cmd.bindPipeline(vk::PipelineBindPoint::eCompute, *block_packing_.pipeline); + cmd.bindDescriptorSets(vk::PipelineBindPoint::eCompute, *block_packing_.layout, 0, block_packing_.ds, {}); + + for (int level = 0; level < DecompositionLevels; level++) + { + auto level_width = get_width(wavelet_img_high_res, level); + auto level_height = get_height(wavelet_img_high_res, level); + + for (int component = 0; component < NumComponents; component++) + { + // Ignore top-level CbCr when doing 420 subsampling. + if (level == 0 && component != 0 && chroma == ChromaSubsampling::Chroma420) + continue; + + begin_label(cmd, std::format("level {}, component {}", level, component).c_str()); + + for (int band = (level == DecompositionLevels - 1 ? 0 : 1); band < 4; band++) + { + BlockPackingPushData packing_push = {}; + packing_push.resolution = glm::ivec2(level_width, level_height); + packing_push.resolution_32x32_blocks = glm::ivec2((level_width + 31) / 32, (level_height + 31) / 32); + packing_push.resolution_8x8_blocks = glm::ivec2((level_width + 7) / 8, (level_height + 7) / 8); + + auto quant_res = quant_scale < 0.0f ? get_quant_resolution(level, component, band) : quant_scale; + packing_push.quant_resolution_code = encode_quant(1.0f / quant_res); + packing_push.sequence_count = sequence_count; + + auto & meta = block_meta[component][level][band]; + + packing_push.block_offset_32x32 = meta.block_offset_32x32; + packing_push.block_stride_32x32 = meta.block_stride_32x32; + packing_push.block_offset_8x8 = meta.block_offset_8x8; + packing_push.block_stride_8x8 = meta.block_stride_8x8; + cmd.pushConstants(*block_packing_.layout, vk::ShaderStageFlagBits::eCompute, 0, packing_push); + + cmd.dispatch((packing_push.resolution_32x32_blocks.x + 1) / 2, + (packing_push.resolution_32x32_blocks.y + 1) / 2, + 1); + } + + end_label(cmd); + } + } + + // auto end_packing = cmd.write_timestamp(VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT); + vk::MemoryBarrier barrier{ + .srcAccessMask = vk::AccessFlagBits::eShaderWrite, + .dstAccessMask = vk::AccessFlagBits::eShaderWrite | vk::AccessFlagBits::eTransferWrite | vk::AccessFlagBits::eTransferRead, + }; + cmd.pipelineBarrier( + vk::PipelineStageFlagBits::eComputeShader, + vk::PipelineStageFlagBits::eAllCommands, // FIXME: clear and copy bits + {}, + barrier, + {}, + {}); + // cmd.barrier(VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_2_SHADER_STORAGE_WRITE_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT | VK_PIPELINE_STAGE_2_CLEAR_BIT | VK_PIPELINE_STAGE_2_COPY_BIT, VK_ACCESS_2_SHADER_STORAGE_WRITE_BIT | VK_ACCESS_2_TRANSFER_WRITE_BIT | VK_ACCESS_2_TRANSFER_READ_BIT); + + // device->register_time_interval("GPU", std::move(start_packing), std::move(end_packing), "Packing"); + end_label(cmd); + + return true; +} + +bool Encoder::resolve_rdo(vk::raii::CommandBuffer & cmd, size_t target_payload_size) +{ + begin_label(cmd, "DWT resolve"); + + // auto start_resolve = cmd.write_timestamp(VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT); + + if (target_payload_size >= sizeof(BitstreamSequenceHeader)) + target_payload_size -= sizeof(BitstreamSequenceHeader); + + cmd.bindPipeline(vk::PipelineBindPoint::eCompute, *resolve_rdo_.pipeline); + cmd.bindDescriptorSets(vk::PipelineBindPoint::eCompute, *resolve_rdo_.layout, 0, resolve_rdo_.ds, {}); + + struct + { + uint32_t target_payload_size; + uint32_t num_blocks_per_subdivision; + } push = {}; + + push.target_payload_size = target_payload_size / sizeof(uint32_t); + push.num_blocks_per_subdivision = compute_block_count_per_subdivision(block_count_32x32); + cmd.pushConstants(*resolve_rdo_.layout, vk::ShaderStageFlagBits::eCompute, 0, push); + cmd.dispatch(NumRDOBuckets * BlockSpaceSubdivision, 1, 1); + + vk::MemoryBarrier barrier{ + .srcAccessMask = vk::AccessFlagBits::eShaderWrite, + .dstAccessMask = vk::AccessFlagBits::eShaderRead, + }; + cmd.pipelineBarrier( + vk::PipelineStageFlagBits::eComputeShader, + vk::PipelineStageFlagBits::eComputeShader, + {}, + barrier, + {}, + {}); + // cmd.barrier(VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_2_SHADER_STORAGE_WRITE_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_2_SHADER_STORAGE_READ_BIT); + end_label(cmd); + + // auto end_resolve = cmd.write_timestamp(VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT); + // device->register_time_interval("GPU", std::move(start_resolve), std::move(end_resolve), "Resolve"); + return true; +} + +bool Encoder::analyze_rdo(vk::raii::CommandBuffer & cmd) +{ + // auto start_analyze = cmd.write_timestamp(VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT); + begin_label(cmd, "DWT analyze"); + cmd.bindPipeline(vk::PipelineBindPoint::eCompute, *analyze_rdo_.pipeline); + cmd.bindDescriptorSets(vk::PipelineBindPoint::eCompute, *analyze_rdo_.layout, 0, analyze_rdo_.ds, {}); + + // Quantize + for (int level = 0; level < DecompositionLevels; level++) + { + for (int component = 0; component < NumComponents; component++) + { + // Ignore top-level CbCr when doing 420 subsampling. + if (level == 0 && component != 0 && chroma == ChromaSubsampling::Chroma420) + continue; + + AnalyzeRateControlPushData push = {}; + + begin_label(cmd, std::format("level {}, component {}", level, component).c_str()); + + for (int band = (level == DecompositionLevels - 1 ? 0 : 1); band < 4; band++) + { + auto level_width = get_width(wavelet_img_high_res, level); + auto level_height = get_height(wavelet_img_high_res, level); + + push.resolution.x = level_width; + push.resolution.y = level_height; + push.resolution_8x8_blocks.x = (level_width + 7) / 8; + push.resolution_8x8_blocks.y = (level_height + 7) / 8; + push.block_offset_8x8 = block_meta[component][level][band].block_offset_8x8; + push.block_stride_8x8 = block_meta[component][level][band].block_stride_8x8; + push.block_offset_32x32 = block_meta[component][level][band].block_offset_32x32; + push.block_stride_32x32 = block_meta[component][level][band].block_stride_32x32; + push.total_wg_count = block_count_32x32; + push.num_blocks_aligned = compute_block_count_per_subdivision(block_count_32x32) * BlockSpaceSubdivision; + push.block_index_shamt = floor_log2(compute_block_count_per_subdivision(block_count_32x32)); + + cmd.pushConstants(*analyze_rdo_.layout, vk::ShaderStageFlagBits::eCompute, 0, push); + + cmd.dispatch((level_width + 31) / 32, (level_height + 31) / 32, 1); + } + + end_label(cmd); + } + } + + vk::MemoryBarrier barrier{ + .srcAccessMask = vk::AccessFlagBits::eShaderWrite, + .dstAccessMask = vk::AccessFlagBits::eShaderRead, + }; + cmd.pipelineBarrier( + vk::PipelineStageFlagBits::eComputeShader, + vk::PipelineStageFlagBits::eComputeShader, // FIXME: clear and copy bits + {}, + barrier, + {}, + {}); + // cmd.barrier(VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_2_SHADER_STORAGE_WRITE_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_2_SHADER_STORAGE_READ_BIT); + + cmd.bindPipeline(vk::PipelineBindPoint::eCompute, *analyze_rdo_finalize.pipeline); + cmd.dispatch(1, 1, 1); + + cmd.pipelineBarrier( + vk::PipelineStageFlagBits::eComputeShader, + vk::PipelineStageFlagBits::eComputeShader, // FIXME: clear and copy bits + {}, + barrier, + {}, + {}); + // cmd.barrier(VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_2_SHADER_STORAGE_WRITE_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_2_SHADER_STORAGE_READ_BIT); + + end_label(cmd); + // auto end_analyze = cmd.write_timestamp(VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT); + // device->register_time_interval("GPU", std::move(start_analyze), std::move(end_analyze), "Analyze"); + return true; +} + +bool Encoder::quant(vk::raii::CommandBuffer & cmd, float quant_scale) +{ + // auto start_quant = cmd.write_timestamp(VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT); + begin_label(cmd, "DWT quantize"); + cmd.bindPipeline(vk::PipelineBindPoint::eCompute, *quant_.pipeline); + + // Quantize + for (int level = 0; level < DecompositionLevels; level++) + { + for (int component = 0; component < NumComponents; component++) + { + // Ignore top-level CbCr when doing 420 subsampling. + if (level == 0 && component != 0 && chroma == ChromaSubsampling::Chroma420) + continue; + + QuantizerPushData push = {}; + + begin_label(cmd, std::format("DWT quant level {}, component {}", level, component).c_str()); + + for (int band = (level == DecompositionLevels - 1 ? 0 : 1); band < 4; band++) + { + float quant_res = quant_scale < 0.0f ? get_quant_resolution(level, component, band) : quant_scale; + + push.resolution.x = get_width(wavelet_img_high_res, level); + push.resolution.y = get_height(wavelet_img_high_res, level); + push.resolution_8x8_blocks.x = (push.resolution.x + 7) / 8; + push.resolution_8x8_blocks.y = (push.resolution.y + 7) / 8; + push.inv_resolution.x = 1.0f / float(push.resolution.x); + push.inv_resolution.y = 1.0f / float(push.resolution.y); + push.input_layer = float(band); + push.quant_resolution = 1.0f / decode_quant(encode_quant(1.0f / quant_res)); + push.rdo_distortion_scale = get_quant_rdo_distortion_scale(level, component, band) * (1.0f / 256.0f); + + int blocks_x = (push.resolution.x + 31) / 32; + int blocks_y = (push.resolution.y + 31) / 32; + + push.block_offset = block_meta[component][level][band].block_offset_8x8; + push.block_stride = block_meta[component][level][band].block_stride_8x8; + + cmd.pushConstants(*quant_.layout, vk::ShaderStageFlagBits::eCompute, 0, push); + cmd.bindDescriptorSets(vk::PipelineBindPoint::eCompute, *quant_.layout, 0, quant_ds[component][level], {}); + + cmd.dispatch(blocks_x, blocks_y, 1); + } + + end_label(cmd); + } + } + + end_label(cmd); + // cmd.barrier(VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_2_SHADER_STORAGE_WRITE_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_2_SHADER_STORAGE_READ_BIT); + vk::MemoryBarrier barrier{ + .srcAccessMask = vk::AccessFlagBits::eShaderWrite, + .dstAccessMask = vk::AccessFlagBits::eShaderRead, + }; + cmd.pipelineBarrier( + vk::PipelineStageFlagBits::eComputeShader, + vk::PipelineStageFlagBits::eComputeShader, + {}, + barrier, + {}, + {}); + + // auto end_quant = cmd.write_timestamp(VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT); + // device->register_time_interval("GPU", std::move(start_quant), std::move(end_quant), "Quant"); + return true; +} + +bool Encoder::dwt(vk::raii::CommandBuffer & cmd, const ViewBuffers & views) +{ + DwtPushData push = {}; + + // Forward transforms. + + // auto start_dwt = cmd.write_timestamp(VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT); + + for (int output_level = 0; output_level < DecompositionLevels; output_level++) + { + if (output_level > 0) + { + push.resolution = glm::uvec2(component_ll_dim[0][output_level - 1].width, + component_ll_dim[0][output_level - 1].height); + push.aligned_resolution = push.resolution; + } + else + { + // FIXME: correct dimensions? original code uses views information + push.resolution = glm::uvec2(width, height); + push.aligned_resolution.x = aligned_width; + push.aligned_resolution.y = aligned_height; + } + + push.inv_resolution.x = 1.0f / float(push.resolution.x); + push.inv_resolution.y = 1.0f / float(push.resolution.y); + cmd.pushConstants(*dwt_.layout, vk::ShaderStageFlagBits::eCompute, 0, push); + + if (output_level == 0) + { + cmd.bindPipeline(vk::PipelineBindPoint::eCompute, *dwt_dcshift); + + if (chroma == ChromaSubsampling::Chroma444) + { + for (int c = 0; c < NumComponents; c++) + { + vk::DescriptorImageInfo sampled{ + .sampler = *mirror_repeat_sampler, + .imageView = views[c], + .imageLayout = vk::ImageLayout::eGeneral, + }; + vk::WriteDescriptorSet descriptor_write{ + .dstSet = dwt_ds[c][0], + .dstBinding = 0, + .descriptorCount = 1, + .descriptorType = vk::DescriptorType::eCombinedImageSampler, + .pImageInfo = &sampled, + }; + device.updateDescriptorSets(descriptor_write, {}); + cmd.bindDescriptorSets(vk::PipelineBindPoint::eCompute, *dwt_.layout, 0, dwt_ds[c][0], {}); + begin_label(cmd, std::format("DWT level 0, component {}", c).c_str()); + cmd.dispatch((push.aligned_resolution.x + 31) / 32, (push.aligned_resolution.y + 31) / 32, 1); + end_label(cmd); + } + } + else + { + begin_label(cmd, "DWT level 0 Y"); + vk::DescriptorImageInfo sampled{ + .sampler = *mirror_repeat_sampler, + .imageView = views[0], + .imageLayout = vk::ImageLayout::eGeneral, + }; + vk::WriteDescriptorSet descriptor_write{ + .dstSet = dwt_ds[0][0], + .dstBinding = 0, + .descriptorCount = 1, + .descriptorType = vk::DescriptorType::eCombinedImageSampler, + .pImageInfo = &sampled, + }; + device.updateDescriptorSets(descriptor_write, {}); + cmd.bindDescriptorSets(vk::PipelineBindPoint::eCompute, *dwt_.layout, 0, dwt_ds[0][0], {}); + cmd.dispatch((push.aligned_resolution.x + 31) / 32, (push.aligned_resolution.y + 31) / 32, 1); + end_label(cmd); + } + } + else + { + for (int c = 0; c < NumComponents; c++) + { + begin_label(cmd, std::format("DWT level {}, component {}", output_level, c).c_str()); + if (chroma == ChromaSubsampling::Chroma420 && c != 0 && output_level == 1) + { + vk::DescriptorImageInfo sampled{ + .sampler = *mirror_repeat_sampler, + .imageView = views[c], + .imageLayout = vk::ImageLayout::eGeneral, + }; + vk::WriteDescriptorSet descriptor_write{ + .dstSet = dwt_ds[c][1], + .dstBinding = 0, + .descriptorCount = 1, + .descriptorType = vk::DescriptorType::eCombinedImageSampler, + .pImageInfo = &sampled, + }; + device.updateDescriptorSets(descriptor_write, {}); + cmd.bindDescriptorSets(vk::PipelineBindPoint::eCompute, *dwt_.layout, 0, dwt_ds[c][output_level], {}); + cmd.bindPipeline(vk::PipelineBindPoint::eCompute, *dwt_dcshift); + + // FIXME: correct dimensions? original code uses views information + push.resolution = glm::uvec2(width / 2, height / 2); + + push.aligned_resolution.x = aligned_width >> output_level; + push.aligned_resolution.y = aligned_height >> output_level; + push.inv_resolution.x = 1.0f / float(push.resolution.x); + push.inv_resolution.y = 1.0f / float(push.resolution.y); + cmd.pushConstants(*dwt_.layout, vk::ShaderStageFlagBits::eCompute, 0, push); + } + else + { + cmd.bindDescriptorSets(vk::PipelineBindPoint::eCompute, *dwt_.layout, 0, dwt_ds[c][output_level], {}); + cmd.bindPipeline(vk::PipelineBindPoint::eCompute, *dwt_.pipeline); + } + cmd.dispatch((push.aligned_resolution.x + 31) / 32, (push.aligned_resolution.y + 31) / 32, 1); + end_label(cmd); + } + } + + // cmd.barrier(VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_2_SHADER_STORAGE_WRITE_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_2_SHADER_SAMPLED_READ_BIT); + vk::MemoryBarrier barrier{ + .srcAccessMask = vk::AccessFlagBits::eMemoryWrite, + .dstAccessMask = vk::AccessFlagBits::eMemoryRead, + }; + cmd.pipelineBarrier( + vk::PipelineStageFlagBits::eComputeShader, + vk::PipelineStageFlagBits::eTransfer | // FIXME: remove + vk::PipelineStageFlagBits::eComputeShader, + {}, + barrier, + {}, + {}); + } + + // auto end_dwt = cmd.write_timestamp(VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT); + // device->register_time_interval("GPU", std::move(start_dwt), std::move(end_dwt), "DWT"); + return true; +} + +size_t Encoder::compute_num_packets(const void * meta_, size_t packet_boundary) const +{ + auto * meta = static_cast(meta_); + size_t num_packets = 0; + size_t size_in_packet = 0; + + size_in_packet += sizeof(BitstreamSequenceHeader); + + for (int i = 0; i < block_count_32x32; i++) + { + size_t packet_size = meta[i].num_words * sizeof(uint32_t); + if (!packet_size) + continue; + + if (size_in_packet + packet_size > packet_boundary) + { + size_in_packet = 0; + num_packets++; + } + + size_in_packet += packet_size; + } + + if (size_in_packet) + num_packets++; + + return num_packets; +} + +bool Encoder::validate_bitstream( + const uint32_t * bitstream_u32, + const BitstreamPacket * meta, + uint32_t block_index) const +{ + if (meta[block_index].num_words == 0) + return true; + + bitstream_u32 += meta[block_index].offset_u32; + auto * header = reinterpret_cast(bitstream_u32); + if (header->block_index != block_index) + { + std::println(std::cerr, "Mismatch in block index. header: {}, meta: {}", header->block_index, block_index); + return false; + } + + if (header->payload_words != meta[block_index].num_words) + { + std::println(std::cerr, "Mismatch in payload words, header: {}, meta: {}", header->payload_words, meta[block_index].num_words); + return false; + } + + // 32x32 block layout: + // N = popcount(ballot) + // N * u16 control words. 2 bits per active 4x2 block. + // N * u8 control words. 4 bits Q, 4 bits quant scale. + // Plane data: M * u8. + // Tightly packed sign data follows. Depends on number of significant values while decoding plane data. + + int blocks_8x8 = int(popcount32(header->ballot)); + auto * bitstream_u8 = reinterpret_cast(bitstream_u32); + auto * block_control_words = reinterpret_cast(bitstream_u32 + 2); + auto * q_control_words = reinterpret_cast(block_control_words + blocks_8x8); + uint32_t offset = sizeof(BitstreamHeader) + 3 * blocks_8x8; + + if (offset > header->payload_words * 4) + { + std::println(std::cerr, "payload_words is not large enough."); + return false; + } + + const auto & mapping = block_32x32_to_8x8_mapping[header->block_index]; + bool invalid_packet = false; + int num_significant_values = 0; + + for_each_bit(header->ballot, [&](unsigned bit) { + int x = int(bit & 3); + int y = int(bit >> 2); + + if (x < mapping.block_width_8x8 && y < mapping.block_height_8x8) + { + auto q_bits = *q_control_words & 0xf; + + for (int subblock_offset = 0; subblock_offset < 16; subblock_offset += 2) + { + int num_planes = q_bits + ((*block_control_words >> subblock_offset) & 3); + int plane_significance = 0; + for (int plane = 0; plane < num_planes; plane++) + plane_significance |= bitstream_u8[offset++]; + num_significant_values += int(popcount32(plane_significance)); + } + + block_control_words++; + q_control_words++; + } + else + { + std::println(std::cerr, + "block_index {}: 8x8 block is out of bounds. ({}, {}) >= ({}, {})", + block_index, + x, + y, + mapping.block_width_8x8, + mapping.block_height_8x8); + invalid_packet = true; + } + }); + + if (invalid_packet) + return false; + + // We expect this many sign bits to have come through. + offset += (num_significant_values + 7) / 8; + + auto offset_words = (offset + 3) / 4; + + if (offset_words != header->payload_words) + { + std::println(std::cerr, "Block index {}, offset {} != {}", block_index, offset_words, header->payload_words); + return false; + } + + return true; +} + +size_t Encoder::packetize(Packet * packets, size_t packet_boundary, void * output_bitstream_, size_t size, const void * mapped_meta, const void * mapped_bitstream) const +{ + size_t num_packets = 0; + size_t size_in_packet = 0; + size_t packet_offset = 0; + size_t output_offset = 0; + auto * meta = static_cast(mapped_meta); + auto * input_bitstream = static_cast(mapped_bitstream); + auto * output_bitstream = static_cast(output_bitstream_); + (void)size; + + size_t num_non_zero_blocks = 0; + for (int i = 0; i < block_count_32x32; i++) + if (meta[i].num_words != 0) + num_non_zero_blocks++; + + BitstreamSequenceHeader header = {}; + header.width_minus_1 = width - 1; + header.height_minus_1 = height - 1; + header.sequence = reinterpret_cast(input_bitstream + meta[0].offset_u32)->sequence; + header.extended = 1; + header.code = BITSTREAM_EXTENDED_CODE_START_OF_FRAME; + header.total_blocks = num_non_zero_blocks; + header.chroma_resolution = chroma == ChromaSubsampling::Chroma444 ? CHROMA_RESOLUTION_444 : CHROMA_RESOLUTION_420; + + assert(sizeof(header) <= size); + memcpy(output_bitstream, &header, sizeof(header)); + output_offset += sizeof(header); + size_in_packet += sizeof(header); + + // for (int i = 0; i < block_count_32x32; i++) + // if (!validate_bitstream(input_bitstream, meta, i)) + // return false; + + for (int i = 0; i < block_count_32x32; i++) + { + size_t packet_size = meta[i].num_words * sizeof(uint32_t); + if (!packet_size) + continue; + + if (size_in_packet + packet_size > packet_boundary) + { + packets[num_packets++] = {packet_offset, size_in_packet}; + size_in_packet = 0; + packet_offset = output_offset; + } + + assert(output_offset + packet_size <= size); + assert(packet_size >= sizeof(BitstreamHeader) / sizeof(uint32_t)); + + uint16_t block = reinterpret_cast(input_bitstream + meta[i].offset_u32)->block_index; + (void)block; + assert(block == i); + + memcpy(output_bitstream + output_offset, input_bitstream + meta[i].offset_u32, packet_size); + + output_offset += packet_size; + size_in_packet += packet_size; + } + + if (size_in_packet) + packets[num_packets++] = {packet_offset, size_in_packet}; + + return num_packets; +} + +bool Encoder::encode_quant_and_coding( + vk::raii::CommandBuffer & cmd, + const BitstreamBuffers & buffers, + float quant_scale) +{ + // cmd.enable_subgroup_size_control(true); + + if (!quant(cmd, quant_scale)) + return false; + + if (!analyze_rdo(cmd)) + return false; + + if (!resolve_rdo(cmd, buffers.target_size)) + return false; + + if (!block_packing(cmd, buffers, quant_scale)) + return false; + + // cmd.enable_subgroup_size_control(false); + return true; +} + +bool Encoder::encode_pre_transformed( + vk::raii::CommandBuffer & cmd, + const BitstreamBuffers & buffers, + float quant_scale) +{ + cmd.fillBuffer(payload_data, 0, 2 * sizeof(uint32_t), 0); + cmd.fillBuffer(bucket_buffer, 0, vk::WholeSize, 0); + cmd.fillBuffer(quant_buffer, 0, vk::WholeSize, 0); + + // Don't need to read the payload offset counter until quantizer. + std::array barriers{ + vk::BufferMemoryBarrier{ + .srcAccessMask = vk::AccessFlagBits::eTransferWrite, + .dstAccessMask = vk::AccessFlagBits::eShaderWrite | vk::AccessFlagBits::eShaderRead, + .buffer = payload_data, + .size = vk::WholeSize, + }, + vk::BufferMemoryBarrier{ + .srcAccessMask = vk::AccessFlagBits::eTransferWrite, + .dstAccessMask = vk::AccessFlagBits::eShaderWrite | vk::AccessFlagBits::eShaderRead, + .buffer = bucket_buffer, + .size = vk::WholeSize, + }, + vk::BufferMemoryBarrier{ + .srcAccessMask = vk::AccessFlagBits::eTransferWrite, + .dstAccessMask = vk::AccessFlagBits::eShaderWrite | vk::AccessFlagBits::eShaderRead, + .buffer = quant_buffer, + .size = vk::WholeSize, + }, + }; + cmd.pipelineBarrier( + vk::PipelineStageFlagBits::eAllCommands, + vk::PipelineStageFlagBits::eComputeShader, // FIXME: clear and copy bits + {}, + {}, + barriers, + {}); + // cmd.barrier(VK_PIPELINE_STAGE_2_CLEAR_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_2_SHADER_STORAGE_READ_BIT | VK_ACCESS_2_SHADER_STORAGE_WRITE_BIT); + + return encode_quant_and_coding(cmd, buffers, quant_scale); +} + +bool Encoder::encode(vk::raii::CommandBuffer & cmd, const ViewBuffers & views, const BitstreamBuffers & buffers) +{ + // TODO: update descriptor sets + sequence_count = (sequence_count + 1) & SequenceCountMask; + + // cmd.image_barrier(*wavelet_img_high_res, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_2_SHADER_STORAGE_WRITE_BIT); + + vk::ImageMemoryBarrier image_barrier{ + .srcAccessMask = vk::AccessFlagBits::eNone, + .dstAccessMask = vk::AccessFlagBits::eShaderWrite, + .oldLayout = vk::ImageLayout::eUndefined, + .newLayout = vk::ImageLayout::eGeneral, + .image = wavelet_img_high_res, + .subresourceRange = { + .aspectMask = vk::ImageAspectFlagBits::eColor, + .levelCount = VK_REMAINING_MIP_LEVELS, + .layerCount = VK_REMAINING_ARRAY_LAYERS, + }, + }; + cmd.pipelineBarrier( + vk::PipelineStageFlagBits::eComputeShader, + vk::PipelineStageFlagBits::eComputeShader, + {}, + {}, + {}, + image_barrier); + + if (wavelet_img_low_res) + { + // cmd.image_barrier(*wavelet_img_low_res, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_2_SHADER_STORAGE_WRITE_BIT); + image_barrier.image = vk::Image(wavelet_img_low_res); + cmd.pipelineBarrier( + vk::PipelineStageFlagBits::eComputeShader, + vk::PipelineStageFlagBits::eComputeShader, + {}, + {}, + {}, + image_barrier); + } + + cmd.fillBuffer(payload_data, 0, 2 * sizeof(uint32_t), 0); + cmd.fillBuffer(bucket_buffer, 0, vk::WholeSize, 0); + cmd.fillBuffer(quant_buffer, 0, vk::WholeSize, 0); + + // cmd.enable_subgroup_size_control(true); + if (!dwt(cmd, views)) + return false; + // cmd.enable_subgroup_size_control(false); + + // Don't need to read the payload offset counter until quantizer. + // cmd.barrier(VK_PIPELINE_STAGE_2_CLEAR_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_2_SHADER_STORAGE_READ_BIT | VK_ACCESS_2_SHADER_STORAGE_WRITE_BIT); + std::array barriers{ + vk::BufferMemoryBarrier{ + .srcAccessMask = vk::AccessFlagBits::eTransferWrite, + .dstAccessMask = vk::AccessFlagBits::eShaderWrite | vk::AccessFlagBits::eShaderRead, + .buffer = payload_data, + .size = vk::WholeSize, + }, + vk::BufferMemoryBarrier{ + .srcAccessMask = vk::AccessFlagBits::eTransferWrite, + .dstAccessMask = vk::AccessFlagBits::eShaderWrite | vk::AccessFlagBits::eShaderRead, + .buffer = bucket_buffer, + .size = vk::WholeSize, + }, + vk::BufferMemoryBarrier{ + .srcAccessMask = vk::AccessFlagBits::eTransferWrite, + .dstAccessMask = vk::AccessFlagBits::eShaderWrite | vk::AccessFlagBits::eShaderRead, + .buffer = quant_buffer, + .size = vk::WholeSize, + }, + }; + cmd.pipelineBarrier( + vk::PipelineStageFlagBits::eAllCommands, + vk::PipelineStageFlagBits::eComputeShader, + {}, + {}, + barriers, + {}); + + return encode_quant_and_coding(cmd, buffers, -1.0f); +} + +const vk::ImageView Encoder::get_wavelet_band(int component, int level) +{ + return *component_layer_views[component][level]; +} + +void Encoder::report_stats(const void *, const void *) const +{ + // impl->report_stats(mapped_meta, mapped_bitstream); +} + +uint64_t Encoder::get_meta_required_size() const +{ + return block_count_32x32 * sizeof(BitstreamPacket); +} + +Encoder::~Encoder() +{ +} +} // namespace PyroWave diff --git a/common/pyrowave/pyrowave_encoder.h b/common/pyrowave/pyrowave_encoder.h new file mode 100644 index 00000000..f04cc0d5 --- /dev/null +++ b/common/pyrowave/pyrowave_encoder.h @@ -0,0 +1,90 @@ +#pragma once + +#include + +#include "pyrowave_common.h" + +namespace PyroWave +{ +class Encoder : public WaveletBuffers +{ + vk::raii::DescriptorPool ds_pool; + struct pipeline + { + vk::raii::DescriptorSetLayout ds_layout = nullptr; + vk::DescriptorSet ds = nullptr; + vk::raii::PipelineLayout layout = nullptr; + vk::raii::Pipeline pipeline = nullptr; + }; + buffer_allocation bucket_buffer, meta_buffer, block_stat_buffer, payload_data, quant_buffer; + uint32_t sequence_count = 0; + + pipeline block_packing_; + pipeline resolve_rdo_; + pipeline analyze_rdo_; + pipeline analyze_rdo_finalize; // shares descriptor set with anaylze_rdo + vk::DescriptorSet quant_ds[NumComponents][DecompositionLevels]; + pipeline quant_; + vk::DescriptorSet dwt_ds[NumComponents][DecompositionLevels]; + pipeline dwt_; + vk::raii::Pipeline dwt_dcshift = nullptr; + + /* +public: + buffer_allocation debug_buffer; + */ + +public: + using ViewBuffers = std::array; + Encoder(vk::raii::PhysicalDevice & phys_dev, vk::raii::Device & device, int width, int height, ChromaSubsampling chroma); + ~Encoder(); + + struct BitstreamBuffers + { + struct + { + vk::Buffer buffer; + uint64_t offset; + uint64_t size; + } meta, bitstream; + size_t target_size; + }; + + bool encode(vk::raii::CommandBuffer & cmd, const ViewBuffers & views, const BitstreamBuffers & buffers); + + // Debug hackery + const vk::ImageView get_wavelet_band(int component, int level); + bool encode_pre_transformed(vk::raii::CommandBuffer & cmd, const BitstreamBuffers & buffers, float quant_scale); + // + + uint64_t get_meta_required_size() const; + + struct Packet + { + size_t offset; + size_t size; + }; + + size_t compute_num_packets(const void * mapped_meta, size_t packet_boundary) const; + size_t packetize(Packet * packets, size_t packet_boundary, void * bitstream, size_t size, const void * mapped_meta, const void * mapped_bitstream) const; + + void report_stats(const void * mapped_meta, const void * mapped_bitstream) const; + +private: + bool encode_quant_and_coding(vk::raii::CommandBuffer & cmd, const BitstreamBuffers & buffers, float quant_scale); + + bool dwt(vk::raii::CommandBuffer & cmd, const ViewBuffers & views); + bool quant(vk::raii::CommandBuffer & cmd, float quant_scale); + bool analyze_rdo(vk::raii::CommandBuffer & cmd); + bool resolve_rdo(vk::raii::CommandBuffer & cmd, size_t target_payload_size); + bool block_packing(vk::raii::CommandBuffer & cmd, const BitstreamBuffers & buffers, float quant_scale); + + float get_noise_power_normalized_quant_resolution(int level, int component, int band) const; + float get_quant_resolution(int level, int component, int band) const; + float get_quant_rdo_distortion_scale(int level, int component, int band) const; + + void analyze_alternative_packing(const void * mapped_meta, const void * mapped_bitstream) const; + + bool validate_bitstream(const uint32_t * bitstream_u32, const BitstreamPacket * meta, uint32_t block_index) const; +}; +} // namespace PyroWave diff --git a/common/pyrowave/shaders/analyze_rate_control.comp b/common/pyrowave/shaders/analyze_rate_control.comp new file mode 100644 index 00000000..643dc124 --- /dev/null +++ b/common/pyrowave/shaders/analyze_rate_control.comp @@ -0,0 +1,222 @@ +#version 450 +#extension GL_KHR_shader_subgroup_basic : require +#extension GL_KHR_shader_subgroup_ballot : require +#extension GL_KHR_shader_subgroup_arithmetic : require +#extension GL_KHR_shader_subgroup_vote : require +#extension GL_KHR_shader_subgroup_shuffle_relative : require +#extension GL_KHR_shader_subgroup_shuffle : require +#extension GL_EXT_shader_explicit_arithmetic_types_float16 : require +#extension GL_EXT_shader_explicit_arithmetic_types_int16 : require +#extension GL_ARB_shading_language_include : require + +#include "dwt_quant_scale.h" +#include "constants.h" + +layout(local_size_x = 64) in; + +struct BlockMeta +{ + uint code_word; + uint offset; +}; + +struct RDOperation +{ + int quant; + uint block_offset_saving; +}; + +const int BLOCK_SPACE_SUBDIVISION = 16; + +layout(set = 0, binding = 0) buffer Buckets +{ + uint count; + uint consumed_payload; + layout(offset = 64) uint total_savings_per_bucket[128 * BLOCK_SPACE_SUBDIVISION]; + RDOperation rdo_operations[]; +} buckets; + +struct QuantStats +{ + float16_t square_error; + uint16_t payload_cost; +}; + +struct BlockStats +{ + uint num_planes; + QuantStats errors[15]; +}; + +layout(set = 0, binding = 1) readonly buffer SSBOBlockStats +{ + BlockStats stats[]; +} block_stats; + +layout(push_constant) uniform Registers +{ + ivec2 resolution; + ivec2 resolution_8x8_blocks; + int block_offset_8x8; + int block_stride_8x8; + int block_offset_32x32; + int block_stride_32x32; + uint total_wg_count; + uint num_blocks_aligned; + uint block_index_shamt; +} registers; + +shared uint shared_rate_cost[16]; +shared float shared_distortion[16]; +shared uint shared_tmp[4]; + +// Perform operations that cause lower distortion first. +uint distortion_to_bucket_index(float d, float cost, float d_base, float cost_base) +{ + if (cost == cost_base) + return 0; + + // Compress a large range into 64 possible buckets. + // Every band is ~1.5 dB. + // Greedily chase least added (weighted) distortion per byte removed from code stream. + float index = 60.0 + 2.0 * log2(max(d - d_base, 0.0) / (cost_base - cost)); + return uint(max(index + 0.5, 0.0)); +} + +uint inclusive_max_clustered16(uint v) +{ + // Ensures that we never end up with a value > 127. + v = min(v, 128 - 16 + gl_SubgroupInvocationID); + + for (uint i = 1; i < 16; i *= 2) + { + // Ensure monotonic progression for buckets. + // Separate every quant level out by at least one bucket. + uint up = subgroupShuffleUp(v, i) + i; + v = max(v, gl_SubgroupInvocationID >= i ? up : 0); + } + + return v; +} + +void emit_rdo_operations() +{ + float distortion; + float cost; + + if (gl_SubgroupInvocationID < 16) + { + cost = float(shared_rate_cost[gl_SubgroupInvocationID]); + distortion = shared_distortion[gl_SubgroupInvocationID]; + } + else + { + // Dummy values. + cost = float(shared_rate_cost[gl_SubgroupInvocationID]); + distortion = 1e30; + } + + uint bucket_index = distortion_to_bucket_index(distortion, cost, shared_distortion[0], float(shared_rate_cost[0])); + if (gl_SubgroupInvocationID == 0) + bucket_index = 0; + + // Constraints: + // bucket_index for Q1 must be less than bucket_index for Q2 if Q1 < Q2. + // If a high quant target sees very favorable RD, lower bucket indices for lower Q values. + uint inclusive_bucket_index = inclusive_max_clustered16(bucket_index); + + if (gl_SubgroupInvocationID == 0) + { + uint unquantized_cost = shared_rate_cost[0]; + atomicAdd(buckets.consumed_payload, unquantized_cost); + } + else if (gl_SubgroupInvocationID < 16) + { + uint saving = shared_rate_cost[gl_SubgroupInvocationID - 1] - shared_rate_cost[gl_SubgroupInvocationID]; + + if (saving != 0) + { + ivec2 block32x32_index = ivec2(gl_WorkGroupID.xy); + int block_index = registers.block_offset_32x32 + + block32x32_index.y * registers.block_stride_32x32 + block32x32_index.x; + uint subdivision = block_index >> registers.block_index_shamt; + atomicAdd(buckets.total_savings_per_bucket[inclusive_bucket_index * BLOCK_SPACE_SUBDIVISION + subdivision], saving); + buckets.rdo_operations[block_index + inclusive_bucket_index * registers.num_blocks_aligned] = + RDOperation(int(gl_SubgroupInvocationID), block_index | (saving << 16)); + } + } +} + +void main() +{ + // Each workgroup processes a 64x64 block and computes all possible rate wins for every potential quant rate. + uint index = gl_SubgroupInvocationID + gl_SubgroupSize * gl_SubgroupID; + ivec2 block32x32_index = ivec2(gl_WorkGroupID.xy); + ivec2 local_block_index = ivec2(bitfieldExtract(index, 0, 2), bitfieldExtract(index, 2, 2)); + ivec2 block8x8_index = 4 * block32x32_index + local_block_index; + + uint num_active_planes; + + bool block8x8_in_range = all(lessThan(block8x8_index, registers.resolution_8x8_blocks)); + int block_index_8x8 = registers.block_offset_8x8 + + registers.block_stride_8x8 * block8x8_index.y + + block8x8_index.x; + + if (block8x8_in_range) + num_active_planes = block_stats.stats[block_index_8x8].num_planes; + + uint bit_index = index >> 4; + + for (uint i = bit_index; i < 16; i += 4) + { + float dist = 0.0; + uint cost = 0; + + if (block8x8_in_range) + { + QuantStats stats = block_stats.stats[block_index_8x8].errors[min(i, num_active_planes)]; + dist = float(stats.square_error); + cost = uint(stats.payload_cost); + } + + // 16 bits to encode the control codes, 8 bits to encode Q bits + quant scale. + // Cost is encoded in terms of bits. 8x8 blocks are decoded in isolation. + if (cost != 0) + cost += 24; + + if (gl_SubgroupSize == 16) + { + cost = subgroupAdd(cost); + dist = subgroupAdd(dist); + } + else + { + cost += subgroupShuffleXor(cost, 1); + cost += subgroupShuffleXor(cost, 2); + cost += subgroupShuffleXor(cost, 4); + cost += subgroupShuffleXor(cost, 8); + + dist += subgroupShuffleXor(dist, 1); + dist += subgroupShuffleXor(dist, 2); + dist += subgroupShuffleXor(dist, 4); + dist += subgroupShuffleXor(dist, 8); + } + + if ((index & 15u) == 0u) + { + // Need to encode a header. + // We can eliminate 32x32 blocks if everything decodes to 0. + if (cost != 0) + cost += 64; + + // Each packet is aligned to 4 bytes for practical reasons. + shared_rate_cost[i] = (cost + 31) >> 5; + shared_distortion[i] = dist; + } + } + + barrier(); + + if (gl_SubgroupID == 0) + emit_rdo_operations(); +} diff --git a/common/pyrowave/shaders/analyze_rate_control_finalize.comp b/common/pyrowave/shaders/analyze_rate_control_finalize.comp new file mode 100644 index 00000000..2defbfda --- /dev/null +++ b/common/pyrowave/shaders/analyze_rate_control_finalize.comp @@ -0,0 +1,39 @@ +#version 450 + +layout(local_size_x = 512) in; + +const int BLOCK_SPACE_SUBDIVISION = 16; + +layout(set = 0, binding = 0) buffer Buckets +{ + layout(offset = 64) uvec4 total_savings_per_bucket[128 * BLOCK_SPACE_SUBDIVISION / 4]; +} buckets; + +shared uint shared_scan[512]; + +void main() +{ + uvec4 v = buckets.total_savings_per_bucket[gl_LocalInvocationIndex]; + v.y += v.x; + v.z += v.y; + v.w += v.z; + shared_scan[gl_LocalInvocationIndex] = v.w; + + barrier(); + + for (uint step = 1u; step < gl_WorkGroupSize.x / 2u; step *= 2u) + { + barrier(); + + uint shuffled_up = 0; + if (gl_LocalInvocationIndex >= step) + shuffled_up = shared_scan[gl_LocalInvocationIndex - step]; + + barrier(); + + v += shuffled_up; + shared_scan[gl_LocalInvocationIndex] = v.w; + } + + buckets.total_savings_per_bucket[gl_LocalInvocationIndex] = v; +} \ No newline at end of file diff --git a/common/pyrowave/shaders/block_packing.comp b/common/pyrowave/shaders/block_packing.comp new file mode 100644 index 00000000..46847a81 --- /dev/null +++ b/common/pyrowave/shaders/block_packing.comp @@ -0,0 +1,380 @@ +#version 450 +// Copyright (c) 2025 Hans-Kristian Arntzen +// SPDX-License-Identifier: MIT +#extension GL_KHR_shader_subgroup_basic : require +#extension GL_KHR_shader_subgroup_ballot : require +#extension GL_KHR_shader_subgroup_arithmetic : require +#extension GL_KHR_shader_subgroup_shuffle_relative : require +#extension GL_KHR_shader_subgroup_shuffle : require +#extension GL_KHR_shader_subgroup_clustered : require +#extension GL_KHR_shader_subgroup_vote : require +#extension GL_EXT_shader_explicit_arithmetic_types_float16 : require +#extension GL_EXT_shader_explicit_arithmetic_types_int16 : require +#extension GL_EXT_shader_8bit_storage : require +#extension GL_ARB_shading_language_include : require + +#include "constants.h" + +layout(local_size_x = 64) in; + +struct BlockMeta +{ + uint code_word; + uint offset; +}; + +struct BitstreamPacket +{ + uint offset; + uint num_words; +}; + +layout(set = 0, binding = 0) writeonly buffer BitstreamPayload +{ + uint data[]; +} bitstream_data; + +layout(set = 0, binding = 0) writeonly buffer BitstreamPayload16Bit +{ + uint16_t data[]; +} bitstream_data_16b; + +layout(set = 0, binding = 0) writeonly buffer BitstreamPayload8Bit +{ + uint8_t data[]; +} bitstream_data_8b; + +layout(set = 0, binding = 1) writeonly buffer BitstreamMeta +{ + BitstreamPacket packets[]; +} bitstream_meta; + +layout(set = 0, binding = 2) readonly buffer SSBOMeta +{ + BlockMeta meta[]; +} block_meta; + +layout(set = 0, binding = 3) buffer Payloads +{ + layout(offset = 4) uint bitstream_payload_counter; + layout(offset = 8) uint8_t data[]; +} payload_data; + +struct QuantStats +{ + float16_t square_error; + uint16_t payload_cost; +}; + +struct BlockStats +{ + uint num_planes; + QuantStats errors[15]; +}; + +layout(set = 0, binding = 4) readonly buffer SSBOBlockStats +{ + BlockStats stats[]; +} block_stats; + +layout(set = 0, binding = 5) readonly buffer RateControlQuant +{ + int data[]; +} quant_data; + +layout(push_constant) uniform Registers +{ + ivec2 resolution; + ivec2 resolution_32x32_blocks; + ivec2 resolution_8x8_blocks; + uint quant_resolution_code; + uint sequence_code; + int block_offset_32x32; + int block_stride_32x32; + int block_offset_8x8; + int block_stride_8x8; +} registers; + +uint compute_required_8x8_size(uint control_word) +{ + int q_bits = int(bitfieldExtract(control_word, Q_PLANES_OFFSET, Q_PLANES_BITS)); + uint lsbs = control_word & 0x5555u; + uint msbs = control_word & 0xaaaau; + uint msbs_shift = msbs >> 1; + msbs |= msbs_shift; + return bitCount(lsbs) + bitCount(msbs) + q_bits * 8; +} + +uint quantize_code_word(uint control_word, int quant) +{ + if (quant != 0 && control_word != 0) + { + int q_bits = int(bitfieldExtract(control_word, Q_PLANES_OFFSET, Q_PLANES_BITS)); + int sub_quant = min(q_bits, quant); + q_bits -= sub_quant; + quant -= sub_quant; + + if (quant != 0) + { + quant = min(quant, 3); + + uint plane0 = control_word & 0x5555u; + uint plane1 = (control_word & 0xaaaau) >> 1; + uint plane2 = plane0 & plane1; + + do + { + plane0 = plane1; + plane1 = plane2; + plane2 = 0; + quant--; + } while (quant != 0); + + plane0 &= ~plane1; + + uint new_control_word = plane0 | (plane1 << 1); + control_word = bitfieldInsert(control_word, new_control_word, 0, 16); + } + + control_word = bitfieldInsert(control_word, uint(q_bits), Q_PLANES_OFFSET, Q_PLANES_BITS); + } + + return control_word; +} + +uint copy_bytes(inout uint output_offset, uint input_offset, uint count) +{ + uint significant_mask = 0; + + do + { + uint in_data = uint(payload_data.data[input_offset]); + // If we observe any 1 in the non-sign planes, it's not deadzone quantized. + significant_mask |= in_data; + bitstream_data_8b.data[output_offset++] = uint8_t(in_data); + count--; + input_offset++; + } while (count > 0); + + return significant_mask; +} + +uint modify_quant_code(uint code, int quant) +{ + int e = int(bitfieldExtract(code, 3, 5)); + e = max(e - quant, 0); + code = bitfieldInsert(code, e, 3, 5); + return code; +} + +uint inclusive_add_clustered16(uint v) +{ + for (uint i = 1; i < 16; i *= 2) + { + uint up = subgroupShuffleUp(v, i); + v += (gl_SubgroupInvocationID & 15) >= i ? up : 0; + } + + return v; +} + +shared uint shared_sign_bank[4][1024 / 32]; +uint pending_sign_write = 0; +uint pending_sign_mask = 0; + +void append_sign_plane(uint bank, inout uint local_sign_offset, uint sign_mask, uint significant_mask) +{ + // Clock out one bit a time. This seems kinda slow. + while (significant_mask != 0) + { + int bit = findLSB(significant_mask); + significant_mask &= significant_mask - 1; + int out_bit = int(local_sign_offset & 31u); + pending_sign_write = bitfieldInsert(pending_sign_write, bitfieldExtract(sign_mask, bit, 1), out_bit, 1); + pending_sign_mask = bitfieldInsert(pending_sign_mask, 1, out_bit, 1); + + if (out_bit == 31) + { + if (pending_sign_mask == ~0u) + { + shared_sign_bank[bank][local_sign_offset / 32] = pending_sign_write; + } + else + { + atomicAnd(shared_sign_bank[bank][local_sign_offset / 32], ~pending_sign_mask); + atomicOr(shared_sign_bank[bank][local_sign_offset / 32], pending_sign_write & pending_sign_mask); + } + + pending_sign_mask = 0; + } + + local_sign_offset++; + } +} + +void flush_sign_plane(uint bank, uint local_sign_offset) +{ + if (pending_sign_mask != 0) + { + atomicAnd(shared_sign_bank[bank][local_sign_offset / 32], ~pending_sign_mask); + atomicOr(shared_sign_bank[bank][local_sign_offset / 32], pending_sign_write & pending_sign_mask); + pending_sign_mask = 0; + } +} + +void main() +{ + uint index = gl_SubgroupInvocationID + gl_SubgroupSize * gl_SubgroupID; + uint linear_block_32x32_index = index >> 4; + ivec2 block32x32_index = 2 * ivec2(gl_WorkGroupID.xy); + block32x32_index.x += int(bitfieldExtract(index, 4, 1)); + block32x32_index.y += int(bitfieldExtract(index, 5, 1)); + ivec2 local_block_index = ivec2(bitfieldExtract(index, 0, 2), bitfieldExtract(index, 2, 2)); + ivec2 block8x8_index = 4 * block32x32_index + local_block_index; + + BlockMeta meta; + int quant; + + bool in_range_8x8 = all(lessThan(block8x8_index, registers.resolution_8x8_blocks)); + bool in_range_32x32 = all(lessThan(block32x32_index, registers.resolution_32x32_blocks)); + uint num_bits_for_q = 0; + + if (in_range_32x32) + { + int block_index = registers.block_offset_32x32 + + registers.block_stride_32x32 * block32x32_index.y + + block32x32_index.x; + quant = quant_data.data[block_index]; + } + else + { + quant = 0; + } + + if (in_range_8x8) + { + int block_index = registers.block_offset_8x8 + + registers.block_stride_8x8 * block8x8_index.y + + block8x8_index.x; + meta = block_meta.meta[block_index]; + uint num_planes = block_stats.stats[block_index].num_planes; + num_bits_for_q = uint(block_stats.stats[block_index].errors[min(num_planes, quant)].payload_cost); + } + else + { + meta = BlockMeta(0, 0); + } + + uint code_word = quantize_code_word(meta.code_word, quant); + bool active_code_word = (code_word & 0xffffu) != 0; + + uvec4 code_word_ballot = subgroupBallot(active_code_word); + uint local_ballot = gl_SubgroupSize >= 64 && linear_block_32x32_index >= 2 ? code_word_ballot.y : code_word_ballot.x; + local_ballot = bitfieldExtract(local_ballot, int(16u * (linear_block_32x32_index & 1u)), 16); + + uint required_plane_bytes = compute_required_8x8_size(code_word); + uint required_sign_bits = num_bits_for_q - required_plane_bytes * 8; + + uint required_bits_with_meta = num_bits_for_q; + if (required_bits_with_meta != 0) + required_bits_with_meta += 24; + + const uint HeaderSize = 2; + bool writes_header = + all(lessThan(block32x32_index, registers.resolution_32x32_blocks)) && (index & 15u) == 15u; + + uint payload_total_bits = subgroupClusteredAdd(required_bits_with_meta, 16); + uint payload_total_words = (payload_total_bits + 31) / 32; + if (payload_total_words != 0) + payload_total_words += HeaderSize; + + uint global_payload_offset = 0; + if (writes_header && payload_total_words != 0) + global_payload_offset = atomicAdd(payload_data.bitstream_payload_counter, payload_total_words); + global_payload_offset = subgroupShuffle(global_payload_offset, gl_SubgroupInvocationID | 15u); + + if (writes_header) + { + uint block_index = registers.block_offset_32x32 + + block32x32_index.y * registers.block_stride_32x32 + block32x32_index.x; + + if (payload_total_words != 0) + { + bitstream_data.data[global_payload_offset + 0] = + local_ballot | (payload_total_words << 16) | (registers.sequence_code << 28); + bitstream_data.data[global_payload_offset + 1] = + modify_quant_code(registers.quant_resolution_code, quant) | (block_index << 8); + } + + bitstream_meta.packets[block_index] = BitstreamPacket(global_payload_offset, payload_total_words); + } + + uint total_subblocks = bitCount(local_ballot); + + uint total_sign_bits = inclusive_add_clustered16(required_sign_bits); + uint local_planes_offset = inclusive_add_clustered16(required_plane_bytes) - required_plane_bytes; + uint local_sign_offset = total_sign_bits - required_sign_bits; + uint global_planes_offset = 4 * global_payload_offset + 3 * total_subblocks + 4 * HeaderSize; + uint global_sign_offset = global_planes_offset + subgroupClusteredAdd(required_plane_bytes, 16); + global_planes_offset += local_planes_offset; + + uint total_sign_bytes = (subgroupShuffle(total_sign_bits, gl_SubgroupInvocationID | 15u) + 7) / 8; + + // Followed by N code words which map to the local ballot of active 16x16 regions. + if (active_code_word) + { + uint block_header_offset = bitCount(bitfieldExtract( + local_ballot, 0, local_block_index.y * 4 + local_block_index.x)); + + uint in_q_bits = bitfieldExtract(meta.code_word, Q_PLANES_OFFSET, Q_PLANES_BITS); + uint out_q_bits = bitfieldExtract(code_word, Q_PLANES_OFFSET, Q_PLANES_BITS); + uint input_offset = meta.offset; + uint output_offset = global_planes_offset; + + for (int bit_offset = 0; bit_offset < 16; bit_offset += 2) + { + uint out_planes = bitfieldExtract(code_word, bit_offset, 2) + out_q_bits; + uint in_planes = bitfieldExtract(meta.code_word, bit_offset, 2) + in_q_bits; + if (in_planes != 0) + in_planes++; + + uint sign_plane = uint(payload_data.data[input_offset]); + + if (out_planes != 0) + { + uint significant_mask = copy_bytes(output_offset, input_offset + 1, out_planes); + append_sign_plane(linear_block_32x32_index, local_sign_offset, sign_plane, significant_mask); + } + + input_offset += in_planes; + } + + flush_sign_plane(linear_block_32x32_index, local_sign_offset); + + bitstream_data_16b.data[2 * global_payload_offset + block_header_offset + 2 * HeaderSize] = + uint16_t(code_word); + bitstream_data_8b.data[4 * global_payload_offset + 2 * total_subblocks + block_header_offset + 4 * HeaderSize] = + uint8_t(code_word >> 16); + } + + subgroupBarrier(); + + // Copy out all sign planes for any given group. + for (uint i = index & 15u; i < total_sign_bytes / 4; i += 16) + { + uint sign_word = shared_sign_bank[linear_block_32x32_index][i]; + uint offset_8b = global_sign_offset + 4 * i; + bitstream_data_8b.data[offset_8b + 0] = uint8_t(sign_word >> 0); + bitstream_data_8b.data[offset_8b + 1] = uint8_t(sign_word >> 8); + bitstream_data_8b.data[offset_8b + 2] = uint8_t(sign_word >> 16); + bitstream_data_8b.data[offset_8b + 3] = uint8_t(sign_word >> 24); + } + + // Copy out any stragglers. + for (uint i = (total_sign_bytes & ~3u) + (index & 15u); i < total_sign_bytes; i += 16) + { + uint sign_word = shared_sign_bank[linear_block_32x32_index][i / 4]; + uint offset_8b = global_sign_offset + i; + bitstream_data_8b.data[offset_8b] = uint8_t(sign_word >> (8 * (i & 3u))); + } +} diff --git a/common/pyrowave/shaders/constants.h b/common/pyrowave/shaders/constants.h new file mode 100644 index 00000000..8443949c --- /dev/null +++ b/common/pyrowave/shaders/constants.h @@ -0,0 +1,10 @@ +#ifndef CONSTANTS_H_ +#define CONSTANTS_H_ + +const int Q_PLANES_OFFSET = 16; +const int Q_PLANES_BITS = 4; + +const int QUANT_SCALE_OFFSET = 20; +const int QUANT_SCALE_BITS = 4; + +#endif \ No newline at end of file diff --git a/common/pyrowave/shaders/dwt.h b/common/pyrowave/shaders/dwt.h new file mode 100644 index 00000000..4c390b87 --- /dev/null +++ b/common/pyrowave/shaders/dwt.h @@ -0,0 +1,241 @@ +layout(local_size_x = 64) in; + +layout(set = 0, binding = 0) uniform mediump sampler2D uTexture; +layout(set = 0, binding = 1) writeonly uniform mediump image2DArray uOutput; + +layout(constant_id = 0) const bool DCShift = false; + +layout(push_constant) uniform Registers +{ + ivec2 resolution; + vec2 inv_resolution; + ivec2 aligned_resolution; +}; + +uint local_index; + +#include "dwt_common.h" + +vec2 generate_mirror_uv(ivec2 coord) +{ + coord -= ivec2(lessThan(coord, ivec2(0))); + coord += 1; + ivec2 end_mirrored_clamp = (2 * aligned_resolution) - resolution; + ivec2 past_wrapped_coord = coord + 2 * (resolution - aligned_resolution) + 1; + coord = mix(min(coord, resolution), past_wrapped_coord, greaterThanEqual(coord, end_mirrored_clamp)); + + return vec2(coord) * inv_resolution; +} + +void load_image_with_apron() +{ + ivec2 base_coord = ivec2(gl_WorkGroupID.xy) * ivec2(BLOCK_SIZE, BLOCK_SIZE) - APRON; + ivec2 local_coord0 = 2 * unswizzle8x8(local_index); + ivec2 coord0 = base_coord + local_coord0; + + VEC4 texels0 = VEC4(textureGather(uTexture, generate_mirror_uv(coord0))).wzxy; + VEC4 texels1 = VEC4(textureGather(uTexture, generate_mirror_uv(coord0 + ivec2(16, 0)))).wzxy; + VEC4 texels2 = VEC4(textureGather(uTexture, generate_mirror_uv(coord0 + ivec2(0, 16)))).wzxy; + VEC4 texels3 = VEC4(textureGather(uTexture, generate_mirror_uv(coord0 + ivec2(16, 16)))).wzxy; + if (DCShift) + { + texels0 -= FLOAT(0.5); + texels1 -= FLOAT(0.5); + texels2 -= FLOAT(0.5); + texels3 -= FLOAT(0.5); + } + + int local_coord0_y_half = local_coord0.y >> 1; + + // Pack two lines together in one vec2. This allows packed FP16 math easily by processing two lines in parallel. + store_shared(local_coord0_y_half + 0, local_coord0.x + 0, texels0.xz); + store_shared(local_coord0_y_half + 0, local_coord0.x + 1, texels0.yw); + store_shared(local_coord0_y_half + 0, local_coord0.x + 16, texels1.xz); + store_shared(local_coord0_y_half + 0, local_coord0.x + 17, texels1.yw); + store_shared(local_coord0_y_half + 8, local_coord0.x + 0, texels2.xz); + store_shared(local_coord0_y_half + 8, local_coord0.x + 1, texels2.yw); + store_shared(local_coord0_y_half + 8, local_coord0.x + 16, texels3.xz); + store_shared(local_coord0_y_half + 8, local_coord0.x + 17, texels3.yw); + + // Load the top-right apron + { + ivec2 local_coord = ivec2(BLOCK_SIZE + 2 * (local_index % 4u), 2 * (local_index / 4u)); + VEC4 texels = VEC4(textureGather(uTexture, generate_mirror_uv(base_coord + local_coord))).wzxy; + if (DCShift) + { + texels -= FLOAT(0.5); + } + store_shared(local_coord.y >> 1, local_coord.x + 0, texels.xz); + store_shared(local_coord.y >> 1, local_coord.x + 1, texels.yw); + } + + // Load the bottom-left apron + { + ivec2 local_coord = ivec2(2 * (local_index % 16u), BLOCK_SIZE + 2 * (local_index / 16u)); + VEC4 texels = VEC4(textureGather(uTexture, generate_mirror_uv(base_coord + local_coord))).wzxy; + if (DCShift) + { + texels -= FLOAT(0.5); + } + store_shared(local_coord.y >> 1, local_coord.x + 0, texels.xz); + store_shared(local_coord.y >> 1, local_coord.x + 1, texels.yw); + } + + if (local_index < 16) + { + // Load the bottom-right apron + ivec2 local_coord = ivec2(BLOCK_SIZE + 2 * (local_index % 4u), BLOCK_SIZE + 2 * (local_index / 4u)); + VEC4 texels = VEC4(textureGather(uTexture, generate_mirror_uv(base_coord + local_coord))).wzxy; + if (DCShift) + { + texels -= FLOAT(0.5); + } + store_shared(local_coord.y >> 1, local_coord.x + 0, texels.xz); + store_shared(local_coord.y >> 1, local_coord.x + 1, texels.yw); + } +} + +void forward_transform8x2() +{ + const int SIZE = 8; + const int PADDED_SIZE = SIZE + 2 * APRON; + const int PADDED_SIZE_HALF = PADDED_SIZE / 2; + VEC2 values[PADDED_SIZE]; + + ivec2 local_coord = ivec2(8 * (local_index % 4u), local_index / 4u); + + for (int i = 0; i < PADDED_SIZE; i++) + { + VEC2 v = load_shared(local_coord.y, local_coord.x + i); + values[i] = v; + } + + // CDF 9/7 lifting steps. + // Arith go brrr. + for (int i = 1; i < PADDED_SIZE - 1; i += 2) + values[i] += ALPHA * (values[i - 1] + values[i + 1]); + for (int i = 2; i < PADDED_SIZE - 2; i += 2) + values[i] += BETA * (values[i - 1] + values[i + 1]); + for (int i = 3; i < PADDED_SIZE - 3; i += 2) + values[i] += GAMMA * (values[i - 1] + values[i + 1]); + for (int i = 4; i < PADDED_SIZE - 4; i += 2) + values[i] += DELTA * (values[i - 1] + values[i + 1]); + + // Avoid WAR hazard. + barrier(); + + for (int i = APRON_HALF; i < PADDED_SIZE_HALF - APRON_HALF; i++) + { + VEC2 a = values[2 * i + 0]; + VEC2 b = values[2 * i + 1]; + + // Filter kernel rescale. + a *= inv_K; + b *= K; + + // Transpose the 2x2 block. + VEC2 t0 = VEC2(a.x, b.x); + VEC2 t1 = VEC2(a.y, b.y); + + // Transpose write + int y_coord = (local_coord.x >> 1) + (i - APRON_HALF); + store_shared(y_coord, 2 * local_coord.y + 0, t0); + store_shared(y_coord, 2 * local_coord.y + 1, t1); + } +} + +void forward_transform4x2(bool active_lane, int y_offset) +{ + const int SIZE = 4; + const int PADDED_SIZE = SIZE + 2 * APRON; + const int PADDED_SIZE_HALF = PADDED_SIZE / 2; + VEC2 values[PADDED_SIZE]; + + ivec2 local_coord = ivec2(4 * (local_index % 8u), local_index / 8u + y_offset); + + if (active_lane) + { + for (int i = 0; i < PADDED_SIZE; i++) + { + VEC2 v = load_shared(local_coord.y, local_coord.x + i); + values[i] = v; + } + + // CDF 9/7 lifting steps. + // Arith go brrr. + for (int i = 1; i < PADDED_SIZE - 1; i += 2) + values[i] += ALPHA * (values[i - 1] + values[i + 1]); + for (int i = 2; i < PADDED_SIZE - 2; i += 2) + values[i] += BETA * (values[i - 1] + values[i + 1]); + for (int i = 3; i < PADDED_SIZE - 3; i += 2) + values[i] += GAMMA * (values[i - 1] + values[i + 1]); + for (int i = 4; i < PADDED_SIZE - 4; i += 2) + values[i] += DELTA * (values[i - 1] + values[i + 1]); + } + + // Avoid WAR hazard. + barrier(); + + if (active_lane) + { + for (int i = APRON_HALF; i < PADDED_SIZE_HALF - APRON_HALF; i++) + { + VEC2 a = values[2 * i + 0]; + VEC2 b = values[2 * i + 1]; + + // Filter kernel rescale. + a *= inv_K; + b *= K; + + // Transpose the 2x2 block. + VEC2 t0 = VEC2(a.x, b.x); + VEC2 t1 = VEC2(a.y, b.y); + + // Transpose write + int y_coord = (local_coord.x >> 1) + (i - APRON_HALF); + store_shared(y_coord, 2 * local_coord.y + 0, t0); + store_shared(y_coord, 2 * local_coord.y + 1, t1); + } + } +} + +void main() +{ + local_index = gl_SubgroupID * gl_SubgroupSize + gl_SubgroupInvocationID; + + load_image_with_apron(); + + barrier(); + + // Horizontal transform. + forward_transform8x2(); + + // Also need to transform the apron. + forward_transform4x2(local_index < 32, BLOCK_SIZE_HALF); + + barrier(); + + // Vertical transform. + forward_transform8x2(); + + barrier(); + + ivec2 local_coord = unswizzle8x8(local_index); + for (int y = local_coord.y; y < BLOCK_SIZE_HALF; y += 8) + { + for (int x = local_coord.x * 2; x < BLOCK_SIZE; x += 16) + { + VEC2 v0 = load_shared(y, x + 0); + VEC2 v1 = load_shared(y, x + 1); + + int img_x = x >> 1; + int img_y = y; + + ivec2 base_image_coord = ivec2(gl_WorkGroupID.xy) * (BLOCK_SIZE / 2) + ivec2(img_x, img_y); + imageStore(uOutput, ivec3(base_image_coord, 0), v0.xxxx); + imageStore(uOutput, ivec3(base_image_coord, 2), v0.yyyy); + imageStore(uOutput, ivec3(base_image_coord, 1), v1.xxxx); + imageStore(uOutput, ivec3(base_image_coord, 3), v1.yyyy); + } + } +} diff --git a/common/pyrowave/shaders/dwt_0.comp b/common/pyrowave/shaders/dwt_0.comp new file mode 100644 index 00000000..614db3ee --- /dev/null +++ b/common/pyrowave/shaders/dwt_0.comp @@ -0,0 +1,10 @@ +#version 450 +// Copyright (c) 2025 Hans-Kristian Arntzen +// SPDX-License-Identifier: MIT +#extension GL_KHR_shader_subgroup_basic : require +#extension GL_EXT_shader_explicit_arithmetic_types_float16 : require +#extension GL_ARB_shading_language_include : require + +#define PRECISION 0 + +#include "dwt.h" diff --git a/common/pyrowave/shaders/dwt_1.comp b/common/pyrowave/shaders/dwt_1.comp new file mode 100644 index 00000000..786c9b22 --- /dev/null +++ b/common/pyrowave/shaders/dwt_1.comp @@ -0,0 +1,10 @@ +#version 450 +// Copyright (c) 2025 Hans-Kristian Arntzen +// SPDX-License-Identifier: MIT +#extension GL_KHR_shader_subgroup_basic : require +#extension GL_EXT_shader_explicit_arithmetic_types_float16 : require +#extension GL_ARB_shading_language_include : require + +#define PRECISION 1 + +#include "dwt.h" diff --git a/common/pyrowave/shaders/dwt_2.comp b/common/pyrowave/shaders/dwt_2.comp new file mode 100644 index 00000000..8c620a71 --- /dev/null +++ b/common/pyrowave/shaders/dwt_2.comp @@ -0,0 +1,10 @@ +#version 450 +// Copyright (c) 2025 Hans-Kristian Arntzen +// SPDX-License-Identifier: MIT +#extension GL_KHR_shader_subgroup_basic : require +#extension GL_EXT_shader_explicit_arithmetic_types_float16 : require +#extension GL_ARB_shading_language_include : require + +#define PRECISION 2 + +#include "dwt.h" diff --git a/common/pyrowave/shaders/dwt_common.h b/common/pyrowave/shaders/dwt_common.h new file mode 100644 index 00000000..b3c897ea --- /dev/null +++ b/common/pyrowave/shaders/dwt_common.h @@ -0,0 +1,52 @@ +// Copyright (c) 2025 Hans-Kristian Arntzen +// SPDX-License-Identifier: MIT +#ifndef DWT_COMMON_H_ +#define DWT_COMMON_H_ + +const int APRON = 4; +const int APRON_HALF = APRON / 2; +const int BLOCK_SIZE = 32; +const int BLOCK_SIZE_HALF = BLOCK_SIZE >> 1; + +#if PRECISION == 2 +#define FLOAT float +#define VEC2 vec2 +#define VEC4 vec4 +#define SHARED_VEC2 vec2 +#elif PRECISION == 1 +#define FLOAT float +#define VEC2 vec2 +#define VEC4 vec4 +#define SHARED_VEC2 f16vec2 +#elif PRECISION == 0 +#define FLOAT float16_t +#define VEC2 f16vec2 +#define VEC4 f16vec4 +#define SHARED_VEC2 f16vec2 +#endif + +const FLOAT ALPHA = FLOAT(-1.586134342059924); +const FLOAT BETA = FLOAT(-0.052980118572961); +const FLOAT GAMMA = FLOAT(0.882911075530934); +const FLOAT DELTA = FLOAT(0.443506852043971); +const FLOAT K = FLOAT(1.230174104914001); +const FLOAT inv_K = FLOAT(1.0 / 1.230174104914001); + +shared SHARED_VEC2 shared_block[(BLOCK_SIZE + 2 * APRON) / 2][(BLOCK_SIZE + 2 * APRON) + 1]; +VEC2 load_shared(uint y, uint x) +{ + return VEC2(shared_block[y][x]); +} +void store_shared(uint y, uint x, VEC2 v) +{ + shared_block[y][x] = SHARED_VEC2(v); +} + +bvec2 band(bvec2 a, bvec2 b) +{ + return bvec2(a.x && b.x, a.y && b.y); +} + +#include "dwt_swizzle.h" + +#endif diff --git a/common/pyrowave/shaders/dwt_quant_scale.h b/common/pyrowave/shaders/dwt_quant_scale.h new file mode 100644 index 00000000..9f53d14e --- /dev/null +++ b/common/pyrowave/shaders/dwt_quant_scale.h @@ -0,0 +1,21 @@ +// Copyright (c) 2025 Hans-Kristian Arntzen +// SPDX-License-Identifier: MIT +#ifndef DWT_QUANT_SCALE_H_ +#define DWT_QUANT_SCALE_H_ + +float decode_quant_scale(uint code) +{ + // Minimum scale: 0.25 + // Maximum scale: ~2.2 + return float(code) / 8.0 + 0.25; +} + +const uint ENCODE_QUANT_IDENTITY = 6; + +uint encode_quant_scale(float scale) +{ + // Round the quant scale FP up so that the quantizer scale effectively rounds down. + return uint(ceil((scale - 0.25) * 8.0)); +} + +#endif diff --git a/common/pyrowave/shaders/dwt_swizzle.h b/common/pyrowave/shaders/dwt_swizzle.h new file mode 100644 index 00000000..63b10882 --- /dev/null +++ b/common/pyrowave/shaders/dwt_swizzle.h @@ -0,0 +1,23 @@ +// Copyright (c) 2025 Hans-Kristian Arntzen +// SPDX-License-Identifier: MIT +#ifndef DWT_SWIZZLE_H_ +#define DWT_SWIZZLE_H_ + +ivec2 unswizzle4x8(uint index) +{ + uint y = bitfieldExtract(index, 0, 1); + uint x = bitfieldExtract(index, 1, 2); + y |= bitfieldExtract(index, 3, 2) << 1; + return ivec2(x, y); +} + +ivec2 unswizzle8x8(uint index) +{ + uint y = bitfieldExtract(index, 0, 1); + uint x = bitfieldExtract(index, 1, 2); + y |= bitfieldExtract(index, 3, 2) << 1; + x |= bitfieldExtract(index, 5, 1) << 2; + return ivec2(x, y); +} + +#endif \ No newline at end of file diff --git a/common/pyrowave/shaders/idwt.h b/common/pyrowave/shaders/idwt.h new file mode 100644 index 00000000..5c7e3ee9 --- /dev/null +++ b/common/pyrowave/shaders/idwt.h @@ -0,0 +1,206 @@ +layout(local_size_x = 64) in; +layout(constant_id = 0) const bool DCShift = false; + +uint local_index; + +#include "dwt_common.h" + +layout(set = 0, binding = 0) uniform mediump sampler2DArray uTexture; +layout(set = 0, binding = 1) writeonly mediump uniform image2D uOutput; + +layout(push_constant) uniform Registers +{ + ivec2 resolution; + vec2 inv_resolution; +}; + +vec2 generate_mirror_uv(ivec2 coord, bool even_x, bool even_y) +{ + coord -= ivec2(band(bvec2(even_x, even_y), lessThan(coord, ivec2(0)))); + coord += 1; + coord += ivec2(band(bvec2(!even_x, !even_y), greaterThanEqual(coord, resolution))); + vec2 uv = vec2(coord) * inv_resolution; + return uv.yx; // Transpose on load. +} + +void write_shared_4x4(ivec2 coord, VEC4 texels0, VEC4 texels1, VEC4 texels2, VEC4 texels3) +{ + store_shared(coord.y + 0, 2 * coord.x + 0, VEC2(texels0.x, texels2.x)); + store_shared(coord.y + 0, 2 * coord.x + 1, VEC2(texels1.x, texels3.x)); + store_shared(coord.y + 0, 2 * coord.x + 2, VEC2(texels0.y, texels2.y)); + store_shared(coord.y + 0, 2 * coord.x + 3, VEC2(texels1.y, texels3.y)); + store_shared(coord.y + 1, 2 * coord.x + 0, VEC2(texels0.z, texels2.z)); + store_shared(coord.y + 1, 2 * coord.x + 1, VEC2(texels1.z, texels3.z)); + store_shared(coord.y + 1, 2 * coord.x + 2, VEC2(texels0.w, texels2.w)); + store_shared(coord.y + 1, 2 * coord.x + 3, VEC2(texels1.w, texels3.w)); +} + +void load_image_with_apron() +{ + ivec2 base_coord = ivec2(gl_WorkGroupID.xy) * ivec2(BLOCK_SIZE_HALF) - APRON_HALF; + ivec2 local_coord0 = 2 * unswizzle8x8(local_index); + ivec2 coord0 = base_coord + local_coord0; + + // Transpose on load. + VEC4 texels0 = VEC4(textureGather(uTexture, vec3(generate_mirror_uv(coord0, true, true), 0.0), 0)).wxzy; + VEC4 texels1 = VEC4(textureGather(uTexture, vec3(generate_mirror_uv(coord0, false, true), 2.0), 0)).wxzy; + VEC4 texels2 = VEC4(textureGather(uTexture, vec3(generate_mirror_uv(coord0, true, false), 1.0), 0)).wxzy; + VEC4 texels3 = VEC4(textureGather(uTexture, vec3(generate_mirror_uv(coord0, false, false), 3.0), 0)).wxzy; + write_shared_4x4(local_coord0, texels0, texels1, texels2, texels3); + + ivec2 local_coord_horiz = ivec2(BLOCK_SIZE_HALF + 2 * (local_index % 2u), 2 * (local_index / 2u)); + if (local_coord_horiz.y < BLOCK_SIZE_HALF + 2 * APRON_HALF) + { + texels0 = VEC4(textureGather(uTexture, vec3(generate_mirror_uv(base_coord + local_coord_horiz, true, true), 0.0), 0)).wxzy; + texels1 = VEC4(textureGather(uTexture, vec3(generate_mirror_uv(base_coord + local_coord_horiz, false, true), 2.0), 0)).wxzy; + texels2 = VEC4(textureGather(uTexture, vec3(generate_mirror_uv(base_coord + local_coord_horiz, true, false), 1.0), 0)).wxzy; + texels3 = VEC4(textureGather(uTexture, vec3(generate_mirror_uv(base_coord + local_coord_horiz, false, false), 3.0), 0)).wxzy; + write_shared_4x4(local_coord_horiz, texels0, texels1, texels2, texels3); + } + + ivec2 local_coord_vert = local_coord_horiz.yx; + if (local_coord_vert.x < BLOCK_SIZE_HALF) + { + texels0 = VEC4(textureGather(uTexture, vec3(generate_mirror_uv(base_coord + local_coord_vert, true, true), 0.0), 0)).wxzy; + texels1 = VEC4(textureGather(uTexture, vec3(generate_mirror_uv(base_coord + local_coord_vert, false, true), 2.0), 0)).wxzy; + texels2 = VEC4(textureGather(uTexture, vec3(generate_mirror_uv(base_coord + local_coord_vert, true, false), 1.0), 0)).wxzy; + texels3 = VEC4(textureGather(uTexture, vec3(generate_mirror_uv(base_coord + local_coord_vert, false, false), 3.0), 0)).wxzy; + write_shared_4x4(local_coord_vert, texels0, texels1, texels2, texels3); + } + + barrier(); +} + +void inverse_transform8x2() +{ + const int SIZE = 8; + const int PADDED_SIZE = SIZE + 2 * APRON; + const int PADDED_SIZE_HALF = PADDED_SIZE / 2; + VEC2 values[PADDED_SIZE]; + + ivec2 local_coord = ivec2(8 * (local_index % 4u), local_index / 4u); + + for (int i = 0; i < PADDED_SIZE; i += 2) + { + VEC2 v0 = load_shared(local_coord.y, local_coord.x + i + 0); + VEC2 v1 = load_shared(local_coord.y, local_coord.x + i + 1); + values[i + 0] = v0 * K; + values[i + 1] = v1 * inv_K; + } + + // CDF 9/7 lifting steps. + // Arith go brrr. + for (int i = 2; i < PADDED_SIZE - 1; i += 2) + values[i] -= DELTA * (values[i - 1] + values[i + 1]); + for (int i = 3; i < PADDED_SIZE - 2; i += 2) + values[i] -= GAMMA * (values[i - 1] + values[i + 1]); + for (int i = 4; i < PADDED_SIZE - 3; i += 2) + values[i] -= BETA * (values[i - 1] + values[i + 1]); + for (int i = 5; i < PADDED_SIZE - 4; i += 2) + values[i] -= ALPHA * (values[i - 1] + values[i + 1]); + + // Avoid WAR hazard. + barrier(); + + for (int i = APRON_HALF; i < PADDED_SIZE_HALF - APRON_HALF; i++) + { + VEC2 a = values[2 * i + 0]; + VEC2 b = values[2 * i + 1]; + + // Transpose the 2x2 block. + VEC2 t0 = VEC2(a.x, b.x); + VEC2 t1 = VEC2(a.y, b.y); + + // Transpose write + int y_coord = (local_coord.x >> 1) + (i - APRON_HALF); + store_shared(y_coord, 2 * local_coord.y + 0, t0); + store_shared(y_coord, 2 * local_coord.y + 1, t1); + } +} + +void inverse_transform4x2(bool active_lane, int y_offset) +{ + const int SIZE = 4; + const int PADDED_SIZE = SIZE + 2 * APRON; + const int PADDED_SIZE_HALF = PADDED_SIZE / 2; + VEC2 values[PADDED_SIZE]; + + ivec2 local_coord = ivec2(4 * (local_index % 8u), local_index / 8u + y_offset); + + if (active_lane) + { + for (int i = 0; i < PADDED_SIZE; i += 2) + { + VEC2 v0 = load_shared(local_coord.y, local_coord.x + i + 0); + VEC2 v1 = load_shared(local_coord.y, local_coord.x + i + 1); + values[i + 0] = v0 * K; + values[i + 1] = v1 * inv_K; + } + + // CDF 9/7 lifting steps. + // Arith go brrr. + for (int i = 2; i < PADDED_SIZE - 1; i += 2) + values[i] -= DELTA * (values[i - 1] + values[i + 1]); + for (int i = 3; i < PADDED_SIZE - 2; i += 2) + values[i] -= GAMMA * (values[i - 1] + values[i + 1]); + for (int i = 4; i < PADDED_SIZE - 3; i += 2) + values[i] -= BETA * (values[i - 1] + values[i + 1]); + for (int i = 5; i < PADDED_SIZE - 4; i += 2) + values[i] -= ALPHA * (values[i - 1] + values[i + 1]); + } + + // Avoid WAR hazard. + barrier(); + + if (active_lane) + { + for (int i = APRON_HALF; i < PADDED_SIZE_HALF - APRON_HALF; i++) + { + VEC2 a = values[2 * i + 0]; + VEC2 b = values[2 * i + 1]; + + // Transpose the 2x2 block. + VEC2 t0 = VEC2(a.x, b.x); + VEC2 t1 = VEC2(a.y, b.y); + + // Transpose write + int y_coord = (local_coord.x >> 1) + (i - APRON_HALF); + store_shared(y_coord, 2 * local_coord.y + 0, t0); + store_shared(y_coord, 2 * local_coord.y + 1, t1); + } + } +} + +void main() +{ + local_index = gl_SubgroupID * gl_SubgroupSize + gl_SubgroupInvocationID; + + load_image_with_apron(); + + // Horizontal transform. + inverse_transform8x2(); + + // Also need to transform the apron. + inverse_transform4x2(local_index < 32, BLOCK_SIZE_HALF); + + barrier(); + + // Vertical transform. + inverse_transform8x2(); + + barrier(); + + ivec2 local_coord = unswizzle8x8(local_index); + + for (int y = local_coord.y; y < BLOCK_SIZE_HALF; y += 8) + { + for (int x = local_coord.x; x < BLOCK_SIZE; x += 8) + { + VEC2 v = load_shared(y, x); + if (DCShift) + v += FLOAT(0.5); + imageStore(uOutput, ivec2(2 * y + 0, x) + BLOCK_SIZE * ivec2(gl_WorkGroupID.yx), v.xxxx); + imageStore(uOutput, ivec2(2 * y + 1, x) + BLOCK_SIZE * ivec2(gl_WorkGroupID.yx), v.yyyy); + } + } +} diff --git a/common/pyrowave/shaders/idwt_0.comp b/common/pyrowave/shaders/idwt_0.comp new file mode 100644 index 00000000..26937ca9 --- /dev/null +++ b/common/pyrowave/shaders/idwt_0.comp @@ -0,0 +1,13 @@ +#version 450 +// Copyright (c) 2025 Hans-Kristian Arntzen +// SPDX-License-Identifier: MIT + +#extension GL_KHR_shader_subgroup_basic : require +#extension GL_KHR_shader_subgroup_quad : require +#extension GL_EXT_shader_explicit_arithmetic_types_float16 : require +#extension GL_EXT_shader_subgroup_extended_types_float16 : require +#extension GL_ARB_shading_language_include : require + +#define PRECISION 0 + +#include "idwt.h" diff --git a/common/pyrowave/shaders/idwt_1.comp b/common/pyrowave/shaders/idwt_1.comp new file mode 100644 index 00000000..017dcc05 --- /dev/null +++ b/common/pyrowave/shaders/idwt_1.comp @@ -0,0 +1,13 @@ +#version 450 +// Copyright (c) 2025 Hans-Kristian Arntzen +// SPDX-License-Identifier: MIT + +#extension GL_KHR_shader_subgroup_basic : require +#extension GL_KHR_shader_subgroup_quad : require +#extension GL_EXT_shader_explicit_arithmetic_types_float16 : require +#extension GL_EXT_shader_subgroup_extended_types_float16 : require +#extension GL_ARB_shading_language_include : require + +#define PRECISION 1 + +#include "idwt.h" diff --git a/common/pyrowave/shaders/idwt_2.comp b/common/pyrowave/shaders/idwt_2.comp new file mode 100644 index 00000000..38a3dea9 --- /dev/null +++ b/common/pyrowave/shaders/idwt_2.comp @@ -0,0 +1,13 @@ +#version 450 +// Copyright (c) 2025 Hans-Kristian Arntzen +// SPDX-License-Identifier: MIT + +#extension GL_KHR_shader_subgroup_basic : require +#extension GL_KHR_shader_subgroup_quad : require +#extension GL_EXT_shader_explicit_arithmetic_types_float16 : require +#extension GL_EXT_shader_subgroup_extended_types_float16 : require +#extension GL_ARB_shading_language_include : require + +#define PRECISION 2 + +#include "idwt.h" diff --git a/common/pyrowave/shaders/power_to_db.comp b/common/pyrowave/shaders/power_to_db.comp new file mode 100644 index 00000000..e0371ce4 --- /dev/null +++ b/common/pyrowave/shaders/power_to_db.comp @@ -0,0 +1,33 @@ +#version 450 +// Copyright (c) 2025 Hans-Kristian Arntzen +// SPDX-License-Identifier: MIT +#extension GL_EXT_samplerless_texture_functions : require + +layout(set = 0, binding = 0) uniform texture2D uTex; +layout(set = 0, binding = 1) writeonly uniform image2D uImage; + +layout(local_size_x = 8, local_size_y = 8) in; + +float power_to_db(float p) +{ + return max(10.0 * log2(p) / log2(10.0), -100.0); +} + +void main() +{ + float input_power = 0.0; + const int Stride = 8; + for (int y = 0; y < Stride; y++) + { + for (int x = 0; x < Stride; x++) + { + if (any(notEqual(ivec4(gl_GlobalInvocationID.xy, x, y), ivec4(0)))) + { + vec2 c = texelFetch(uTex, ivec2(gl_GlobalInvocationID.xy) * Stride + ivec2(x, y), 0).xy; + input_power += dot(c, c); + } + } + } + + imageStore(uImage, ivec2(gl_GlobalInvocationID.xy), vec4(power_to_db(input_power))); +} diff --git a/common/pyrowave/shaders/resolve_rate_control.comp b/common/pyrowave/shaders/resolve_rate_control.comp new file mode 100644 index 00000000..0e972797 --- /dev/null +++ b/common/pyrowave/shaders/resolve_rate_control.comp @@ -0,0 +1,80 @@ +#version 450 +// Copyright (c) 2025 Hans-Kristian Arntzen +// SPDX-License-Identifier: MIT +#extension GL_KHR_shader_subgroup_basic : require +#extension GL_KHR_shader_subgroup_ballot : require +#extension GL_KHR_shader_subgroup_arithmetic : require +#extension GL_KHR_shader_subgroup_shuffle_relative : require + +layout(local_size_x_id = 0) in; + +struct RDOperation +{ + int quant; + uint block_offset_saving; +}; + +const int BLOCK_SPACE_SUBDIVISION = 16; + +layout(set = 0, binding = 0) readonly buffer Buckets +{ + layout(offset = 4) int consumed_payload; + layout(offset = 64) int total_savings_per_bucket[128 * BLOCK_SPACE_SUBDIVISION]; + RDOperation rdo_operations[]; +} buckets; + +layout(set = 0, binding = 1) buffer QuantList +{ + int data[]; +} quant_data; + +layout(push_constant) uniform Registers +{ + uint target_payload_size; + uint num_blocks_per_subdivision; +} registers; + +void main() +{ + int required_savings_per_bucket = int(buckets.consumed_payload) - int(registers.target_payload_size); + if (gl_WorkGroupID.x != 0) + { + int prev_bucket_total = buckets.total_savings_per_bucket[gl_WorkGroupID.x - 1]; + // This bucket is empty. + if (buckets.total_savings_per_bucket[gl_WorkGroupID.x] == prev_bucket_total) + return; + + required_savings_per_bucket -= prev_bucket_total; + } + else + { + // This bucket is empty. + if (buckets.total_savings_per_bucket[gl_WorkGroupID.x] == 0) + return; + } + + // If all previous buckets can complete the job, skip. + if (required_savings_per_bucket <= 0) + return; + + uint total_saved = 0; + + for (uint i = 0; i < registers.num_blocks_per_subdivision && total_saved < required_savings_per_bucket; i += gl_SubgroupSize) + { + RDOperation op = RDOperation(0, 0); + if (i + gl_SubgroupInvocationID < registers.num_blocks_per_subdivision) + op = buckets.rdo_operations[gl_WorkGroupID.x * registers.num_blocks_per_subdivision + i + gl_SubgroupInvocationID]; + + uint saving = bitfieldExtract(op.block_offset_saving, 16, 16); + uint block_offset = bitfieldExtract(op.block_offset_saving, 0, 16); + + uint scan_saving = subgroupInclusiveAdd(saving); + + bool should_apply_quant = total_saved + scan_saving - saving < required_savings_per_bucket; + if (should_apply_quant && saving != 0) + atomicMax(quant_data.data[block_offset], op.quant); + + total_saved += subgroupBroadcast(scan_saving, gl_SubgroupSize - 1); + } +} + diff --git a/common/pyrowave/shaders/wavelet_dequant.comp b/common/pyrowave/shaders/wavelet_dequant.comp new file mode 100644 index 00000000..a212ab0f --- /dev/null +++ b/common/pyrowave/shaders/wavelet_dequant.comp @@ -0,0 +1,263 @@ +#version 450 +// Copyright (c) 2025 Hans-Kristian Arntzen +// SPDX-License-Identifier: MIT +#extension GL_KHR_shader_subgroup_basic : require +#extension GL_KHR_shader_subgroup_ballot : require +#extension GL_KHR_shader_subgroup_vote : require +#extension GL_KHR_shader_subgroup_arithmetic : require +#extension GL_KHR_shader_subgroup_shuffle_relative : require +#extension GL_EXT_shader_8bit_storage : require +#extension GL_EXT_shader_16bit_storage : require +#extension GL_ARB_shading_language_include : require + +layout(local_size_x = 128) in; + +layout(set = 0, binding = 0) writeonly uniform image2DArray uDequantImg; + +layout(set = 0, binding = 1) readonly buffer PayloadOffsets +{ + uint data[]; +} payload_offsets; + +layout(set = 0, binding = 2) readonly buffer Payloads +{ + uint data[]; +} payload_data_u32; + +layout(set = 0, binding = 2) readonly buffer Payloads16 +{ + uint16_t data[]; +} payload_data_u16; + +layout(set = 0, binding = 2) readonly buffer Payloads8 +{ + uint8_t data[]; +} payload_data_u8; + +#include "dwt_swizzle.h" +#include "dwt_quant_scale.h" +#include "constants.h" + +layout(push_constant) uniform Registers +{ + ivec2 resolution; + int output_layer; + int block_offset_32x32; + int block_stride_32x32; +} registers; + +mat2x4 decode_payload(uint code_word, uint q_bits, uint offset, uint block_index) +{ + bool empty_block = code_word == 0; + if (empty_block) + return mat2x4(vec4(0.0), vec4(0.0)); + + int bit_offset = 2 * int(block_index); + + // First, we need to compute the offset that our 4x2 block starts on. + uint lsbs = code_word & 0x5555u; + uint msbs = code_word & 0xaaaau; + uint msbs_shift = msbs >> 1; + msbs |= msbs_shift; + + uint byte_offset = + bitCount(bitfieldExtract(lsbs, 0, bit_offset)) + + bitCount(bitfieldExtract(msbs, 0, bit_offset)) + + q_bits * block_index + offset; + + // Eagerly load the data to keep latency down. + // Also forces the descriptor to be loaded early. + uint payload = uint(payload_data_u8.data[byte_offset]); + + uint local_control_word = bitfieldExtract(code_word, bit_offset, 2); + int decoded_abs[8] = int[8](0, 0, 0, 0, 0, 0, 0, 0); + int plane_iterations = int(q_bits + local_control_word); + + for (int q = plane_iterations - 1; q >= 0; q--) + { + for (int b = 0; b < 8; b++) + { + int decoded = int(bitfieldExtract(payload, b, 1)); + decoded_abs[b] = bitfieldInsert(decoded_abs[b], decoded, q, 1); + } + byte_offset++; + payload = uint(payload_data_u8.data[byte_offset]); + } + + mat2x4 m; + + for (int i = 0; i < 4; i++) + { + for (int j = 0; j < 2; j++) + { + float v = float(decoded_abs[i * 2 + j]); + if (v != 0.0) + v += 0.5; + m[j][i] = v; + } + } + + return m; +} + +shared uint shared_sign_offset; +shared uint shared_plane_byte_offsets[16]; +shared uint shared_sign_scan[8]; + +const int MaxScaleExp = 4; + +float decode_quant(uint quant_code) +{ + // Custom FP formulation for numbers in (0, 16) range. + int e = MaxScaleExp - int(quant_code >> 3); + int m = int(quant_code) & 0x7; + float inv_quant = (1.0 / (8.0 * 1024.0 * 1024.0)) * float((8 + m) * (1 << (20 + e))); + return inv_quant; +} + +uint scan8(uint v) +{ + for (uint i = 1; i < gl_NumSubgroups; i *= 2) + { + uint up = subgroupShuffleUp(v, i); + v += gl_SubgroupInvocationID >= i ? up : 0; + } + + return v; +} + +void main() +{ + uint local_index = gl_SubgroupID * gl_SubgroupSize + gl_SubgroupInvocationID; + + int block_index_32x32 = int(registers.block_offset_32x32 + + gl_WorkGroupID.y * registers.block_stride_32x32 + + gl_WorkGroupID.x); + + uint block_local_index = bitfieldExtract(local_index, 0, 3); + uint block_x = bitfieldExtract(local_index, 3, 2); + uint block_y = bitfieldExtract(local_index, 5, 2); + uint linear_block = block_y * 4 + block_x; + + // Each thread individually decodes 8 values. + ivec2 local_coord = unswizzle8x8(block_local_index << 3); + + ivec2 coord = ivec2(gl_WorkGroupID.xy) * 32; + coord += 8 * ivec2(block_x, block_y); + coord += local_coord; + + uint offset_u32 = payload_offsets.data[block_index_32x32]; + + if (offset_u32 == ~0u) + { + for (int j = 0; j < 2; j++) + for (int i = 0; i < 4; i++) + imageStore(uDequantImg, ivec3(coord + ivec2(i, j), registers.output_layer), vec4(0.0)); + return; + } + + uint ballot = payload_data_u32.data[offset_u32] & 0xffff; + uint q_code = payload_data_u32.data[offset_u32 + 1] & 0xff; + + if (local_index < 16) + { + uint control_word = 0; + uint q_bits = 0; + + if (bitfieldExtract(ballot, int(local_index), 1) != 0) + { + uint local_code_offset = bitCount(bitfieldExtract(ballot, 0, int(local_index))); + control_word = uint(payload_data_u16.data[offset_u32 * 2 + 4 + local_code_offset]); + q_bits = uint(payload_data_u8.data[offset_u32 * 4 + 8 + bitCount(ballot) * 2 + local_code_offset]) & 0xfu; + } + + uint lsbs = control_word & 0x5555u; + uint msbs = control_word & 0xaaaau; + uint msbs_shift = msbs >> 1; + msbs |= msbs_shift; + uint byte_cost = bitCount(lsbs) + bitCount(msbs) + q_bits * 8; + + uint byte_scan = offset_u32 * 4 + 8 + 3 * bitCount(ballot) + subgroupInclusiveAdd(byte_cost); + if (local_index == 15) + shared_sign_offset = 8 * byte_scan; + shared_plane_byte_offsets[local_index] = byte_scan - byte_cost; + } + + barrier(); + + mat2x4 v; + int significant_count; + + if (bitfieldExtract(ballot, int(linear_block), 1) != 0) + { + uint local_code_offset = bitCount(bitfieldExtract(ballot, 0, int(linear_block))); + uint control_word = uint(payload_data_u16.data[offset_u32 * 2 + 4 + local_code_offset]); + uint control_word2 = uint(payload_data_u8.data[offset_u32 * 4 + 8 + bitCount(ballot) * 2 + local_code_offset]); + + v = decode_payload(control_word, control_word2 & 0xfu, + shared_plane_byte_offsets[linear_block], block_local_index); + + significant_count = 0; + for (int j = 0; j < 2; j++) + for (int i = 0; i < 4; i++) + significant_count += int(v[j][i] != 0.0); + + float q = decode_quant(q_code); + float inv_scale = q * decode_quant_scale(bitfieldExtract(control_word2, QUANT_SCALE_OFFSET - 16, QUANT_SCALE_BITS)); + + v *= inv_scale; + } + else + { + v = mat2x4(vec4(0.0), vec4(0.0)); + significant_count = 0; + } + + // Figure out how many significant coefficients we have. + int significant_scan = subgroupInclusiveAdd(significant_count); + if (gl_SubgroupInvocationID == gl_SubgroupSize - 1) + shared_sign_scan[gl_SubgroupID] = significant_scan; + + barrier(); + + if (local_index < 8) + shared_sign_scan[local_index] = scan8(shared_sign_scan[local_index]); + + barrier(); + + // Compute where we need to start reading sign bits from. + uint sign_offset = shared_sign_offset + significant_scan - significant_count; + if (gl_SubgroupID != 0) + sign_offset += shared_sign_scan[gl_SubgroupID - 1]; + + // Read out all sign bits we could possibly access per thread. + // On AMD at least, this 64-bit load should be vectorizable. + uint sign_word = payload_data_u32.data[sign_offset / 32 + 0]; + uint sign_word_upper = payload_data_u32.data[sign_offset / 32 + 1]; + uint masked_sign_offset = sign_offset & 31u; + if (masked_sign_offset != 0) + { + sign_word >>= masked_sign_offset; + sign_word |= sign_word_upper << (32 - masked_sign_offset); + } + + int sign_counter = 0; + + // Clock out the sign bits as needed. + for (int i = 0; i < 4; i++) + { + for (int j = 0; j < 2; j++) + { + if (v[j][i] != 0.0) + { + v[j][i] *= 1.0 - 2.0 * float(bitfieldExtract(sign_word, sign_counter, 1)); + sign_counter++; + } + } + } + + // Write output. + for (int j = 0; j < 2; j++) + for (int i = 0; i < 4; i++) + imageStore(uDequantImg, ivec3(coord + ivec2(i, j), registers.output_layer), vec4(v[j][i])); +} diff --git a/common/pyrowave/shaders/wavelet_quant.comp b/common/pyrowave/shaders/wavelet_quant.comp new file mode 100644 index 00000000..afb0d0b6 --- /dev/null +++ b/common/pyrowave/shaders/wavelet_quant.comp @@ -0,0 +1,317 @@ +#version 450 +// Copyright (c) 2025 Hans-Kristian Arntzen +// SPDX-License-Identifier: MIT +#extension GL_KHR_shader_subgroup_basic : require +#extension GL_KHR_shader_subgroup_arithmetic : require +#extension GL_KHR_shader_subgroup_ballot : require +#extension GL_KHR_shader_subgroup_shuffle : require +#extension GL_KHR_shader_subgroup_vote : require +#extension GL_KHR_shader_subgroup_shuffle_relative : require +#extension GL_KHR_shader_subgroup_clustered : require +#extension GL_EXT_shader_8bit_storage : require +#extension GL_EXT_shader_explicit_arithmetic_types_float16 : require +#extension GL_EXT_shader_explicit_arithmetic_types_int16 : require +#extension GL_ARB_shading_language_include : require + +#include "dwt_quant_scale.h" +#include "constants.h" + +layout(local_size_x = 128) in; +layout(constant_id = 1) const bool SkipQuantScale = false; + +layout(set = 0, binding = 0) uniform sampler2DArray uTexture; + +struct QuantStats +{ + float16_t square_error; + uint16_t payload_cost; +}; + +struct BlockMeta +{ + uint code_word; + uint offset; +}; + +// Fit into 64 bytes. +struct BlockStats +{ + uint num_planes; + QuantStats errors[15]; +}; + +layout(set = 0, binding = 1) writeonly buffer SSBOMeta +{ + BlockMeta meta[]; +} block_meta; + +layout(set = 0, binding = 2) writeonly buffer SSBOBlockStats +{ + BlockStats stats[]; +} block_stats; + +layout(set = 0, binding = 3) buffer Payloads +{ + layout(offset = 0) uint counter; + layout(offset = 8) uint8_t data[]; +} payload_data; + +#include "dwt_swizzle.h" + +layout(push_constant) uniform Registers +{ + ivec2 resolution; + ivec2 resolution_8x8_blocks; + vec2 inv_resolution; + float input_layer; + float quant_resolution; + int block_offset; + int block_stride; + float rdo_distortion_scale; +} registers; + +float max4(vec4 v) +{ + vec2 v2 = max(v.xy, v.zw); + return max(v2.x, v2.y); +} + +int max4(ivec4 v) +{ + ivec2 v2 = max(v.xy, v.zw); + return max(v2.x, v2.y); +} + +int scan_clustered8(int v) +{ + for (uint i = 1; i < 8; i *= 2) + { + int up = subgroupShuffleUp(v, i); + v += (gl_SubgroupInvocationID & 7u) >= i ? up : 0; + } + + return v; +} + +void compute_quant_scale(float max_wave_texels, out uint quant_code, out float quant_scale) +{ + if (SkipQuantScale || max_wave_texels < 1.0) + { + quant_code = ENCODE_QUANT_IDENTITY; + quant_scale = 1.0; + } + else + { + int e; + frexp(max_wave_texels - 0.25, e); + float target_max = float(1 << e) - 0.25; + float inv_scale = max_wave_texels / target_max; + quant_code = encode_quant_scale(inv_scale); + quant_scale = 1.0 / decode_quant_scale(quant_code); + } +} + +float compute_square_error(mat2x4 v, int q, out uint num_significant_values) +{ + v = mat2x4(abs(v[0]), abs(v[1])); + mat2x4 iv = mat2x4(floor(ldexp(v[0], ivec4(-q))), trunc(ldexp(v[1], ivec4(-q)))); + num_significant_values = 0; + for (int j = 0; j < 2; j++) + for (int i = 0; i < 4; i++) + if (iv[j][i] != 0.0) + num_significant_values++; + iv[0] += mix(vec4(0.0), vec4(0.5), notEqual(iv[0], vec4(0.0))); + iv[1] += mix(vec4(0.0), vec4(0.5), notEqual(iv[1], vec4(0.0))); + iv = mat2x4(trunc(ldexp(iv[0], ivec4(q))), trunc(ldexp(iv[1], ivec4(q)))); + mat2x4 err = v - iv; + num_significant_values = subgroupClusteredAdd(num_significant_values, 8); + return (dot(err[0], err[0]) + dot(err[1], err[1])) * registers.rdo_distortion_scale; +} + +struct QuantResult +{ + float square_error; + int encode_cost_early; + int block4x2_shifted; + int encode_cost_late_bits; + int quality_planes; +}; + +QuantResult compute_quant_stats(mat2x4 v, int q, int msb, int block4x2_max, float inv_quant_squared) +{ + block4x2_max >>= q; + + uint wave8_num_significants; + QuantResult result; + + result.square_error = compute_square_error(v, q, wave8_num_significants) * inv_quant_squared; + result.block4x2_shifted = block4x2_max; + + result.encode_cost_early = block4x2_max > 0 ? 1 : 0; + msb -= q; + + result.quality_planes = 0; + + if (msb >= 3) + { + result.quality_planes = msb - 2; + // Must encode the sign plane if we have quality planes. + result.encode_cost_early = result.quality_planes + 1; + result.block4x2_shifted >>= result.quality_planes; + } + + result.encode_cost_early += findMSB(result.block4x2_shifted) + 1; + result.encode_cost_late_bits = 8 * subgroupClusteredAdd(max(result.encode_cost_early - 1, 0), 8) + int(wave8_num_significants); + return result; +} + +float square(float v) +{ + return v * v; +} + +void encode_payload(ivec2 block_index_8x8, mat2x4 texels) +{ + precise float max_subblock_texel = max(max4(abs(texels[0])), max4(abs(texels[1]))); + precise float max_wave_texels = subgroupClusteredMax(max_subblock_texel, 8); + float quant_scale; + uint quant_code; + compute_quant_scale(max_wave_texels, quant_code, quant_scale); + texels *= quant_scale; + max_wave_texels *= quant_scale; + max_subblock_texel *= quant_scale; + + float overall_quant_scale = registers.quant_resolution * quant_scale; + float inv_quant = 1.0 / overall_quant_scale; + float inv_quant_squared = inv_quant * inv_quant; + ivec4 abs_quant_texels0 = abs(ivec4(texels[0])); + ivec4 abs_quant_texels1 = abs(ivec4(texels[1])); + int max_absolute_value = int(max_wave_texels); + int block4x2_max = int(max_subblock_texel); + + uint block_index = registers.block_offset + block_index_8x8.y * registers.block_stride + block_index_8x8.x; + + // The entire block quantizes to zero. + if (max_absolute_value == 0) + { + if ((gl_SubgroupInvocationID & 7) == 0) + { + block_meta.meta[block_index] = BlockMeta(0, 0); + block_stats.stats[block_index].num_planes = 0; + block_stats.stats[block_index].errors[0] = QuantStats(float16_t(0.0), uint16_t(0)); + } + return; + } + + int msb = findMSB(max_absolute_value); + + QuantResult result = compute_quant_stats(texels, 0, msb, block4x2_max, inv_quant_squared); + int scan = scan_clustered8(result.encode_cost_early); + + uint global_offset = 0; + + // For feedback, and allocation of payload. + if ((gl_SubgroupInvocationID & 7u) == 7u) + global_offset = atomicAdd(payload_data.counter, scan); + global_offset = subgroupShuffle(global_offset, gl_SubgroupInvocationID | 7u); + + scan -= result.encode_cost_early; + + // First, encode the code word. + int quality_planes = result.quality_planes; + uint code_word = quality_planes << Q_PLANES_OFFSET; + code_word = bitfieldInsert(code_word, quant_code, QUANT_SCALE_OFFSET, QUANT_SCALE_BITS); + uint plane_code = findMSB(result.block4x2_shifted) + 1; + + uint merged_plane_code = plane_code << ((gl_SubgroupInvocationID & 7u) * 2u); + merged_plane_code |= subgroupShuffleXor(merged_plane_code, 1u); + merged_plane_code |= subgroupShuffleXor(merged_plane_code, 2u); + merged_plane_code |= subgroupShuffleXor(merged_plane_code, 4u); + code_word |= merged_plane_code; + + if ((gl_SubgroupInvocationID & 7u) == 0u) + { + block_meta.meta[block_index] = BlockMeta(code_word, global_offset); + block_stats.stats[block_index].num_planes = msb + 1; + block_stats.stats[block_index].errors[0] = QuantStats( + float16_t(0.0), // We don't care about distortion from 0 quant since we've already made that decision. + uint16_t(result.encode_cost_late_bits)); + } + + for (int q = 1; q <= msb; q++) + { + QuantResult quant_result = compute_quant_stats(texels, q, msb, block4x2_max, inv_quant_squared); + float square_error = subgroupClusteredAdd(quant_result.square_error, 8); + + if ((gl_SubgroupInvocationID & 7u) == 0) + { + block_stats.stats[block_index].errors[q] = QuantStats( + float16_t(min(square_error, 60000.0)), + uint16_t(quant_result.encode_cost_late_bits)); + } + } + + // Record distortion for throwing away everything. + float square_error = subgroupClusteredAdd((dot(texels[0], texels[0]) + dot(texels[1], texels[1])) * inv_quant_squared, 8); + if ((gl_SubgroupInvocationID & 7u) == 0) + block_stats.stats[block_index].errors[msb + 1] = QuantStats(float16_t(min(60000.0, square_error)), uint16_t(0)); + + uint byte_offset = scan + global_offset; + bool need_sign = result.block4x2_shifted != 0 || quality_planes != 0; + + // Don't pack the sign plane until final pass, since we don't know how we quantize yet. + if (need_sign) + { + uvec4 s0 = uvec4(lessThan(texels[0], vec4(0.0))) << uvec4(0, 1, 2, 3); + uvec4 s1 = uvec4(lessThan(texels[1], vec4(0.0))) << uvec4(4, 5, 6, 7); + uint s = s0.x | s0.y | s0.z | s0.w | s1.x | s1.y | s1.z | s1.w; + payload_data.data[byte_offset++] = uint8_t(s); + + int plane_iterations = quality_planes + int(plane_code); + int q = plane_iterations - 1; + do + { + s0 = uvec4( + bitfieldExtract(uint(abs_quant_texels0.x), q, 1), + bitfieldExtract(uint(abs_quant_texels0.y), q, 1), + bitfieldExtract(uint(abs_quant_texels0.z), q, 1), + bitfieldExtract(uint(abs_quant_texels0.w), q, 1)); + s1 = uvec4( + bitfieldExtract(uint(abs_quant_texels1.x), q, 1), + bitfieldExtract(uint(abs_quant_texels1.y), q, 1), + bitfieldExtract(uint(abs_quant_texels1.z), q, 1), + bitfieldExtract(uint(abs_quant_texels1.w), q, 1)); + s0 <<= uvec4(0, 1, 2, 3); + s1 <<= uvec4(4, 5, 6, 7); + s = s0.x | s0.y | s0.z | s0.w | s1.x | s1.y | s1.z | s1.w; + payload_data.data[byte_offset++] = uint8_t(s); + q--; + } while (q >= 0); + } +} + +void main() +{ + uint local_index = gl_SubgroupID * gl_SubgroupSize + gl_SubgroupInvocationID; + uint block_local_index = bitfieldExtract(local_index, 0, 3); + uint block_x = bitfieldExtract(local_index, 3, 2); + uint block_y = bitfieldExtract(local_index, 5, 2); + + // Each thread individually encodes 8 values. + ivec2 local_coord = unswizzle8x8(block_local_index << 3); + + ivec2 coord = ivec2(gl_WorkGroupID.xy) * 32; + coord += 8 * ivec2(block_x, block_y); + coord += local_coord; + + ivec2 block_index = 4 * ivec2(gl_WorkGroupID.xy) + ivec2(block_x, block_y); + + vec3 uv = vec3(vec2(coord) * registers.inv_resolution, registers.input_layer); + vec4 texels0 = textureGatherOffset(uTexture, uv, ivec2(1, 1)).wxzy; + vec4 texels1 = textureGatherOffset(uTexture, uv, ivec2(3, 1)).wxzy; + precise vec4 scaled_texels0 = texels0 * registers.quant_resolution; + precise vec4 scaled_texels1 = texels1 * registers.quant_resolution; + bool in_bounds = all(lessThan(block_index, registers.resolution_8x8_blocks)); + if (in_bounds) + encode_payload(block_index, mat2x4(scaled_texels0, scaled_texels1)); +} diff --git a/common/pyrowave/shaders/yuv2rgb.frag b/common/pyrowave/shaders/yuv2rgb.frag new file mode 100644 index 00000000..363d8f18 --- /dev/null +++ b/common/pyrowave/shaders/yuv2rgb.frag @@ -0,0 +1,60 @@ +#version 450 + +#if DELTA +layout(set = 0, binding = 0) uniform texture2D Y0; +layout(set = 0, binding = 1) uniform texture2D Y1; +#else +layout(set = 0, binding = 0) uniform texture2D Y; +layout(set = 0, binding = 1) uniform texture2D Cb; +layout(set = 0, binding = 2) uniform texture2D Cr; +#endif +layout(set = 0, binding = 3) uniform sampler Samp; + +layout(location = 0) out vec3 FragColor; +layout(location = 0) in vec2 vUV; + +layout(constant_id = 0) const bool BT2020 = false; +layout(constant_id = 1) const bool FullRange = false; + +const mat3 yuv2rgb_bt709 = mat3( + vec3(1.0, 1.0, 1.0), + vec3(0.0, -0.13397432 / 0.7152, 1.8556), + vec3(1.5748, -0.33480248 / 0.7152, 0.0)); + +const mat3 yuv2rgb_bt2020 = mat3( + vec3(1.0, 1.0, 1.0), + vec3(0.0, -0.202008 / 0.587, 1.772), + vec3(1.402, -0.419198 / 0.587, 0.0)); + +void main() +{ +#if DELTA + float y0 = textureLod(sampler2D(Y0, Samp), vUV, 0.0).x; + float y1 = textureLod(sampler2D(Y1, Samp), vUV, 0.0).x; + FragColor = vec3(abs(y0 - y1) * 10.0); +#else + float y = textureLod(sampler2D(Y, Samp), vUV, 0.0).x; + float cb = textureLod(sampler2D(Cb, Samp), vUV, 0.0).x; + float cr = textureLod(sampler2D(Cr, Samp), vUV, 0.0).x; + + cb -= 0.5; + cr -= 0.5; + + if (!FullRange) + { + y -= 16.0 / 255.0; + y *= 255.0 / 219.0; + const float ChromaScale = 255.0 / 224.0; + cb *= ChromaScale; + cr *= ChromaScale; + y = clamp(y, 0.0, 1.0); + cb = clamp(cb, -0.5, 0.5); + cr = clamp(cr, -0.5, 0.5); + } + + if (BT2020) + FragColor = yuv2rgb_bt2020 * vec3(y, cb, cr); + else + FragColor = yuv2rgb_bt709 * vec3(y, cb, cr); +#endif +} diff --git a/common/wivrn_packets.h b/common/wivrn_packets.h index ce852ddd..0d03ba02 100644 --- a/common/wivrn_packets.h +++ b/common/wivrn_packets.h @@ -168,6 +168,7 @@ enum video_codec h265, hevc = h265, av1, + pyrowave, }; struct audio_data diff --git a/server/CMakeLists.txt b/server/CMakeLists.txt index 3794c3c6..bc5d00fa 100644 --- a/server/CMakeLists.txt +++ b/server/CMakeLists.txt @@ -145,6 +145,12 @@ if (WIVRN_BUILD_SERVER) target_link_libraries(wivrn-server PRIVATE PkgConfig::LIBAV PkgConfig::LIBDRM) endif() + target_sources( + wivrn-server + PRIVATE encoder/video_encoder_pyrowave.cpp + ) + target_link_libraries(wivrn-server PRIVATE pyrowave) + if(WIVRN_USE_VULKAN_ENCODE) target_sources(wivrn-server PRIVATE encoder/video_encoder_vulkan.cpp diff --git a/server/driver/configuration.cpp b/server/driver/configuration.cpp index 002dc5f0..2e4dc42e 100644 --- a/server/driver/configuration.cpp +++ b/server/driver/configuration.cpp @@ -64,6 +64,8 @@ NLOHMANN_JSON_SERIALIZE_ENUM( {h265, "hevc"}, {av1, "av1"}, {av1, "AV1"}, + {pyrowave, "pyrowave"}, + {pyrowave, "PyroWave"}, }) NLOHMANN_JSON_SERIALIZE_ENUM( diff --git a/server/driver/wivrn_comp_target.cpp b/server/driver/wivrn_comp_target.cpp index 46a0be4e..a66e9086 100644 --- a/server/driver/wivrn_comp_target.cpp +++ b/server/driver/wivrn_comp_target.cpp @@ -69,6 +69,7 @@ std::vector wivrn_comp_target::wanted_device_extensions = { #ifdef VK_KHR_video_encode_h265 VK_KHR_VIDEO_ENCODE_H265_EXTENSION_NAME, #endif + VK_KHR_8BIT_STORAGE_EXTENSION_NAME, }; static void target_init_semaphores(struct wivrn_comp_target * cn); diff --git a/server/encoder/encoder_settings.cpp b/server/encoder/encoder_settings.cpp index 6fd30ad8..ff627324 100644 --- a/server/encoder/encoder_settings.cpp +++ b/server/encoder/encoder_settings.cpp @@ -70,6 +70,9 @@ static void split_bitrate(std::vector & encoders, uint6 case wivrn::h265: case wivrn::av1: break; + case wivrn::pyrowave: + w *= 50; + break; } encoder.bitrate = w; total_weight += w; @@ -374,6 +377,21 @@ std::vector get_encoder_settings(wivrn_vk_bundle & bundle, uin config.encoder_passthrough->offset_y = 0; fill_defaults(bundle, info.supported_codecs, *config.encoder_passthrough, config.bit_depth); + config.encoder_passthrough = { + .name = encoder_pyrowave, + .width = 1, + .height = 1, + .codec = video_codec::pyrowave, + }; + config.encoders = { + { + .name = encoder_pyrowave, + .width = 1, + .height = 1, + .codec = video_codec::pyrowave, + }, + }; + uint64_t bitrate = config.bitrate.value_or(default_bitrate); std::array default_scale; default_scale.fill(info.eye_gaze ? 0.35 : 0.5); diff --git a/server/encoder/ffmpeg/video_encoder_va.cpp b/server/encoder/ffmpeg/video_encoder_va.cpp index bbab42ce..e6e0330f 100644 --- a/server/encoder/ffmpeg/video_encoder_va.cpp +++ b/server/encoder/ffmpeg/video_encoder_va.cpp @@ -58,6 +58,8 @@ const char * encoder(video_codec codec) return "hevc_vaapi"; case video_codec::av1: return "av1_vaapi"; + case video_codec::pyrowave: + throw std::runtime_error("pyrowave is only supported by the specific encoder"); } throw std::runtime_error("invalid codec " + std::to_string(int(codec))); } @@ -239,6 +241,8 @@ video_encoder_va::video_encoder_va(wivrn_vk_bundle & vk, case video_codec::av1: encoder_ctx->profile = FF_PROFILE_AV1_MAIN; break; + case video_codec::pyrowave: + throw std::runtime_error("pyrowave is only supported by the specific encoder"); } for (auto option: settings.options) { diff --git a/server/encoder/video_encoder.cpp b/server/encoder/video_encoder.cpp index 8bbaaffe..7e768b65 100644 --- a/server/encoder/video_encoder.cpp +++ b/server/encoder/video_encoder.cpp @@ -42,6 +42,7 @@ #include "video_encoder_vulkan_h264.h" // #include "video_encoder_vulkan_h265.h" #endif +#include "video_encoder_pyrowave.h" namespace wivrn { @@ -126,6 +127,8 @@ std::unique_ptr video_encoder::create( // break; case video_codec::av1: throw std::runtime_error("av1 not supported for vulkan video encode"); + case video_codec::pyrowave: + throw std::runtime_error("pyrowave is only supported by the specific encoder"); } #else throw std::runtime_error("Vulkan video encode not enabled"); @@ -155,6 +158,11 @@ std::unique_ptr video_encoder::create( throw std::runtime_error("vaapi support not enabled"); #endif } + if (settings.encoder_name == encoder_pyrowave) + { + res = std::make_unique(wivrn_vk, settings, fps, stream_idx); + } + if (not res) throw std::runtime_error("Failed to create encoder " + settings.encoder_name); @@ -174,6 +182,9 @@ std::unique_ptr video_encoder::create( case av1: file += ".av1"; break; + case pyrowave: + file += ".pyro"; + break; } res->video_dump.open(file); } diff --git a/server/encoder/video_encoder.h b/server/encoder/video_encoder.h index 639f56b6..a9af8d01 100644 --- a/server/encoder/video_encoder.h +++ b/server/encoder/video_encoder.h @@ -43,6 +43,7 @@ inline const char * encoder_nvenc = "nvenc"; inline const char * encoder_vaapi = "vaapi"; inline const char * encoder_x264 = "x264"; inline const char * encoder_vulkan = "vulkan"; +inline const char * encoder_pyrowave = "pyrowave"; class video_encoder { diff --git a/server/encoder/video_encoder_nvenc.cpp b/server/encoder/video_encoder_nvenc.cpp index 3b1e6e4d..58b5092a 100644 --- a/server/encoder/video_encoder_nvenc.cpp +++ b/server/encoder/video_encoder_nvenc.cpp @@ -74,6 +74,8 @@ static auto encode_guid(video_codec codec) return NV_ENC_CODEC_HEVC_GUID; case av1: return NV_ENC_CODEC_AV1_GUID; + case video_codec::pyrowave: + throw std::runtime_error("pyrowave is only supported by the specific encoder"); } throw std::out_of_range("Invalid codec " + std::to_string(codec)); } @@ -164,6 +166,8 @@ video_encoder_nvenc::video_encoder_nvenc( params.encodeCodecConfig.av1Config.maxNumRefFramesInDPB = 0; params.encodeCodecConfig.av1Config.idrPeriod = NVENC_INFINITE_GOPLENGTH; break; + case video_codec::pyrowave: + throw std::runtime_error("pyrowave is only supported by the specific encoder"); } NV_ENC_INITIALIZE_PARAMS params2{ diff --git a/server/encoder/video_encoder_pyrowave.cpp b/server/encoder/video_encoder_pyrowave.cpp new file mode 100644 index 00000000..f9c25b10 --- /dev/null +++ b/server/encoder/video_encoder_pyrowave.cpp @@ -0,0 +1,173 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2025 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 "video_encoder_pyrowave.h" +#include "encoder/encoder_settings.h" +#include "util/u_logging.h" +#include "utils/wivrn_vk_bundle.h" + +#include + +namespace wivrn +{ +video_encoder_pyrowave::video_encoder_pyrowave(wivrn_vk_bundle & vk, encoder_settings & settings, float fps, uint8_t stream_idx) : + video_encoder(stream_idx, settings.channels, 50, true), + enc(vk.physical_device, vk.device, settings.width, settings.height, PyroWave::ChromaSubsampling::Chroma420), + encoded_size(settings.bitrate / fps) +{ + size_t meta_size = enc.get_meta_required_size(); + meta_buf = buffer_allocation( + vk.device, + { + .size = meta_size, + .usage = vk::BufferUsageFlagBits::eStorageBuffer | vk::BufferUsageFlagBits::eTransferSrc, + }, + { + .flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT | VMA_ALLOCATION_CREATE_HOST_ACCESS_ALLOW_TRANSFER_INSTEAD_BIT, + .usage = VMA_MEMORY_USAGE_AUTO, + }, + "pyrowave encoder meta buffer"); + data_buf = buffer_allocation( + vk.device, + { + .size = encoded_size + 2 * meta_size, + .usage = vk::BufferUsageFlagBits::eStorageBuffer | vk::BufferUsageFlagBits::eTransferSrc, + }, + { + .flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT | VMA_ALLOCATION_CREATE_HOST_ACCESS_ALLOW_TRANSFER_INSTEAD_BIT, + .usage = VMA_MEMORY_USAGE_AUTO, + }, + "pyrowave encoder data buffer"); + + if (not(meta_buf.properties() & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT)) + { + meta_buf_staging = buffer_allocation( + vk.device, + { + .size = meta_buf.info().size, + .usage = vk::BufferUsageFlagBits::eTransferDst, + }, + { + .flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT, + .usage = VMA_MEMORY_USAGE_AUTO, + }, + "pyrowave encoder meta staging buffer"); + } + if (not(data_buf.properties() & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT)) + { + data_buf_staging = buffer_allocation( + vk.device, + { + .size = data_buf.info().size, + .usage = vk::BufferUsageFlagBits::eTransferDst, + }, + { + .flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT, + .usage = VMA_MEMORY_USAGE_AUTO, + }, + "pyrowave encoder data staging buffer"); + } +} + +std::pair video_encoder_pyrowave::present_image(vk::Image y_cbcr, vk::raii::CommandBuffer & cmd_buf, uint8_t slot, uint64_t frame_index) +{ + std::array image_view; + + if (auto it = image_views.find(y_cbcr); it != image_views.end()) + { + std::ranges::copy(it->second, image_view.begin()); + } + else + { + auto y = enc.device.createImageView( + vk::ImageViewCreateInfo{ + .image = y_cbcr, + .viewType = vk::ImageViewType::e2D, + .subresourceRange = { + .aspectMask = vk::ImageAspectFlagBits::ePlane0, + .levelCount = 1, + .baseArrayLayer = uint32_t(channels), + .layerCount = 1, + }}); + auto cb = enc.device.createImageView( + vk::ImageViewCreateInfo{ + .image = y_cbcr, + .viewType = vk::ImageViewType::e2D, + .subresourceRange = { + .aspectMask = vk::ImageAspectFlagBits::ePlane1, + .levelCount = 1, + .baseArrayLayer = uint32_t(channels), + .layerCount = 1, + }}); + auto cr = enc.device.createImageView( + vk::ImageViewCreateInfo{ + .image = y_cbcr, + .viewType = vk::ImageViewType::e2D, + .components = { + .r = vk::ComponentSwizzle::eG, + }, + .subresourceRange = { + .aspectMask = vk::ImageAspectFlagBits::ePlane1, + .levelCount = 1, + .baseArrayLayer = uint32_t(channels), + .layerCount = 1, + }}); + + image_view = {y, cb, cr}; + image_views.emplace(y_cbcr, std::array{std::move(y), std::move(cb), std::move(cr)}); + } + PyroWave::Encoder::BitstreamBuffers buffers{ + .meta = { + .buffer = meta_buf, + .size = meta_buf.info().size, + }, + .bitstream = { + .buffer = data_buf, + .size = data_buf.info().size, + }, + .target_size = encoded_size, + }; + if (not enc.encode(cmd_buf, image_view, buffers)) + U_LOG_W("pyrowave encode failed"); + + if (meta_buf_staging) + cmd_buf.copyBuffer(meta_buf, meta_buf_staging, vk::BufferCopy{.size = buffers.meta.size}); + if (data_buf_staging) + cmd_buf.copyBuffer(data_buf, data_buf_staging, vk::BufferCopy{.size = buffers.bitstream.size}); + return {false, nullptr}; +} + +std::optional video_encoder_pyrowave::encode(bool idr, std::chrono::steady_clock::time_point pts, uint8_t slot) +{ + reordered_packet_buffer.resize(8 * 1024 * 1024); + packets.resize(enc.compute_num_packets(meta_buf_staging ? meta_buf_staging.map() : meta_buf.map(), 8 * 1024)); + enc.packetize( + packets.data(), + 8 * 1024, + reordered_packet_buffer.data(), + reordered_packet_buffer.size(), + meta_buf_staging ? meta_buf_staging.map() : meta_buf.map(), + data_buf_staging ? data_buf_staging.map() : data_buf.map()); + for (auto & p: packets) + SendData({reordered_packet_buffer.data() + p.offset, p.size}, &p == &packets.back()); + + return {}; +} + +video_encoder_pyrowave::~video_encoder_pyrowave() {} +} // namespace wivrn diff --git a/server/encoder/video_encoder_pyrowave.h b/server/encoder/video_encoder_pyrowave.h new file mode 100644 index 00000000..ec66accc --- /dev/null +++ b/server/encoder/video_encoder_pyrowave.h @@ -0,0 +1,51 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2025 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.h" + +#include "pyrowave_encoder.h" + +#include +#include + +namespace wivrn +{ +class video_encoder_pyrowave : public video_encoder +{ + PyroWave::Encoder enc; + std::unordered_map> image_views; // for input images + vk::ImageViewCreateInfo image_view_template; + buffer_allocation data_buf, meta_buf; + buffer_allocation data_buf_staging, meta_buf_staging; + size_t encoded_size; + + std::vector reordered_packet_buffer; + std::vector packets; + +public: + video_encoder_pyrowave(wivrn_vk_bundle & vk, encoder_settings & settings, float fps, uint8_t stream_idx); + + std::pair present_image(vk::Image y_cbcr, vk::raii::CommandBuffer & cmd_buf, uint8_t slot, uint64_t frame_index) override; + + std::optional encode(bool idr, std::chrono::steady_clock::time_point pts, uint8_t slot) override; + + ~video_encoder_pyrowave(); +}; +} // namespace wivrn