diff --git a/client/decoder/android/android_decoder.cpp b/client/decoder/android/android_decoder.cpp index f276c348..48fff17c 100644 --- a/client/decoder/android/android_decoder.cpp +++ b/client/decoder/android/android_decoder.cpp @@ -42,6 +42,7 @@ struct wivrn::android::decoder::mapped_hardware_buffer { vk::raii::DeviceMemory memory = nullptr; vk::raii::Image vimage = nullptr; + vk::Extent2D extent{}; vk::raii::ImageView image_view = nullptr; vk::ImageLayout layout = vk::ImageLayout::eUndefined; }; @@ -85,11 +86,12 @@ struct android_blit_handle : public decoder::blit_handle const wivrn::to_headset::video_stream_data_shard::view_info_t & view_info, vk::ImageView image_view, vk::Image image, + vk::Extent2D extent, vk::ImageLayout & current_layout, decltype(vk_data) vk_data, decltype(image_reader) image_reader, decltype(aimage) aimage) : - decoder::blit_handle(feedback, view_info, image_view, image, current_layout), + decoder::blit_handle(feedback, view_info, image_view, image, extent, current_layout), vk_data(vk_data), image_reader(image_reader), aimage(std::move(aimage)) {} @@ -103,19 +105,21 @@ namespace wivrn::android decoder::decoder( vk::raii::Device & device, vk::raii::PhysicalDevice & physical_device, - const wivrn::to_headset::video_stream_description::item & description, - float fps, + const wivrn::to_headset::video_stream_description & description, uint8_t stream_index, std::weak_ptr weak_scene, shard_accumulator * accumulator) : - wivrn::decoder(description), stream_index(stream_index), fps(fps), device(device), weak_scene(weak_scene), accumulator(accumulator) + stream_index(stream_index), device(device), weak_scene(weak_scene), accumulator(accumulator) { spdlog::info("hbm_mutex.native_handle() = {}", (void *)hbm_mutex.native_handle()); + auto width = description.width; + auto height = description.height / (stream_index == 2 ? 2 : 1); + AImageReader * ir; check(AImageReader_newWithUsage( - description.video_width, - description.video_height, + width, + height, AIMAGE_FORMAT_PRIVATE, AHARDWAREBUFFER_USAGE_CPU_READ_NEVER | AHARDWAREBUFFER_USAGE_CPU_WRITE_NEVER | AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE, scenes::stream::image_buffer_size + 4 /* maxImages */, @@ -131,18 +135,18 @@ decoder::decoder( "vkGetAndroidHardwareBufferPropertiesANDROID"); { AMediaFormat_ptr format(AMediaFormat_new()); - AMediaFormat_setString(format.get(), AMEDIAFORMAT_KEY_MIME, mime(description.codec)); + AMediaFormat_setString(format.get(), AMEDIAFORMAT_KEY_MIME, mime(description.codec[stream_index])); // AMediaFormat_setInt32(format.get(), "vendor.qti-ext-dec-low-latency.enable", 1); // Qualcomm low // latency mode - AMediaFormat_setInt32(format.get(), AMEDIAFORMAT_KEY_WIDTH, description.video_width); - AMediaFormat_setInt32(format.get(), AMEDIAFORMAT_KEY_HEIGHT, description.video_height); - AMediaFormat_setInt32(format.get(), AMEDIAFORMAT_KEY_OPERATING_RATE, std::ceil(fps)); + AMediaFormat_setInt32(format.get(), AMEDIAFORMAT_KEY_WIDTH, width); + AMediaFormat_setInt32(format.get(), AMEDIAFORMAT_KEY_HEIGHT, height); + AMediaFormat_setInt32(format.get(), AMEDIAFORMAT_KEY_OPERATING_RATE, std::ceil(description.fps)); AMediaFormat_setInt32(format.get(), AMEDIAFORMAT_KEY_PRIORITY, 0); - media_codec.reset(AMediaCodec_createDecoderByType(mime(description.codec))); + media_codec.reset(AMediaCodec_createDecoderByType(mime(description.codec[stream_index]))); if (not media_codec) - throw std::runtime_error(std::string("Cannot create decoder for MIME type ") + mime(description.codec)); + throw std::runtime_error(std::string("Cannot create decoder for MIME type ") + mime(description.codec[stream_index])); char * codec_name; check(AMediaCodec_getName(media_codec.get(), &codec_name), "AMediaCodec_getName"); @@ -308,6 +312,7 @@ void decoder::on_image_available(AImageReader * reader) info->view_info, *vk_data->image_view, *vk_data->vimage, + vk_data->extent, vk_data->layout, std::move(vk_data), image_reader, @@ -361,11 +366,8 @@ void decoder::create_sampler(const AHardwareBuffer_Desc & buffer_desc, vk::Andro }; // suggested values from decoder don't actually read the metadata, so it's garbage - if (description.range) - ycbcr_create_info.get().ycbcrRange = vk::SamplerYcbcrRange(*description.range); - - if (description.color_model) - ycbcr_create_info.get().ycbcrModel = vk::SamplerYcbcrModelConversion(*description.color_model); + ycbcr_create_info.get().ycbcrRange = vk::SamplerYcbcrRange::eItuFull; + ycbcr_create_info.get().ycbcrModel = vk::SamplerYcbcrModelConversion::eYcbcr709; ycbcr_conversion = vk::raii::SamplerYcbcrConversion(device, ycbcr_create_info.get()); @@ -411,7 +413,6 @@ std::shared_ptr decoder::map_hardware_buffer(AI if (!*ycbcr_sampler || memcmp(&ahb_format, &format_properties, sizeof(format_properties))) { memcpy(&ahb_format, &format_properties, sizeof(format_properties)); - extent_ = {buffer_desc.width, buffer_desc.height}; spdlog::info("decoded image size: {}x{}", buffer_desc.width, buffer_desc.height); create_sampler(buffer_desc, ahb_format); hardware_buffer_map.clear(); @@ -490,6 +491,10 @@ std::shared_ptr decoder::map_hardware_buffer(AI handle->vimage = std::move(vimage); handle->image_view = std::move(image_view); handle->memory = std::move(memory); + handle->extent = vk::Extent2D{ + .width = buffer_desc.width, + .height = buffer_desc.height, + }; hardware_buffer_map[hardware_buffer] = handle; return handle; diff --git a/client/decoder/android/android_decoder.h b/client/decoder/android/android_decoder.h index 3cfa3cb4..97db1412 100644 --- a/client/decoder/android/android_decoder.h +++ b/client/decoder/android/android_decoder.h @@ -67,7 +67,6 @@ public: private: uint8_t stream_index; - float fps; vk::raii::Device & device; @@ -122,8 +121,7 @@ private: public: decoder(vk::raii::Device & device, vk::raii::PhysicalDevice & physical_device, - const wivrn::to_headset::video_stream_description::item & description, - float fps, + const wivrn::to_headset::video_stream_description & description, uint8_t stream_index, std::weak_ptr scene, shard_accumulator * accumulator); diff --git a/client/decoder/decoder.cpp b/client/decoder/decoder.cpp index d92f657f..cb588117 100644 --- a/client/decoder/decoder.cpp +++ b/client/decoder/decoder.cpp @@ -31,13 +31,12 @@ std::shared_ptr wivrn::decoder::make( vk::raii::Device & device, vk::raii::PhysicalDevice & phys_dev, uint32_t vk_queue_family_index, - const wivrn::to_headset::video_stream_description::item & description, - float fps, + const wivrn::to_headset::video_stream_description & description, uint8_t stream_index, std::weak_ptr scene, shard_accumulator * acc) { - switch (description.codec) + switch (description.codec[stream_index]) { case h264: case h265: @@ -47,7 +46,6 @@ std::shared_ptr wivrn::decoder::make( device, phys_dev, description, - fps, stream_index, scene, acc); diff --git a/client/decoder/decoder.h b/client/decoder/decoder.h index da927082..081fdbbd 100644 --- a/client/decoder/decoder.h +++ b/client/decoder/decoder.h @@ -42,25 +42,18 @@ public: wivrn::to_headset::video_stream_data_shard::view_info_t view_info; vk::ImageView image_view = nullptr; vk::Image image = nullptr; + vk::Extent2D extent{}; vk::ImageLayout & current_layout; vk::Semaphore semaphore = nullptr; uint64_t * semaphore_val = nullptr; }; - const wivrn::to_headset::video_stream_description::item description; - -protected: - decoder(const wivrn::to_headset::video_stream_description::item & description) : - description(description) {} - vk::Extent2D extent_; // Must be populated when sampler is set - public: static std::shared_ptr make( vk::raii::Device &, vk::raii::PhysicalDevice &, uint32_t vk_queue_family_index, - const wivrn::to_headset::video_stream_description::item & description, - float fps, + const wivrn::to_headset::video_stream_description & description, uint8_t stream_index, std::weak_ptr, shard_accumulator *); @@ -72,10 +65,6 @@ public: const to_headset::video_stream_data_shard::view_info_t & view_info) = 0; virtual vk::Sampler sampler() = 0; - const vk::Extent2D extent() - { - return extent_; - } static std::vector supported_codecs(); }; diff --git a/client/decoder/ffmpeg/ffmpeg_decoder.cpp b/client/decoder/ffmpeg/ffmpeg_decoder.cpp index 1fddf3f6..0267eee3 100644 --- a/client/decoder/ffmpeg/ffmpeg_decoder.cpp +++ b/client/decoder/ffmpeg/ffmpeg_decoder.cpp @@ -73,6 +73,7 @@ struct decoder::ffmpeg_blit_handle : public wivrn::decoder::blit_handle const wivrn::to_headset::video_stream_data_shard::view_info_t & view_info, vk::ImageView image_view, vk::Image image, + vk::Extent2D extent, vk::ImageLayout & current_layout, int image_index, wivrn::ffmpeg::decoder * self) : @@ -81,6 +82,7 @@ struct decoder::ffmpeg_blit_handle : public wivrn::decoder::blit_handle view_info, image_view, image, + extent, current_layout, }, image_index(image_index), @@ -100,16 +102,19 @@ struct decoder::ffmpeg_blit_handle : public wivrn::decoder::blit_handle decoder::decoder( vk::raii::Device & device, vk::raii::PhysicalDevice & physical_device, - const wivrn::to_headset::video_stream_description::item & description, + const wivrn::to_headset::video_stream_description & description, uint8_t stream_index, std::weak_ptr scene, shard_accumulator * accumulator) : - wivrn::decoder(description), device(device), codec(nullptr, free_codec_context), sws(nullptr, sws_freeContext), weak_scene(scene), - accumulator(accumulator) + accumulator(accumulator), + extent{ + .width = description.width, + .height = description.height / (stream_index == 2 ? 2u : 1u), + } { free_images.resize(image_count); @@ -121,8 +126,8 @@ decoder::decoder( .imageType = vk::ImageType::e2D, .format = vk::Format::eA8B8G8R8SrgbPack32, .extent = { - .width = description.width, - .height = description.height, + .width = extent.width, + .height = extent.height, .depth = 1, }, .mipLevels = 1, @@ -139,7 +144,6 @@ decoder::decoder( decoded_images[i].image = image_allocation(device, image_info, alloc_info); decoded_images[i].image.map(); - extent_ = vk::Extent2D{description.width, description.height}; vk::ImageSubresource resource; resource.aspectMask = vk::ImageAspectFlagBits::eColor; @@ -164,7 +168,7 @@ decoder::decoder( decoded_images[i].current_layout = vk::ImageLayout::eUndefined; } - auto avcodec = avcodec_find_decoder(codec_id(description.codec)); + auto avcodec = avcodec_find_decoder(codec_id(description.codec[stream_index])); if (avcodec == nullptr) { throw std::runtime_error{"avcodec_find_decoder failed"}; @@ -233,7 +237,7 @@ void decoder::frame_completed(const wivrn::from_headset::feedback & feedback, co if (!sws) { - sws.reset(sws_getContext(frame->width, frame->height, (AVPixelFormat)frame->format, description.width, description.height, AV_PIX_FMT_RGB0, SWS_BILINEAR, nullptr, nullptr, nullptr)); + sws.reset(sws_getContext(frame->width, frame->height, (AVPixelFormat)frame->format, extent.width, extent.height, AV_PIX_FMT_RGB0, SWS_BILINEAR, nullptr, nullptr, nullptr)); } std::unique_lock lock(mutex); @@ -259,6 +263,7 @@ void decoder::frame_completed(const wivrn::from_headset::feedback & feedback, co view_info, *decoded_images[index].image_view, decoded_images[index].image, + extent, decoded_images[index].current_layout, index, this); diff --git a/client/decoder/ffmpeg/ffmpeg_decoder.h b/client/decoder/ffmpeg/ffmpeg_decoder.h index 9bc121d5..18e90fbc 100644 --- a/client/decoder/ffmpeg/ffmpeg_decoder.h +++ b/client/decoder/ffmpeg/ffmpeg_decoder.h @@ -73,13 +73,14 @@ private: uint64_t frame_index; std::weak_ptr weak_scene; shard_accumulator * accumulator; + const vk::Extent2D extent; std::mutex mutex; public: decoder(vk::raii::Device & device, vk::raii::PhysicalDevice & physical_device, - const wivrn::to_headset::video_stream_description::item & description, + const wivrn::to_headset::video_stream_description & description, uint8_t stream_index, std::weak_ptr scene, shard_accumulator * accumulator); diff --git a/client/decoder/raw_decoder.cpp b/client/decoder/raw_decoder.cpp index 74c12596..0a712005 100644 --- a/client/decoder/raw_decoder.cpp +++ b/client/decoder/raw_decoder.cpp @@ -32,11 +32,12 @@ struct raw_blit_handle : public wivrn::decoder::blit_handle const wivrn::to_headset::video_stream_data_shard::view_info_t & view_info, vk::ImageView image_view, vk::Image image, + vk::Extent2D extent, vk::ImageLayout & current_layout, vk::Semaphore semaphore, uint64_t & semaphore_val, std::atomic_bool & free) : - wivrn::decoder::blit_handle{feedback, view_info, image_view, image, current_layout, semaphore, &semaphore_val}, + wivrn::decoder::blit_handle{feedback, view_info, image_view, image, extent, current_layout, semaphore, &semaphore_val}, free(free) {} ~raw_blit_handle() { @@ -46,8 +47,7 @@ struct raw_blit_handle : public wivrn::decoder::blit_handle vk::raii::Sampler make_sampler( vk::raii::Device & device, - vk::raii::SamplerYcbcrConversion & ycbcr_conversion, - to_headset::video_stream_description::channels_t channels) + vk::SamplerYcbcrConversion ycbcr_conversion) { vk::StructureChain info{ vk::SamplerCreateInfo{ @@ -60,17 +60,11 @@ vk::raii::Sampler make_sampler( .maxAnisotropy = 1, }, vk::SamplerYcbcrConversionInfo{ - .conversion = *ycbcr_conversion, + .conversion = ycbcr_conversion, }, }; - switch (channels) - { - case wivrn::to_headset::video_stream_description::channels_t::colour: - break; - case wivrn::to_headset::video_stream_description::channels_t::alpha: - info.unlink(); - break; - } + if (ycbcr_conversion == VK_NULL_HANDLE) + info.unlink(); return vk::raii::Sampler(device, info.get()); } } // namespace @@ -81,20 +75,18 @@ raw_decoder::raw_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, + const wivrn::to_headset::video_stream_description & description, uint8_t stream_index, std::weak_ptr scene, shard_accumulator * accumulator) : - decoder(description), device(device), - ycbcr_conversion(device, - { - .format = vk::Format::eG8B8R82Plane420Unorm, - .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_(make_sampler(device, ycbcr_conversion, description.channels)), + ycbcr_conversion(stream_index == 2 ? nullptr : vk::raii::SamplerYcbcrConversion(device, { + .format = vk::Format::eG8B8R82Plane420Unorm, + .ycbcrModel = vk::SamplerYcbcrModelConversion::eYcbcr709, + .ycbcrRange = vk::SamplerYcbcrRange::eItuFull, + .chromaFilter = vk::Filter::eNearest, + })), + sampler_(make_sampler(device, *ycbcr_conversion)), command_pool(device, vk::CommandPoolCreateInfo{ .flags = vk::CommandPoolCreateFlagBits::eResetCommandBuffer, .queueFamilyIndex = vk_queue_family_index, @@ -105,22 +97,24 @@ raw_decoder::raw_decoder( })[0] .release()), fence(device, vk::FenceCreateInfo{.flags = vk::FenceCreateFlagBits::eSignaled}), + stream_index(stream_index), + extent{ + .width = description.width, + .height = description.height / (stream_index == 2 ? 2u : 1u), + }, weak_scene(scene), accumulator(accumulator) { - extent_ = vk::Extent2D{ - .width = description.width, - .height = description.height, - }; - vk::DeviceSize buffer_size = description.width * description.height; + vk::DeviceSize buffer_size = extent.width * extent.height; vk::Format format{}; - switch (description.channels) + switch (stream_index) { - case to_headset::video_stream_description::channels_t::colour: - buffer_size += (description.width * description.height) / 2; + case 0: // colour left + case 1: // colour right + buffer_size += buffer_size / 2; format = vk::Format::eG8B8R82Plane420Unorm; break; - case to_headset::video_stream_description::channels_t::alpha: + case 2: // alpha (monochrome) format = vk::Format::eR8Unorm; break; } @@ -148,8 +142,8 @@ raw_decoder::raw_decoder( .imageType = vk::ImageType::e2D, .format = format, .extent = { - .width = description.width, - .height = description.height, + .width = extent.width, + .height = extent.height, .depth = 1, }, .mipLevels = 1, @@ -220,6 +214,7 @@ void raw_decoder::frame_completed( view_info, *item->view_full, item->image, + extent, item->current_layout, *item->semaphore, item->semaphore_val, @@ -263,20 +258,20 @@ void raw_decoder::frame_completed( .layerCount = 1, }, .imageExtent = { - .width = description.width, - .height = description.height, + .width = extent.width, + .height = extent.height, .depth = 1, }, }, vk::BufferImageCopy{ - .bufferOffset = vk::DeviceSize(description.width * description.height), + .bufferOffset = vk::DeviceSize(extent.width * extent.height), .imageSubresource = { .aspectMask = vk::ImageAspectFlagBits::ePlane1, .layerCount = 1, }, .imageExtent = { - .width = description.width / 2u, - .height = description.height / 2u, + .width = extent.width / 2u, + .height = extent.height / 2u, .depth = 1, }, }, @@ -286,7 +281,7 @@ void raw_decoder::frame_completed( input[0], item->image, item->current_layout, - description.channels == to_headset::video_stream_description::channels_t::colour ? 2 : 1, + stream_index ? 2 : 1, regions.data()); vk::ImageMemoryBarrier barrier{ diff --git a/client/decoder/raw_decoder.h b/client/decoder/raw_decoder.h index 01eb9269..afd04f19 100644 --- a/client/decoder/raw_decoder.h +++ b/client/decoder/raw_decoder.h @@ -48,6 +48,9 @@ private: vk::CommandBuffer cmd; vk::raii::Fence fence; + uint8_t stream_index; + const vk::Extent2D extent; + std::array image_pool; std::weak_ptr weak_scene; @@ -57,13 +60,12 @@ private: std::array input; uint8_t * input_pos; from_headset::feedback feedback; - to_headset::video_stream_data_shard::view_info_t view_info; public: raw_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, + const wivrn::to_headset::video_stream_description & description, uint8_t stream_index, std::weak_ptr scene, shard_accumulator * accumulator); @@ -79,14 +81,6 @@ public: return *sampler_; } - vk::Extent2D image_size() - { - return { - description.width, - description.height, - }; - } - static std::vector supported_codecs(); private: diff --git a/client/decoder/shard_accumulator.cpp b/client/decoder/shard_accumulator.cpp index a7ec0636..aa3d7e33 100644 --- a/client/decoder/shard_accumulator.cpp +++ b/client/decoder/shard_accumulator.cpp @@ -55,7 +55,7 @@ static bool is_complete(const shard_set & shards) const auto & frame = shards.data; if (frame.empty()) return false; - if (not(frame.back() and frame.back()->flags & video_stream_data_shard::end_of_frame)) + if (not(frame.back() and frame.back()->timing_info)) return false; for (const auto & shard: frame) if (not shard) @@ -99,7 +99,7 @@ static void debug_why_not_sent(const shard_set & shards) ++missing; } - bool end = frame.back() and frame.back()->flags & video_stream_data_shard::end_of_frame; + bool end = frame.back() and frame.back()->timing_info; spdlog::info("frame {} was not sent with {} data shards, {}{} missing", frame_idx, data, end ? "" : "at least ", missing); } @@ -185,7 +185,7 @@ void shard_accumulator::try_submit_frame(uint16_t shard_idx) for (size_t idx = shard_idx; idx < last_idx; ++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 = last_idx == data_shards.size() and data_shards.back()->timing_info; 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 6f099534..e3dc7228 100644 --- a/client/decoder/shard_accumulator.h +++ b/client/decoder/shard_accumulator.h @@ -81,11 +81,10 @@ public: vk::raii::PhysicalDevice & physical_device, xr::instance & instance, uint32_t vk_queue_family_index, - const wivrn::to_headset::video_stream_description::item & description, - float fps, + const wivrn::to_headset::video_stream_description & description, std::weak_ptr scene, uint8_t stream_index) : - decoder_(decoder::make(device, physical_device, vk_queue_family_index, description, fps, stream_index, scene, this)), + decoder_(decoder::make(device, physical_device, vk_queue_family_index, description, stream_index, scene, this)), current(stream_index), next(stream_index), weak_scene(scene), @@ -96,21 +95,11 @@ public: void push_shard(wivrn::to_headset::video_stream_data_shard &&); - auto & desc() const - { - return decoder_->description; - } - vk::Sampler sampler() { return decoder_->sampler(); } - const vk::Extent2D extent() - { - return decoder_->extent(); - } - using blit_handle = decoder::blit_handle; private: diff --git a/client/scenes/blitter.cpp b/client/scenes/blitter.cpp deleted file mode 100644 index bab9d0df..00000000 --- a/client/scenes/blitter.cpp +++ /dev/null @@ -1,364 +0,0 @@ -/* - * 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 "blitter.h" - -#include "application.h" -#include "utils/ranges.h" -#include "vk/pipeline.h" -#include "vk/shader.h" -#include "vk/specialization_constants.h" -#include -#include - -namespace wivrn -{ - -static const uint32_t num_views = 2; - -blitter::blitter(vk::raii::Device & device, size_t view) : - device(device), view(view) -{ -} - -void blitter::reset(const to_headset::video_stream_description & desc) -{ - using channels_t = to_headset::video_stream_description::channels_t; - this->desc = desc; - - current = {}; - target = image_allocation(); - image_view = nullptr; - rp = nullptr; - fb = nullptr; - sampler = nullptr; - pipelines.clear(); - passthrough_rgb = passthrough_a = -1; - - auto w = desc.width / num_views; - for (auto [i, item]: utils::enumerate(desc.items)) - { - if (item.offset_x <= view * w and - item.offset_y == 0 and - item.offset_x + item.width * item.subsampling >= (view + 1) * w and - item.height * item.subsampling >= desc.height) - { - spdlog::info("Stream {} is eligible for blit-less path on view {}", i, view); - switch (item.channels) - { - case channels_t::colour: - passthrough_rgb = i; - break; - case channels_t::alpha: - passthrough_a = i; - break; - } - const bool alpha = item.channels == to_headset::video_stream_description::channels_t::alpha; - auto & r = alpha ? current.rect_a : current.rect_rgb; - r = vk::Rect2D{ - .offset = { - .x = int32_t(view * w) - item.offset_x, - .y = 0, - }, - }; - } - } - - if (passthrough_rgb != -1 and passthrough_a != -1) - return; - - target = image_allocation( - device, - vk::ImageCreateInfo{ - .imageType = vk::ImageType::e2D, - .format = vk::Format::eB8G8R8A8Srgb, - .extent = { - .width = w, - .height = desc.height, - .depth = 1, - }, - .mipLevels = 1, - .arrayLayers = 1, - .usage = vk::ImageUsageFlagBits::eSampled | vk::ImageUsageFlagBits::eColorAttachment, - }, - { - .usage = VMA_MEMORY_USAGE_AUTO, - }, - std::format("blit image {}", view)); - - image_view = device.createImageView(vk::ImageViewCreateInfo{ - .image = vk::Image(target), - .viewType = vk::ImageViewType::e2D, - .format = target.info().format, - .subresourceRange = { - .aspectMask = vk::ImageAspectFlagBits::eColor, - .levelCount = 1, - .layerCount = 1, - }}); - - // render pass - { - vk::AttachmentReference color_ref{ - .attachment = 0, - .layout = vk::ImageLayout::eColorAttachmentOptimal, - }; - - vk::SubpassDescription subpass{ - .pipelineBindPoint = vk::PipelineBindPoint::eGraphics, - .colorAttachmentCount = 1, - .pColorAttachments = &color_ref, - }; - - vk::AttachmentDescription color_desc{ - .format = target.info().format, - .loadOp = vk::AttachmentLoadOp::eDontCare, - .finalLayout = vk::ImageLayout::eShaderReadOnlyOptimal, - }; - - rp = device.createRenderPass(vk::RenderPassCreateInfo{ - .attachmentCount = 1, - .pAttachments = &color_desc, - .subpassCount = 1, - .pSubpasses = &subpass, - }); - } - - fb = device.createFramebuffer( - vk::FramebufferCreateInfo{ - .renderPass = *rp, - .attachmentCount = 1, - .pAttachments = &*image_view, - .width = w, - .height = desc.height, - .layers = 1, - }); - - sampler = device.createSampler(vk::SamplerCreateInfo{ - .magFilter = vk::Filter::eLinear, - .minFilter = vk::Filter::eLinear, - .addressModeU = vk::SamplerAddressMode::eClampToBorder, - .addressModeV = vk::SamplerAddressMode::eClampToBorder, - .addressModeW = vk::SamplerAddressMode::eClampToBorder, - .borderColor = vk::BorderColor::eFloatOpaqueBlack, - }); - - pipelines.resize(desc.items.size()); - for (auto [i, item]: utils::enumerate(desc.items)) - { - pipelines[i].used = item.offset_x < (view + 1) * w and - item.offset_x + item.width * item.subsampling > view * w; - } - - current.rgb = *image_view; - current.sampler_rgb = *sampler; - current.rect_rgb = vk::Rect2D{.extent = {w, desc.height}}; - current.layout_rgb = vk::ImageLayout::eShaderReadOnlyOptimal; -} - -void blitter::begin(vk::raii::CommandBuffer & cmd) -{ - assert(not desc.items.empty()); - if (*fb == VK_NULL_HANDLE) - { - current.rgb = nullptr; - current.a = nullptr; - current.sampler_rgb = nullptr; - current.sampler_a = nullptr; - return; - } - - current.rgb = *image_view; - current.sampler_rgb = *sampler; - - cmd.beginRenderPass( - { - .renderPass = *rp, - .framebuffer = *fb, - .renderArea = { - .offset = {0, 0}, - .extent = {target.info().extent.width, target.info().extent.height}, - }, - }, - vk::SubpassContents::eInline); -} - -bool blitter::push_image(vk::raii::CommandBuffer & cmd, uint8_t stream, vk::Sampler sampler, const vk::Extent2D & extent_, vk::ImageView image, vk::ImageLayout layout) -{ - if (stream == passthrough_rgb) - { - current.rgb = image; - current.sampler_rgb = sampler; - current.layout_rgb = layout; - current.rect_rgb.extent = vk::Extent2D{ - extent_.width * desc.items[stream].subsampling, - extent_.height * desc.items[stream].subsampling, - }; - return true; - } - if (stream == passthrough_a) - { - current.a = image; - current.sampler_a = sampler; - current.layout_a = layout; - current.rect_a.extent = vk::Extent2D{ - extent_.width * desc.items[stream].subsampling, - extent_.height * desc.items[stream].subsampling, - }; - return false; - } - if (pipelines.empty()) - return false; - - assert(stream < pipelines.size()); - auto & p = pipelines[stream]; - if (not p.used) - return false; - - const auto & extent = target.info().extent; - const auto & description = desc.items[stream]; - if (not *p.pipeline) - { - const bool alpha = description.channels == to_headset::video_stream_description::channels_t::alpha; - vk::DescriptorSetLayoutBinding sampler_layout_binding{ - .binding = 0, - .descriptorType = vk::DescriptorType::eCombinedImageSampler, - .descriptorCount = 1, - .stageFlags = vk::ShaderStageFlagBits::eFragment, - .pImmutableSamplers = &sampler, - }; - - p.set_layout = device.createDescriptorSetLayout(vk::DescriptorSetLayoutCreateInfo{ - .flags = vk::DescriptorSetLayoutCreateFlagBits::ePushDescriptorKHR, - .bindingCount = 1, - .pBindings = &sampler_layout_binding, - }); - - auto vert_constants = make_specialization_constants( - float(description.width) / extent_.width, - float(description.height) / extent_.height); - - auto frag_constants = make_specialization_constants( - VkBool32(alpha)); - - // Create graphics pipeline - auto vertex_shader = load_shader(device, "stream.vert"); - auto fragment_shader = load_shader(device, "stream.frag"); - - p.layout = device.createPipelineLayout(vk::PipelineLayoutCreateInfo{ - .setLayoutCount = 1, - .pSetLayouts = &*p.set_layout, - }); - - vk::pipeline_builder pipeline_info{ - .Stages = {{ - .stage = vk::ShaderStageFlagBits::eVertex, - .module = *vertex_shader, - .pName = "main", - .pSpecializationInfo = vert_constants, - }, - { - .stage = vk::ShaderStageFlagBits::eFragment, - .module = *fragment_shader, - .pName = "main", - .pSpecializationInfo = frag_constants, - }}, - .VertexBindingDescriptions = {}, - .VertexAttributeDescriptions = {}, - .InputAssemblyState = {{ - .topology = vk::PrimitiveTopology::eTriangleStrip, - }}, - // With vk::DynamicState::eViewport, vk::DynamicState::eScissor the number of viewports - // and scissors is still used, put a vector with one element - .Viewports = {{}}, - .Scissors = {{}}, - .RasterizationState = {{ - .polygonMode = vk::PolygonMode::eFill, - .lineWidth = 1, - }}, - .MultisampleState = {{ - .rasterizationSamples = vk::SampleCountFlagBits::e1, - }}, - .ColorBlendAttachments = { - {.colorWriteMask = alpha ? vk::ColorComponentFlagBits::eA - : vk::ColorComponentFlagBits::eA | vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG | vk::ColorComponentFlagBits::eB}}, - .DynamicStates = {vk::DynamicState::eViewport, vk::DynamicState::eScissor}, - .layout = *p.layout, - .renderPass = *rp, - .subpass = 0, - }; - - p.pipeline = device.createGraphicsPipeline(application::get_pipeline_cache(), pipeline_info); - spdlog::info("Created blit pipeline for stream {}, view {}", stream, view); - } - - cmd.bindPipeline(vk::PipelineBindPoint::eGraphics, *p.pipeline); - - vk::DescriptorImageInfo image_info{ - .imageView = image, - .imageLayout = layout, - }; - cmd.pushDescriptorSetKHR( - vk::PipelineBindPoint::eGraphics, - *p.layout, - 0, - vk::WriteDescriptorSet{ - .dstBinding = 0, - .descriptorCount = 1, - .descriptorType = vk::DescriptorType::eCombinedImageSampler, - .pImageInfo = &image_info, - }); - - int x0 = description.offset_x - view * extent.width; - int y0 = description.offset_y; - int x1 = x0 + description.width * description.subsampling; - int y1 = y0 + description.height * description.subsampling; - - cmd.setViewport( - 0, - vk::Viewport{ - .x = (float)x0, - .y = (float)y0, - .width = float(description.width * description.subsampling), - .height = float(description.height * description.subsampling), - .minDepth = 0, - .maxDepth = 1, - }); - - x0 = std::clamp(x0, 0, extent.width); - x1 = std::clamp(x1, 0, extent.width); - y0 = std::clamp(y0, 0, extent.height); - y1 = std::clamp(y1, 0, extent.height); - - cmd.setScissor( - 0, - vk::Rect2D{ - .offset = {.x = x0, .y = y0}, - .extent = {.width = uint32_t(x1 - x0), .height = uint32_t(y1 - y0)}, - }); - cmd.draw(3, 1, 0, 0); - return true; -} - -blitter::output blitter::end(vk::raii::CommandBuffer & cmd) -{ - if (*fb) - cmd.endRenderPass(); - return current; -} - -} // namespace wivrn diff --git a/client/scenes/blitter.h b/client/scenes/blitter.h deleted file mode 100644 index cd2bea3f..00000000 --- a/client/scenes/blitter.h +++ /dev/null @@ -1,73 +0,0 @@ -/* - * 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 "vk/allocation.h" -#include "wivrn_packets.h" -#include - -namespace wivrn -{ -class blitter -{ -public: - struct output - { - vk::ImageView rgb; - vk::Sampler sampler_rgb; - vk::Rect2D rect_rgb; - vk::ImageLayout layout_rgb; - vk::ImageView a; - vk::Sampler sampler_a; - vk::Rect2D rect_a; - vk::ImageLayout layout_a; - }; - -private: - vk::raii::Device & device; - size_t view; - to_headset::video_stream_description desc; - // indices to simply passthrough, if -1 image needs to be blitted - int passthrough_rgb = -1; - int passthrough_a = -1; - image_allocation target; - vk::raii::ImageView image_view = nullptr; - vk::raii::RenderPass rp = nullptr; - vk::raii::Framebuffer fb = nullptr; - vk::raii::Sampler sampler = nullptr; - struct pipeline_t - { - vk::raii::DescriptorSetLayout set_layout = nullptr; - vk::raii::PipelineLayout layout = nullptr; - vk::raii::Pipeline pipeline = nullptr; - bool used = false; // true if we need this image for blitting - }; - std::vector pipelines; - output current; - -public: - blitter(vk::raii::Device & device, size_t view); - - void reset(const to_headset::video_stream_description & desc); - void begin(vk::raii::CommandBuffer &); - // Return true if the image is used for this blitter's rgb - bool push_image(vk::raii::CommandBuffer & buf, uint8_t stream, vk::Sampler sampler, const vk::Extent2D &, vk::ImageView image, vk::ImageLayout); - output end(vk::raii::CommandBuffer &); -}; -} // namespace wivrn diff --git a/client/scenes/stream.cpp b/client/scenes/stream.cpp index 1d3e6c0b..0cd6a794 100644 --- a/client/scenes/stream.cpp +++ b/client/scenes/stream.cpp @@ -153,8 +153,7 @@ static const std::array supported_depth_formats{ scenes::stream::stream(std::string server_name, scene & parent_scene) : scene_impl(supported_color_formats, supported_depth_formats, parent_scene), - apps{*this, std::move(server_name)}, - blitters{blitter(device, 0), blitter(device, 1)} + apps{*this, std::move(server_name)} { } @@ -488,9 +487,6 @@ void scenes::stream::on_focused() assert(video_stream_description); std::unique_lock lock(decoder_mutex); - setup_reprojection_swapchain( - video_stream_description->defoveated_width / view_count, - video_stream_description->defoveated_height); if (application::get_config().high_power_mode) { @@ -545,9 +541,7 @@ void scenes::stream::push_blit_handle(shard_accumulator * decoder, std::shared_p std::swap(handle, decoders[stream].latest_frames[handle->feedback.frame_index % decoders[stream].latest_frames.size()]); } - if (state_ != state::streaming and std::ranges::all_of(decoders, [](accumulator_images & i) { - return i.alpha() or not i.empty(); - })) + if (state_ != state::streaming and not(decoders[0].empty() and decoders[1].empty())) { state_ = state::streaming; spdlog::info("Stream scene ready at t={}", instance.now()); @@ -560,11 +554,6 @@ void scenes::stream::push_blit_handle(shard_accumulator * decoder, std::shared_p } } -bool scenes::stream::accumulator_images::alpha() const -{ - return decoder->desc().channels == wivrn::to_headset::video_stream_description::channels_t::alpha; -} - bool scenes::stream::accumulator_images::empty() const { for (const auto & frame: latest_frames) @@ -575,7 +564,7 @@ bool scenes::stream::accumulator_images::empty() const return true; } -std::vector> scenes::stream::common_frame(XrTime display_time) +std::array, 3> scenes::stream::common_frame(XrTime display_time) { if (decoders.empty()) return {}; @@ -583,10 +572,8 @@ std::vector> scenes::stream::com thread_local std::vector common_frames; common_frames.clear(); const bool alpha = decoders[0].latest_frames[0] and decoders[0].latest_frames[0]->view_info.alpha; - for (size_t i = 0; i < decoders.size(); ++i) + for (size_t i = 0; i < view_count + alpha; ++i) { - if (decoders[i].alpha() and not alpha) - continue; if (i == 0) { for (const auto & h: decoders[i].latest_frames) @@ -609,8 +596,7 @@ std::vector> scenes::stream::com // clang-format on } } - std::vector> result; - result.reserve(decoders.size()); + std::array, view_count + 1> result; if (not common_frames.empty()) { auto min = std::ranges::min_element(common_frames, @@ -623,12 +609,10 @@ std::vector> scenes::stream::com assert(*min); auto frame_index = (*min)->feedback.frame_index; - for (const auto & decoder: decoders) + for (auto [i, decoder]: utils::enumerate(decoders)) { - if (alpha or not decoder.alpha()) - result.emplace_back(decoder.frame(frame_index)); - else - result.emplace_back(nullptr); + if (alpha or i < view_count) + result[i] = decoder.frame(frame_index); } } else @@ -647,9 +631,9 @@ std::vector> scenes::stream::com spdlog::warn(frames); } - for (const auto & decoder: decoders) + for (auto [i, decoder]: utils::enumerate(decoders)) { - if (alpha or not decoder.alpha()) + if (alpha or i < view_count) { auto min = std::ranges::min_element(decoder.latest_frames, std::ranges::less{}, @@ -658,10 +642,8 @@ std::vector> scenes::stream::com return std::numeric_limits::max(); return std::abs(frame->view_info.display_time - display_time); }); - result.emplace_back(*min); + result[i] = *min; } - else - result.emplace_back(nullptr); } } return result; @@ -768,19 +750,11 @@ void scenes::stream::render(const XrFrameState & frame_state) last_display_time = frame_state.predictedDisplayTime; std::shared_lock lock(decoder_mutex); - if (decoders.empty() or not frame_state.shouldRender) + if (not frame_state.shouldRender or (decoders[0].empty() and decoders[1].empty())) { // TODO: stop/restart video stream session.begin_frame(); session.end_frame(frame_state.predictedDisplayTime, {}); - - std::unique_lock lock(frames_mutex); - for (auto & i: decoders) - { - for (auto & frame: i.latest_frames) - frame.reset(); - } - return; } @@ -796,14 +770,13 @@ void scenes::stream::render(const XrFrameState & frame_state) application::pop_scene(); } - assert(swapchain); if (device.waitForFences(*fence, VK_TRUE, UINT64_MAX) == vk::Result::eTimeout) throw std::runtime_error("Vulkan fence timeout"); device.resetFences(*fence); // We don't need those after vkWaitForFences - current_blit_handles.clear(); + current_blit_handles.fill(nullptr); gpu_timestamps timestamps; if (query_pool_filled) @@ -843,13 +816,15 @@ void scenes::stream::render(const XrFrameState & frame_state) // Search for frame with desired display time on all decoders // If no such frame exists, use the latest frame for each decoder current_blit_handles = common_frame(frame_state.predictedDisplayTime); - std::array pose{}; - std::array fov{}; - std::array foveation{}; + std::array pose; + std::array fov; + std::array foveation; bool use_alpha = false; - for (auto & blit_handle: current_blit_handles) + std::array images; + for (size_t i = 0; i < view_count + use_alpha; ++i) { + auto & blit_handle = current_blit_handles[i]; if (not blit_handle) continue; @@ -879,29 +854,44 @@ void scenes::stream::render(const XrFrameState & frame_state) command_buffer.pipelineBarrier(vk::PipelineStageFlagBits::eAllCommands, vk::PipelineStageFlagBits::eAllCommands, {}, {}, {}, barrier); blit_handle->current_layout = vk::ImageLayout::eGeneral; } - } - // Blit images from the decoders - std::array blitted; - for (auto [i, b]: utils::enumerate(blitters)) - { - b.begin(command_buffer); - for (auto [j, blit_handle]: utils::enumerate(current_blit_handles)) + if (i < view_count) { - if (not blit_handle) - continue; - if (b.push_image(command_buffer, j, decoders[j].decoder->sampler(), decoders[j].decoder->extent(), blit_handle->image_view, blit_handle->current_layout)) + foveation[i] = blit_handle->view_info.foveation[i]; + pose[i] = blit_handle->view_info.pose[i]; + fov[i] = blit_handle->view_info.fov[i]; + // colour image + images[i] = { + .rgb = blit_handle->image_view, + .sampler_rgb = decoders[i].decoder->sampler(), + .rect_rgb = { + .extent = blit_handle->extent, + }, + .layout_rgb = blit_handle->current_layout, + }; + } + else + { + // alpha image, must set for each view + for (int j = 0; j < view_count; ++j) { - pose[i] = blit_handle->view_info.pose[i]; - fov[i] = blit_handle->view_info.fov[i]; - foveation[i] = blit_handle->view_info.foveation[i]; + images[j].a = blit_handle->image_view; + images[j].sampler_a = decoders[i].decoder->sampler(); + images[j].rect_a = vk::Rect2D{ + // in full size pixels + .offset = { + .x = j * video_stream_description->width, + }, + .extent = { + .width = blit_handle->extent.width * 2, + .height = blit_handle->extent.height * 2, + }, + }; + images[j].layout_a = blit_handle->current_layout; } } - blitted[i] = b.end(command_buffer); } - command_buffer.writeTimestamp(vk::PipelineStageFlagBits::eBottomOfPipe, *query_pool, 1); - XrExtent2Di extents[view_count]; { int32_t max_width = 0; @@ -912,9 +902,11 @@ void scenes::stream::render(const XrFrameState & frame_state) max_width = std::max(max_width, extents[i].width); max_height = std::max(max_height, extents[i].height); } - // If the defoveated image is larger than the swapchain, try to reallocate one - if (swapchain.width() < max_width or swapchain.height() < max_height) + if (not swapchain) + setup_reprojection_swapchain(max_width, max_height); + else if (swapchain.width() < max_width or swapchain.height() < max_height) { + // If the defoveated image is larger than the swapchain, try to reallocate one try { spdlog::info("Recreating swapchain, from {}x{} to {}x{}", @@ -935,12 +927,13 @@ void scenes::stream::render(const XrFrameState & frame_state) } } } + assert(swapchain); // defoveate the image int image_index = swapchain.acquire(); swapchain.wait(); - defoveator->defoveate(command_buffer, foveation, blitted, image_index); + defoveator->defoveate(command_buffer, foveation, images, image_index); - command_buffer.writeTimestamp(vk::PipelineStageFlagBits::eBottomOfPipe, *query_pool, 2); + command_buffer.writeTimestamp(vk::PipelineStageFlagBits::eBottomOfPipe, *query_pool, 1); command_buffer.end(); vk::SubmitInfo submit_info; @@ -1133,37 +1126,25 @@ void scenes::stream::setup(const to_headset::video_stream_description & descript { session.set_refresh_rate(description.fps); + spdlog::info("Creating decoders, size {}x{}", description.width, description.height); std::unique_lock lock(decoder_mutex); - decoders.clear(); - - if (description.items.empty()) - { - spdlog::info("Stopping video stream"); - return; - } - video_stream_description = description; - for (auto & b: blitters) - b.reset(description); - for (const auto & [stream_index, item]: utils::enumerate(description.items)) + for (const auto & [stream_index, item]: utils::enumerate(decoders)) { - 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, queue_family_index, item, description.fps, shared_from_this(), stream_index), - }); + item = accumulator_images{ + .decoder = std::make_unique(device, physical_device, instance, queue_family_index, description, shared_from_this(), stream_index), + }; } } void scenes::stream::setup_reprojection_swapchain(uint32_t swapchain_width, uint32_t swapchain_height) { + assert(swapchain_width); + assert(swapchain_height); device.waitIdle(); session.set_refresh_rate(video_stream_description->fps); - const uint32_t video_width = video_stream_description->width / view_count; - const uint32_t video_height = video_stream_description->height; - auto views = system.view_configuration_views(viewconfig); swapchain = xr::swapchain(instance, session, device, swapchain_format, swapchain_width, swapchain_height, 1, views.size()); diff --git a/client/scenes/stream.h b/client/scenes/stream.h index 17a0e21a..a93e0288 100644 --- a/client/scenes/stream.h +++ b/client/scenes/stream.h @@ -24,7 +24,6 @@ #include "decoder/shard_accumulator.h" #include "render/imgui_impl.h" #include "scene.h" -#include "scenes/blitter.h" #include "scenes/input_profile.h" #include "stream_defoveator.h" #include "utils/thread_safe.h" @@ -55,8 +54,6 @@ public: private: static const size_t view_count = 2; - using stream_description = wivrn::to_headset::video_stream_description::item; - struct accumulator_images { std::unique_ptr decoder; @@ -64,7 +61,6 @@ private: std::array, image_buffer_size> latest_frames; std::shared_ptr frame(uint64_t id) const; - bool alpha() const; bool empty() const; }; @@ -72,7 +68,7 @@ private: // for frames inside accumulator images std::mutex frames_mutex; - std::vector> common_frame(XrTime display_time); + std::array, view_count + 1> common_frame(XrTime display_time); std::unique_ptr network_session; std::atomic exiting = false; @@ -90,9 +86,7 @@ private: std::shared_mutex decoder_mutex; std::optional video_stream_description; - std::vector decoders; // Locked by decoder_mutex - - std::array blitters; + std::array decoders; // Locked by decoder_mutex std::optional defoveator; @@ -168,7 +162,7 @@ private: void update_gui_position(xr::spaces controller); // Keep a reference to the resources needed to blit the images until vkWaitForFences - std::vector> current_blit_handles; + std::array, view_count + 1> current_blit_handles; XrTime running_application_req = 0; thread_safe running_applications; @@ -257,13 +251,11 @@ private: struct gpu_timestamps { - float gpu_barrier = 0; float gpu_time = 0; }; - struct global_metric //: gpu_timestamps + struct global_metric { - float gpu_barrier; float gpu_time; float cpu_time = 0; float bandwidth_rx = 0; @@ -312,7 +304,7 @@ private: float compact_cpu_time = 0; float compact_gpu_time = 0; - void accumulate_metrics(XrTime predicted_display_time, const std::vector> & blit_handles, const gpu_timestamps & timestamps); + void accumulate_metrics(XrTime predicted_display_time, const std::array, view_count + 1> & blit_handles, const gpu_timestamps & timestamps); void gui_performance_metrics(); void gui_compact_view(); void gui_settings(float predicted_display_period); diff --git a/client/scenes/stream_defoveator.cpp b/client/scenes/stream_defoveator.cpp index 5e321e8b..8293a3f7 100644 --- a/client/scenes/stream_defoveator.cpp +++ b/client/scenes/stream_defoveator.cpp @@ -295,7 +295,7 @@ static size_t required_vertices(const wivrn::to_headset::foveation_parameter & p void stream_defoveator::defoveate(vk::raii::CommandBuffer & command_buffer, const std::array & foveation, - std::span inputs, + const std::array & inputs, int destination) { if (destination < 0 || destination >= (int)output_images.size()) diff --git a/client/scenes/stream_defoveator.h b/client/scenes/stream_defoveator.h index ba2a2e62..6b106564 100644 --- a/client/scenes/stream_defoveator.h +++ b/client/scenes/stream_defoveator.h @@ -19,7 +19,6 @@ #pragma once -#include "blitter.h" #include "vk/allocation.h" #include "wivrn_packets.h" #include @@ -61,6 +60,18 @@ class stream_defoveator pipeline_t & ensure_pipeline(size_t view, vk::Sampler rgb, vk::Sampler a); public: + struct input + { + vk::ImageView rgb; + vk::Sampler sampler_rgb; + vk::Rect2D rect_rgb; + vk::ImageLayout layout_rgb; + vk::ImageView a; + vk::Sampler sampler_a; + vk::Rect2D rect_a; + vk::ImageLayout layout_a; + }; + stream_defoveator( vk::raii::Device & device, vk::raii::PhysicalDevice & physical_device, @@ -73,7 +84,7 @@ public: void defoveate( vk::raii::CommandBuffer & command_buffer, const std::array & foveation, - std::span inputs, + const std::array & inputs, int destination); XrExtent2Di defoveated_size(const wivrn::to_headset::foveation_parameter &) const; diff --git a/client/scenes/stream_gui.cpp b/client/scenes/stream_gui.cpp index a1655844..9060b0c5 100644 --- a/client/scenes/stream_gui.cpp +++ b/client/scenes/stream_gui.cpp @@ -86,7 +86,7 @@ ImPlotPoint getter(int index, void * data_) } } // namespace -void scenes::stream::accumulate_metrics(XrTime predicted_display_time, const std::vector> & blit_handles, const gpu_timestamps & timestamps) +void scenes::stream::accumulate_metrics(XrTime predicted_display_time, const std::array, view_count + 1> & blit_handles, const gpu_timestamps & timestamps) { uint64_t rx = network_session->bytes_received(); uint64_t tx = network_session->bytes_sent(); @@ -171,8 +171,7 @@ void scenes::stream::gui_performance_metrics() // clang-format off plot(_("CPU time"), {{"", &global_metric::cpu_time}}, "s"), - plot(_("GPU time"), {{_("Reproject"), &global_metric::gpu_time}, - {_("Blit"), &global_metric::gpu_barrier}}, "s"), + plot(_("GPU time"), {{_("Defoveate"), &global_metric::gpu_time}}, "s"), plot(_("Network"), {{_("Download"), &global_metric::bandwidth_rx}, {_("Upload"), &global_metric::bandwidth_tx}}, "bit/s"), diff --git a/client/shaders/stream.glsl b/client/shaders/stream.glsl deleted file mode 100644 index c07b0953..00000000 --- a/client/shaders/stream.glsl +++ /dev/null @@ -1,63 +0,0 @@ -/* - * WiVRn VR streaming - * Copyright (C) 2022 Guillaume Meunier - * Copyright (C) 2022 Patrick Nicolas - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -#version 450 - -#ifdef VERT_SHADER - -layout(constant_id = 0) const float useful_size_x = 1.0; -layout(constant_id = 1) const float useful_size_y = 1.0; - -vec2 positions[3] = vec2[]( - vec2(-1.0, -1.0), - vec2(3.0, -1.0), - vec2(-1.0, 3.0)); - -vec2 uvs[3] = vec2[]( - vec2(0.0, 0.0), - vec2(2.0 * useful_size_x, 0.0), - vec2(0.0, 2.0 * useful_size_y)); - -layout(location = 0) out vec2 outUV; - -void main() -{ - outUV = uvs[gl_VertexIndex]; - gl_Position = vec4(positions[gl_VertexIndex], 0.0, 1.0); -} -#endif - -#ifdef FRAG_SHADER -layout(binding = 0) uniform sampler2D texSampler; -layout(constant_id = 0) const bool is_alpha = false; - -layout(location = 0) in vec2 inUV; - -layout(location = 0) out vec4 outColor; - -void main() -{ - outColor = texture(texSampler, inUV); - outColor.a = outColor.r; - if (!is_alpha) - { - outColor.a = 1; - } -} -#endif diff --git a/common/wivrn_packets.h b/common/wivrn_packets.h index a27cdc27..4b7582d6 100644 --- a/common/wivrn_packets.h +++ b/common/wivrn_packets.h @@ -636,52 +636,27 @@ struct audio_stream_description struct video_stream_description { - enum class channels_t - { - colour, - alpha, - }; - struct item - { - // useful dimensions of the video stream - uint16_t width; - uint16_t height; - // dimensions of the video, may include padding at the end - uint16_t video_width; - uint16_t video_height; - uint16_t offset_x; - uint16_t offset_y; - video_codec codec; - channels_t channels; - uint8_t subsampling; // applies to width/height only, offsets are in full size pixels - std::optional range; - std::optional color_model; - }; + // dimensions of the video stream per eye + // alpha is half resolution uint16_t width; uint16_t height; + std::array codec; // left, right, alpha float fps; - uint16_t defoveated_width; - uint16_t defoveated_height; - std::vector items; }; class video_stream_data_shard { public: inline static const size_t max_payload_size = 1400; - enum flags : uint8_t - { - start_of_slice = 1, - end_of_slice = 1 << 1, - end_of_frame = 1 << 2, - }; - // Identifier of stream in video_stream_description + // Identifier of stream: + // 0 left + // 1 right + // 2 alpha uint8_t stream_item_idx; // Counter increased for each frame uint64_t frame_idx; // Identifier of the shard within the frame uint16_t shard_idx; - uint8_t flags; // Position information, must be present on first video shard struct view_info_t diff --git a/dashboard/settings.cpp b/dashboard/settings.cpp index 8b6abacd..9070d5c9 100644 --- a/dashboard/settings.cpp +++ b/dashboard/settings.cpp @@ -147,11 +147,11 @@ void Settings::load(const wivrn_server * server) bool Settings::simpleConfig() const { - // Simple configuration: either unset, or all encoders + codecs are the same + // Simple configuration: either unset, single encoder or all encoders + codecs are the same try { - auto it = m_jsonSettings.find("encoders"); - if (it == m_jsonSettings.end()) + auto it = m_jsonSettings.find("encoder"); + if (it == m_jsonSettings.end() or it->is_object()) return true; std::optional encoder; std::optional codec; @@ -193,13 +193,15 @@ Settings::encoder_name Settings::encoder() const { try { - auto it = m_jsonSettings.find("encoders"); + auto it = m_jsonSettings.find("encoder"); if (it == m_jsonSettings.end()) return encoder_name::EncoderAuto; - for (const auto & item: *it) + if (it->is_array() and it->size()) + it = it->begin(); + if (it->is_object()) { - if (auto it = item.find("encoder"); it != item.end()) - return encoder_id_from_string(std::string(*it)); + if (auto e = it->find("encoder"); e != it->end()) + return encoder_id_from_string(std::string(*e)); return encoder_name::EncoderAuto; } } @@ -216,30 +218,15 @@ void Settings::set_encoder(const encoder_name & value) switch (value) { case EncoderAuto: - m_jsonSettings.erase("encoders"); + m_jsonSettings.erase("encoder"); break; case Nvenc: case Vaapi: - case Vulkan: { - auto & enc = m_jsonSettings["encoders"] = nlohmann::json::array(); - for (float offset: {0.f, 0.5f}) - { - auto obj = nlohmann::json::object({ - {"width", 0.5}, - {"encoder", encoder_from_id(value)}, - }); - if (offset) - obj["offset_x"] = offset; - if (value == Vulkan) - obj["codec"] = "h264"; - enc.push_back(obj); - } - } - break; - case encoder_name::X264: - m_jsonSettings["encoders"] = - nlohmann::json::parse(R"([{"encoder": "x264", "codec": "h264"}])"); - break; + case X264: + case Vulkan: + m_jsonSettings["encoder"] = nlohmann::json::object({ + {"encoder", encoder_from_id(value)}, + }); } if (value != old) { @@ -256,13 +243,15 @@ Settings::video_codec Settings::codec() const { try { - auto it = m_jsonSettings.find("encoders"); + auto it = m_jsonSettings.find("encoder"); if (it == m_jsonSettings.end()) return video_codec::CodecAuto; - for (const auto & item: *it) + if (it->is_array() and it->size()) + it = it->begin(); + if (it->is_object()) { - if (auto it = item.find("codec"); it != item.end()) - return codec_id_from_string(std::string(*it)); + if (auto c = it->find("codec"); c != it->end()) + return codec_id_from_string(std::string(*c)); return video_codec::CodecAuto; } } @@ -275,17 +264,28 @@ Settings::video_codec Settings::codec() const void Settings::set_codec(const video_codec & value) { auto old = codec(); - auto it = m_jsonSettings.find("encoders"); - if (it == m_jsonSettings.end() or not it->is_array()) + auto it = m_jsonSettings.find("encoder"); + if (it == m_jsonSettings.end()) return; - for (auto & item: *it) + + if (it->is_object()) { - if (not item.is_object()) - continue; if (value == CodecAuto) - item.erase("codec"); + it->erase("codec"); else - item["codec"] = codec_from_id(value); + (*it)["codec"] = codec_from_id(value); + } + else if (it->is_array()) + { + for (auto & item: *it) + { + if (not item.is_object()) + continue; + if (value == CodecAuto) + item.erase("codec"); + else + item["codec"] = codec_from_id(value); + } } if (value != old) { @@ -520,8 +520,7 @@ void Settings::save(wivrn_server * server) void Settings::restore_defaults() { - m_jsonSettings.erase("encoders"); - m_jsonSettings.erase("encoder-passthrough"); + m_jsonSettings.erase("encoder"); m_jsonSettings.erase("scale"); m_jsonSettings.erase("bitrate"); m_jsonSettings.erase("application"); diff --git a/docs/configuration.md b/docs/configuration.md index 4d737512..c1f9fa2b 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -43,12 +43,10 @@ Default value: `8` (bits) Bit depth of the video. 8-bit is supported by all encoders. 10-bit is supported by `vaapi` and `nvenc` encoders using `h265` or `av1`. -## `encoders` -A list of encoders to use. +## `encoder` +The encoder to use, either a single object applied to all streams, or a list of objects with values for left, right and alpha. -Default value: one encoder per eye - -WiVRn has the ability to split the video in blocks that are processed independently, this may use resources more effectively and reduce latency. +WiVRn encodes each eye separately, and the alpha channel as one for both eyes. Each stream is processed independently, this may use resources more effectively and reduce latency. All the provided encoders are put into groups, groups are executed concurrently and items within a group are processed sequentially. ### `encoder` @@ -73,31 +71,24 @@ Not all encoders support every codec: If `nvenc` encoder is in use, you can refer to [nvidia website](https://developer.nvidia.com/video-encode-decode-support-matrix) to make sure that your GPU supports encoding with the desired codec. -### `width`, `height`, `offset_x`, `offset_y` (advanced) -Default values: full image (`width` = 1, `height` = 1, `offset_x` = 0, `offset_y` = 0) - -Specifies the portion of the video to encode: all values are in 0, 1 range. Left eye image ranges from x 0 to x 0.5 and y 0 to 1, Rigth eye is x from 0.5 to 1 and y 0 to 1. - -### `group` (very advanced) +### `group` (advanced) Default value: One value for each encoder type (nvenc, vaapi, vulkan, x264). Identifier (number) of the encoder group. Encoders with the same identifier are executed sequentially, in the order they are defined in the configuration. Encoders with different identifiers are executed concurrently. Default setting will have all encoders of a given type execute sequentially, and different types in parallel. ### Examples -1. Simple encoder +1. Simple configuration ```json { "bitrate": 50000000, - "encoders": [ - { - "encoder": "vaapi", - "codec": "h265" - } - ] + "encoder": { + "encoder": "vaapi", + "codec": "h265" + } } ``` -Creates a single encoder, using vaapi hardware encoding, h265 video codec (HEVC) and 50Mb/s bitrate. +Use vaapi hardware encoding, h265 video codec (HEVC) and 50Mb/s bitrate. 2. Hardware + software encoder ```json @@ -107,52 +98,19 @@ Creates a single encoder, using vaapi hardware encoding, h265 video codec (HEVC) { "encoder": "vaapi", "codec": "h265", - "width": 0.5, - "height": 1, - "offset_x": 0, - "offset_y": 0 }, { "encoder": "x264", "codec": "h264", - "width": 0.5, - "height": 1, - "offset_x": 0.5, - "offset_y": 0 - } - ] -} -``` -Creates a hardware encoder for left eye, and a software encoder for right eye. - -3. 2 Hardware encoders -```json -{ - "bitrate": 50000000, - "encoders": [ - { - "encoder": "vaapi", - "codec": "h265", - "width": 0.5, - "height": 1, - "offset_x": 0, - "offset_y": 0, - "group": 0 }, { "encoder": "vaapi", - "codec": "h264", - "width": 0.5, - "height": 1, - "offset_x": 0.5, - "offset_y": 0, - "group": 0 - } + "codec": "h265", + }, ] } ``` -Creates two hardware encoders, one for left eye and one for right eye, executed sequentially as they have the same `group`. -This allows the left eye image to be encoded faster than the full image would be, so network transfer starts earlier, and decoding starts earlier. While the total encoding, transfer and decoding time remain the same or are longer, this can reduce the latency. +Creates a hardware encoder for left eye and transparency, and a software encoder for right eye. ### `device`, only for vaapi Default value: unset @@ -165,11 +123,6 @@ Default value: unset Json object of additional options to pass directly to ffmpeg `avcodec_open2`'s `option` parameter. -## `encoder-passthrough` - -The single encoder used for passthrough (transparency), contains the same elements as the other encoders, except for width/height and offsets which are ignored. -Default values are those computed for the first encoder. - ## `application` Default value: unset diff --git a/patches/monado/0001-c-multi-early-wake-of-compositor.patch b/patches/monado/0001-c-multi-early-wake-of-compositor.patch index 040e330b..c3d3e8f1 100644 --- a/patches/monado/0001-c-multi-early-wake-of-compositor.patch +++ b/patches/monado/0001-c-multi-early-wake-of-compositor.patch @@ -1,7 +1,7 @@ -From 253c8071648498da89536556db9154e3941b4d41 Mon Sep 17 00:00:00 2001 +From 4dc055eccff32e27da9e332ab6f380eb199d9e2c Mon Sep 17 00:00:00 2001 From: Patrick Nicolas Date: Tue, 22 Oct 2024 15:23:19 +0200 -Subject: [PATCH 1/6] c/multi: early wake of compositor +Subject: [PATCH 1/7] c/multi: early wake of compositor --- .../compositor/multi/comp_multi_compositor.c | 14 +++++++++ @@ -51,7 +51,7 @@ index 3351defa4..e8f0c8295 100644 { int64_t predicted_display_time_ns; diff --git a/src/xrt/compositor/multi/comp_multi_system.c b/src/xrt/compositor/multi/comp_multi_system.c -index 199025a13..35ca4aa29 100644 +index 4db923457..80cbbbc26 100644 --- a/src/xrt/compositor/multi/comp_multi_system.c +++ b/src/xrt/compositor/multi/comp_multi_system.c @@ -24,6 +24,8 @@ @@ -93,7 +93,7 @@ index 199025a13..35ca4aa29 100644 } static void -@@ -529,10 +538,13 @@ multi_main_loop(struct multi_system_compositor *msc) +@@ -530,10 +539,13 @@ multi_main_loop(struct multi_system_compositor *msc) broadcast_timings_to_clients(msc, predicted_display_time_ns); // Now we can wait. @@ -109,7 +109,7 @@ index 199025a13..35ca4aa29 100644 // Now we know the diff, broadcast to pacers. broadcast_timings_to_pacers(msc, predicted_display_time_ns, predicted_display_period_ns, diff_ns); -@@ -718,6 +730,8 @@ system_compositor_destroy(struct xrt_system_compositor *xsc) +@@ -721,6 +733,8 @@ system_compositor_destroy(struct xrt_system_compositor *xsc) xrt_comp_native_destroy(&msc->xcn); os_mutex_destroy(&msc->list_and_timing_lock); @@ -118,7 +118,7 @@ index 199025a13..35ca4aa29 100644 free(msc); } -@@ -772,6 +786,8 @@ comp_multi_create_system_compositor(struct xrt_compositor_native *xcn, +@@ -775,6 +789,8 @@ comp_multi_create_system_compositor(struct xrt_compositor_native *xcn, msc->sessions.state = do_warm_start ? MULTI_SYSTEM_STATE_INIT_WARM_START : MULTI_SYSTEM_STATE_STOPPED; os_mutex_init(&msc->list_and_timing_lock); diff --git a/patches/monado/0002-Use-extern-socket-fd.patch b/patches/monado/0002-Use-extern-socket-fd.patch index 1cf19e7e..67477a15 100644 --- a/patches/monado/0002-Use-extern-socket-fd.patch +++ b/patches/monado/0002-Use-extern-socket-fd.patch @@ -1,7 +1,7 @@ -From 543a4b3aefdbfab45a881129e539bb57fa43646e Mon Sep 17 00:00:00 2001 +From 99c1547e6cc41db4c55c72892b46878a22b4c3a9 Mon Sep 17 00:00:00 2001 From: Patrick Nicolas Date: Tue, 8 Oct 2024 22:13:15 +0200 -Subject: [PATCH 2/6] Use extern socket fd +Subject: [PATCH 2/7] Use extern socket fd --- src/xrt/ipc/server/ipc_server_mainloop_linux.c | 8 ++++++++ diff --git a/patches/monado/0003-change-environment-blend-mode-selection-logic.patch b/patches/monado/0003-change-environment-blend-mode-selection-logic.patch index a9d006d7..39ea52c9 100644 --- a/patches/monado/0003-change-environment-blend-mode-selection-logic.patch +++ b/patches/monado/0003-change-environment-blend-mode-selection-logic.patch @@ -1,14 +1,14 @@ -From a2dd5416fea5e97931b91dddf82b4431d8908939 Mon Sep 17 00:00:00 2001 +From 92dae610f58935a3db4ff46d0fcf9cf18cd10e21 Mon Sep 17 00:00:00 2001 From: galister <85970-galister@users.noreply.gitlab.freedesktop.org> Date: Sat, 23 Nov 2024 02:42:12 +0900 -Subject: [PATCH 3/6] change environment blend mode selection logic +Subject: [PATCH 3/7] change environment blend mode selection logic --- src/xrt/compositor/multi/comp_multi_system.c | 26 +++++++++++++------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/src/xrt/compositor/multi/comp_multi_system.c b/src/xrt/compositor/multi/comp_multi_system.c -index 35ca4aa29..1d162a45d 100644 +index 80cbbbc26..4a397d7ec 100644 --- a/src/xrt/compositor/multi/comp_multi_system.c +++ b/src/xrt/compositor/multi/comp_multi_system.c @@ -233,23 +233,31 @@ find_active_blend_mode(struct multi_compositor **overlay_sorted_clients, size_t diff --git a/patches/monado/0004-st-oxr-forward-0-refresh-rate.patch b/patches/monado/0004-st-oxr-forward-0-refresh-rate.patch index b778a607..056ecec3 100644 --- a/patches/monado/0004-st-oxr-forward-0-refresh-rate.patch +++ b/patches/monado/0004-st-oxr-forward-0-refresh-rate.patch @@ -1,7 +1,7 @@ -From 58d2c3f51a6c1b4fcad4c5e23c267931e0ef5580 Mon Sep 17 00:00:00 2001 +From 5f278ee8a2234bb7a8463b8c028ffd9454cbe30a Mon Sep 17 00:00:00 2001 From: Patrick Nicolas Date: Sat, 15 Mar 2025 22:19:48 +0100 -Subject: [PATCH 4/6] st/oxr: forward 0 refresh rate +Subject: [PATCH 4/7] st/oxr: forward 0 refresh rate --- src/xrt/compositor/main/comp_compositor.c | 2 +- diff --git a/patches/monado/0005-Replace-distortion-with-foveation.patch b/patches/monado/0005-Replace-distortion-with-foveation.patch index b6860c0f..54bbabab 100644 --- a/patches/monado/0005-Replace-distortion-with-foveation.patch +++ b/patches/monado/0005-Replace-distortion-with-foveation.patch @@ -1,7 +1,7 @@ -From ddae46a3ef27f71172be70de4bdf99be7d65ee36 Mon Sep 17 00:00:00 2001 +From 8d3fb92d6436b0111185682d7e99b7d2ec040724 Mon Sep 17 00:00:00 2001 From: Patrick Nicolas Date: Wed, 11 Sep 2024 22:56:29 +0200 -Subject: [PATCH 5/6] Replace distortion with foveation +Subject: [PATCH 5/7] Replace distortion with foveation --- src/xrt/compositor/CMakeLists.txt | 4 +- @@ -11,15 +11,15 @@ Subject: [PATCH 5/6] Replace distortion with foveation src/xrt/compositor/render/render_interface.h | 95 ++-- src/xrt/compositor/render/render_resources.c | 106 ++--- src/xrt/compositor/shaders/clear.comp | 4 +- - src/xrt/compositor/shaders/distortion.comp | 180 ++++---- + src/xrt/compositor/shaders/distortion.comp | 182 ++++---- .../compositor/util/comp_high_level_render.c | 6 +- .../compositor/util/comp_high_level_render.h | 9 +- src/xrt/compositor/util/comp_render.h | 11 +- src/xrt/compositor/util/comp_render_cs.c | 112 ++--- - 12 files changed, 354 insertions(+), 592 deletions(-) + 12 files changed, 356 insertions(+), 592 deletions(-) diff --git a/src/xrt/compositor/CMakeLists.txt b/src/xrt/compositor/CMakeLists.txt -index 1ba5ec438..eb068f5fc 100644 +index 1ba5ec438..7435a9ce3 100644 --- a/src/xrt/compositor/CMakeLists.txt +++ b/src/xrt/compositor/CMakeLists.txt @@ -105,7 +105,7 @@ if(XRT_HAVE_VULKAN) @@ -41,10 +41,10 @@ index 1ba5ec438..eb068f5fc 100644 render/render_interface.h render/render_resources.c diff --git a/src/xrt/compositor/main/comp_renderer.c b/src/xrt/compositor/main/comp_renderer.c -index 51a14e9fc..2cbdc5e68 100644 +index 16c16fd7a..40b219cef 100644 --- a/src/xrt/compositor/main/comp_renderer.c +++ b/src/xrt/compositor/main/comp_renderer.c -@@ -991,7 +991,8 @@ dispatch_compute(struct comp_renderer *r, +@@ -1005,7 +1005,8 @@ dispatch_compute(struct comp_renderer *r, // Target Vulkan resources.. VkImage target_image = r->c->target->images[r->acquired_buffer].handle; @@ -54,7 +54,7 @@ index 51a14e9fc..2cbdc5e68 100644 // Target view information. struct render_viewport_data target_viewport_datas[XRT_MAX_VIEWS]; -@@ -1008,7 +1009,8 @@ dispatch_compute(struct comp_renderer *r, +@@ -1022,7 +1023,8 @@ dispatch_compute(struct comp_renderer *r, eye_poses, // fovs, // target_image, // @@ -1094,10 +1094,10 @@ index 1f0e732b8..e02307415 100644 + imageStore(target, ivec3(offset.x + ix, offset.y + iy, 0), colour); } diff --git a/src/xrt/compositor/shaders/distortion.comp b/src/xrt/compositor/shaders/distortion.comp -index 0b28d8bf3..41de849e6 100644 +index 0b28d8bf3..df2b612b0 100644 --- a/src/xrt/compositor/shaders/distortion.comp +++ b/src/xrt/compositor/shaders/distortion.comp -@@ -4,136 +4,104 @@ +@@ -4,136 +4,106 @@ #version 460 #extension GL_GOOGLE_include_directive : require @@ -1171,17 +1171,6 @@ index 0b28d8bf3..41de849e6 100644 -} - -vec2 transform_uv_subimage(vec2 uv, uint iz) --{ -- vec2 values = uv; -- -- // To deal with OpenGL flip and sub image view. -- values.xy = values.xy * ubo.post_transform[iz].zw + ubo.post_transform[iz].xy; -- -- // Ready to be used. -- return values.xy; --} -- --vec2 transform_uv_timewarp(vec2 uv, uint iz) + mat4 transform[2]; +} ubo; +layout(set = 0, binding = 4) uniform writeonly restrict image2DArray chroma; @@ -1196,6 +1185,17 @@ index 0b28d8bf3..41de849e6 100644 + +vec3 rgb_to_ycbcr(vec3 color) { +- vec2 values = uv; +- +- // To deal with OpenGL flip and sub image view. +- values.xy = values.xy * ubo.post_transform[iz].zw + ubo.post_transform[iz].xy; +- +- // Ready to be used. +- return values.xy; +-} +- +-vec2 transform_uv_timewarp(vec2 uv, uint iz) +-{ - vec4 values = vec4(uv, -1, 1); - - // From uv to tan angle (tangent space). @@ -1231,7 +1231,7 @@ index 0b28d8bf3..41de849e6 100644 uint iz = gl_GlobalInvocationID.z; ivec2 offset = ivec2(ubo.views[iz].xy); - ivec2 extent = ivec2(ubo.views[iz].zw); +- ivec2 extent = ivec2(ubo.views[iz].zw); - - if (ix >= extent.x || iy >= extent.y) { + uint iy = gl_GlobalInvocationID.y; @@ -1252,27 +1252,24 @@ index 0b28d8bf3..41de849e6 100644 - vec2 r_uv = texture(distortion[iz + 0], dist_uv).xy; - vec2 g_uv = texture(distortion[iz + 2], dist_uv).xy; - vec2 b_uv = texture(distortion[iz + 4], dist_uv).xy; -- -- // Do any transformation needed. -- r_uv = transform_uv(r_uv, iz); -- g_uv = transform_uv(g_uv, iz); -- b_uv = transform_uv(b_uv, iz); + uint xmin = foveation.x[MAX_DIM * iz + ix]; + uint xmax = foveation.x[MAX_DIM * iz + ix + 1]; + if (xmin == xmax) + return; +- // Do any transformation needed. +- r_uv = transform_uv(r_uv, iz); +- g_uv = transform_uv(g_uv, iz); +- b_uv = transform_uv(b_uv, iz); ++ uint xstep = (xmax - xmin + MAX_SAMPLES - 1) / MAX_SAMPLES; ++ uint ystep = (ymax - ymin + MAX_SAMPLES - 1) / MAX_SAMPLES; + - // Sample the source with distorted and chromatic-aberration corrected samples. - vec4 colour = vec4( // - texture(source[iz], r_uv).r, // - texture(source[iz], g_uv).g, // - texture(source[iz], b_uv).b, // - 1); // -+ uint xstep = (xmax - xmin + MAX_SAMPLES - 1) / MAX_SAMPLES; -+ uint ystep = (ymax - ymin + MAX_SAMPLES - 1) / MAX_SAMPLES; - -- // Do colour correction here since there are no automatic conversion in hardware available. -- colour = vec4(from_linear_to_srgb(colour.rgb), 1); + vec4 colour = vec4(0); + uint count = 0; + for (uint y = ymin ; y < ymax; y += ystep) { @@ -1284,7 +1281,7 @@ index 0b28d8bf3..41de849e6 100644 + colour /= count; + colour.xyz = rgb_to_ycbcr(from_linear_to_srgb(colour.rgb)); + -+ imageStore(luma, ivec3(offset.x + ix, offset.y + iy, 0), vec4(colour.x)); ++ imageStore(luma, ivec3(ix, iy, iz), vec4(colour.x)); + + vec4 sum = colour; + for (uint i = 0 ; i < gl_SubgroupSize; ++i) @@ -1300,12 +1297,17 @@ index 0b28d8bf3..41de849e6 100644 + } + } -- imageStore(target, ivec2(offset.x + ix, offset.y + iy), colour); +- // Do colour correction here since there are no automatic conversion in hardware available. +- colour = vec4(from_linear_to_srgb(colour.rgb), 1); + if (ix %2 == 0 && iy %2 == 0) + { -+ imageStore(chroma, ivec3(offset.xy/2 + gl_GlobalInvocationID.xy/2, 0), vec4(sum.y, sum.z, 0, 0) / 4); -+ imageStore(luma, ivec3(offset.xy/2 + gl_GlobalInvocationID.xy/2, 1), vec4(sum.w, 0, 0, 0) / 4); -+ imageStore(chroma, ivec3(offset.xy/2 + gl_GlobalInvocationID.xy/2, 1), vec4(0.5, 0.5, 0, 0)); ++ // actual chroma ++ imageStore(chroma, ivec3(gl_GlobalInvocationID.xy/2, iz), vec4(sum.y, sum.z, 0, 0) / 4); + +- imageStore(target, ivec2(offset.x + ix, offset.y + iy), colour); ++ // alpha in luma ++ imageStore(luma, ivec3(offset.xy/2 + gl_GlobalInvocationID.xy/2, 2), vec4(sum.w, 0, 0, 0) / 4); ++ imageStore(chroma, ivec3(offset.xy/2 + gl_GlobalInvocationID.xy/2, 2), vec4(0.5, 0.5, 0, 0)); + } } diff --git a/src/xrt/compositor/util/comp_high_level_render.c b/src/xrt/compositor/util/comp_high_level_render.c diff --git a/patches/monado/0006-d-steamvr_lh-prevent-crash-on-vive-pro2-WiVRn.patch b/patches/monado/0006-d-steamvr_lh-prevent-crash-on-vive-pro2-WiVRn.patch index fd623443..9b5881d4 100644 --- a/patches/monado/0006-d-steamvr_lh-prevent-crash-on-vive-pro2-WiVRn.patch +++ b/patches/monado/0006-d-steamvr_lh-prevent-crash-on-vive-pro2-WiVRn.patch @@ -1,14 +1,14 @@ -From e0cacca9e23baee0cc7bda8133e3e49357fe132f Mon Sep 17 00:00:00 2001 +From 202b9acfb598ab61f75d8cb7aa9c9cb08460674b Mon Sep 17 00:00:00 2001 From: no name Date: Sun, 28 Sep 2025 11:33:10 +0200 -Subject: [PATCH 6/6] d/steamvr_lh: prevent crash on vive pro2/WiVRn +Subject: [PATCH 6/7] d/steamvr_lh: prevent crash on vive pro2/WiVRn --- src/xrt/drivers/steamvr_lh/steamvr_lh.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/xrt/drivers/steamvr_lh/steamvr_lh.cpp b/src/xrt/drivers/steamvr_lh/steamvr_lh.cpp -index c63c14529..2e7b247e6 100644 +index 111a4d225..cdc06d0a7 100644 --- a/src/xrt/drivers/steamvr_lh/steamvr_lh.cpp +++ b/src/xrt/drivers/steamvr_lh/steamvr_lh.cpp @@ -895,7 +895,7 @@ steamvr_lh_create_devices(struct xrt_prober *xp, struct xrt_system_devices **out diff --git a/patches/monado/0007-st-oxr-push-XrEventDataInteractionProfileChanged-whe.patch b/patches/monado/0007-st-oxr-push-XrEventDataInteractionProfileChanged-whe.patch index fb6229c4..81ac6601 100644 --- a/patches/monado/0007-st-oxr-push-XrEventDataInteractionProfileChanged-whe.patch +++ b/patches/monado/0007-st-oxr-push-XrEventDataInteractionProfileChanged-whe.patch @@ -1,7 +1,7 @@ -From 6f7304dee78dcbf0b485177465d10b4878668ede Mon Sep 17 00:00:00 2001 +From 0bce153782cc0fedcdbf997afa2da81b4efe92e8 Mon Sep 17 00:00:00 2001 From: Sapphire Date: Fri, 7 Nov 2025 20:41:16 -0600 -Subject: [PATCH] st/oxr: push XrEventDataInteractionProfileChanged when +Subject: [PATCH 7/7] st/oxr: push XrEventDataInteractionProfileChanged when profile changes to NULL --- diff --git a/server/driver/configuration.cpp b/server/driver/configuration.cpp index 9cfb4a63..7e3c8d86 100644 --- a/server/driver/configuration.cpp +++ b/server/driver/configuration.cpp @@ -140,10 +140,6 @@ configuration::encoder parse_encoder(const nlohmann::json & item) if (item.contains(#property)) \ e.property = item[#property]; - SET_IF(width); - SET_IF(height); - SET_IF(offset_x); - SET_IF(offset_y); SET_IF(group); SET_IF(codec); if (e.codec == wivrn::video_codec(-1)) @@ -175,15 +171,21 @@ configuration::configuration() if (auto it = json.find("bitrate"); it != json.end()) bitrate = *it; - if (auto it = json.find("encoders"); it != json.end()) + if (auto it = json.find("encoder"); it != json.end()) { - for (const auto & encoder: *it) - encoders.push_back(parse_encoder(encoder)); + if (it->is_object()) + { + std::ranges::fill(encoders, parse_encoder(*it)); + } + else if (it->is_array()) + { + for (size_t i = 0; i < std::min(encoders.size(), it->size()); ++i) + { + encoders[i] = parse_encoder(it->at(i)); + } + } } - if (auto it = json.find("encoder-passthrough"); it != json.end()) - encoder_passthrough = parse_encoder(*it); - if (auto it = json.find("application"); it != json.end()) { if (it->is_string()) diff --git a/server/driver/configuration.h b/server/driver/configuration.h index 3dece25d..df926e1c 100644 --- a/server/driver/configuration.h +++ b/server/driver/configuration.h @@ -44,18 +44,13 @@ struct configuration struct encoder { std::string name; - std::optional width; - std::optional height; - std::optional offset_x; - std::optional offset_y; std::optional group; std::optional codec; std::map options; std::optional device; }; - std::vector encoders; - std::optional encoder_passthrough; + std::array encoders; // left, right, alpha std::optional bitrate; int bit_depth = 8; std::optional> scale; diff --git a/server/driver/wivrn_comp_target.cpp b/server/driver/wivrn_comp_target.cpp index 4f0b7546..8b49b820 100644 --- a/server/driver/wivrn_comp_target.cpp +++ b/server/driver/wivrn_comp_target.cpp @@ -31,6 +31,7 @@ #include "xrt_cast.h" #include +#include #include #include #include @@ -143,21 +144,17 @@ static void create_encoders(wivrn_comp_target * cn) to_headset::video_stream_description & desc = cn->desc; desc.width = cn->width; desc.height = cn->height; - const auto & hmd = cn->cnx.get_hmd().hmd; - desc.defoveated_width = hmd->views[0].display.w_pixels * 2; - desc.defoveated_height = hmd->views[0].display.h_pixels; std::map>> thread_params; uint32_t bitrate = 0; - for (auto & settings: cn->settings) + for (auto [i, settings]: std::ranges::enumerate_view(cn->settings)) { bitrate += settings.bitrate; - uint8_t stream_index = cn->encoders.size(); auto & encoder = cn->encoders.emplace_back( - video_encoder::create(*cn->wivrn_bundle, settings, stream_index, desc.width, desc.height, desc.fps)); - desc.items.push_back(settings); + video_encoder::create(*cn->wivrn_bundle, settings, i)); + desc.codec[i] = settings.codec; thread_params[settings.group].emplace_back(encoder); } @@ -204,7 +201,7 @@ static VkResult create_images(struct wivrn_comp_target * cn, vk::ImageUsageFlags .depth = 1, }, .mipLevels = 1, - .arrayLayers = 2, // colour then alpha + .arrayLayers = 3, // left, right then alpha .samples = vk::SampleCountFlagBits::e1, .tiling = vk::ImageTiling::eOptimal, .usage = flags | vk::ImageUsageFlagBits::eStorage | vk::ImageUsageFlagBits::eTransferSrc, @@ -218,10 +215,10 @@ static VkResult create_images(struct wivrn_comp_target * cn, vk::ImageUsageFlags #if WIVRN_USE_VULKAN_ENCODE if ( vk->features.video_maintenance_1 and - std::ranges::any_of( + std::ranges::contains( cn->settings, - [](const auto & item) { return item.encoder_name == encoder_vulkan // - and item.offset_x == 0 and item.offset_y == 0; })) + encoder_vulkan, + &encoder_settings::encoder_name)) { image_info.get().flags |= vk::ImageCreateFlagBits::eVideoProfileIndependentKHR; image_info.get().usage |= vk::ImageUsageFlagBits::eVideoEncodeSrcKHR; @@ -255,7 +252,7 @@ static VkResult create_images(struct wivrn_comp_target * cn, vk::ImageUsageFlags .subresourceRange = { .aspectMask = vk::ImageAspectFlagBits::ePlane0, .levelCount = 1, - .layerCount = 2, + .layerCount = vk::RemainingArrayLayers, }, }); item.image_view_cbcr = vk::raii::ImageView(device, @@ -267,7 +264,7 @@ static VkResult create_images(struct wivrn_comp_target * cn, vk::ImageUsageFlags .subresourceRange = { .aspectMask = vk::ImageAspectFlagBits::ePlane1, .levelCount = 1, - .layerCount = 2, + .layerCount = vk::RemainingArrayLayers, }, }); cn->images[i].view = VkImageView(*item.image_view_y); @@ -491,7 +488,7 @@ static void comp_wivrn_present_thread(std::stop_token stop_token, wivrn_comp_tar { for (auto & encoder: encoders) { - if (encoder->channels == to_headset::video_stream_description::channels_t::colour or view_info.alpha) + if (encoder->stream_idx < 2 or view_info.alpha) encoder->encode(cn->cnx, view_info, frame_index); } } @@ -572,7 +569,7 @@ static VkResult comp_wivrn_present(struct comp_target * ct, std::vector present_done_sem; for (auto & encoder: cn->encoders) { - if (encoder->channels == to_headset::video_stream_description::channels_t::alpha and not do_alpha) + if (encoder->stream_idx == 2 and not do_alpha) continue; auto [transfer, sem] = encoder->present_image(psc_image.image, command_buffer, info.frame_id); need_queue_transfer |= transfer; @@ -595,7 +592,7 @@ static VkResult comp_wivrn_present(struct comp_target * ct, .baseMipLevel = 0, .levelCount = 1, .baseArrayLayer = 0, - .layerCount = 2}, + .layerCount = vk::RemainingArrayLayers}, }; command_buffer.pipelineBarrier( vk::PipelineStageFlagBits::eTransfer, @@ -615,7 +612,7 @@ static VkResult comp_wivrn_present(struct comp_target * ct, cn->wivrn_bundle->queue.submit(submit_info, *cn->psc.fence); for (auto & encoder: cn->encoders) { - if (encoder->channels == to_headset::video_stream_description::channels_t::alpha and not do_alpha) + if (encoder->stream_idx == 2 and not do_alpha) continue; encoder->post_submit(); } diff --git a/server/driver/wivrn_comp_target.h b/server/driver/wivrn_comp_target.h index 40f64fa7..8d8a8185 100644 --- a/server/driver/wivrn_comp_target.h +++ b/server/driver/wivrn_comp_target.h @@ -94,7 +94,7 @@ struct wivrn_comp_target : public comp_target static std::vector wanted_device_extensions; uint32_t bitrate = 0; - std::vector settings; + std::array settings; std::list encoder_threads; std::vector> encoders; diff --git a/server/driver/wivrn_foveation.cpp b/server/driver/wivrn_foveation.cpp index 8670c7fd..6274ada4 100644 --- a/server/driver/wivrn_foveation.cpp +++ b/server/driver/wivrn_foveation.cpp @@ -302,7 +302,7 @@ void wivrn_foveation::compute_params( } wivrn_foveation::wivrn_foveation(wivrn_vk_bundle & bundle, const xrt_hmd_parts & hmd) : - foveated_width(hmd.screens[0].w_pixels / 2), + foveated_width(hmd.screens[0].w_pixels), foveated_height(hmd.screens[0].h_pixels), angle_offset(get_angle_offset()), convergence_distance(get_convergence_distance()), diff --git a/server/driver/wivrn_hmd.cpp b/server/driver/wivrn_hmd.cpp index 0ede1343..5a8efdae 100644 --- a/server/driver/wivrn_hmd.cpp +++ b/server/driver/wivrn_hmd.cpp @@ -103,7 +103,7 @@ wivrn_hmd::wivrn_hmd(wivrn::wivrn_session * cnx, hmd->distortion.models = XRT_DISTORTION_MODEL_NONE; hmd->distortion.preferred = XRT_DISTORTION_MODEL_NONE; - hmd->screens[0].w_pixels = eye_width * 2; + hmd->screens[0].w_pixels = eye_width; hmd->screens[0].h_pixels = eye_height; // Left @@ -208,19 +208,17 @@ xrt_result_t wivrn_hmd::get_battery_status(bool * out_present, void wivrn_hmd::set_foveated_size(uint32_t width, uint32_t height) { - assert(width % 2 == 0); - uint32_t eye_width = width / 2; - hmd->screens[0].w_pixels = width; hmd->screens[0].h_pixels = height; for (int i = 0; i < 2; ++i) { auto & view = hmd->views[i]; - view.viewport.x_pixels = i * eye_width; + // offset is only applicable for alpha channel + view.viewport.x_pixels = i * width; view.viewport.y_pixels = 0; - view.viewport.w_pixels = eye_width; + view.viewport.w_pixels = width; view.viewport.h_pixels = height; } } diff --git a/server/encoder/encoder_settings.cpp b/server/encoder/encoder_settings.cpp index f2267e16..5d2ce210 100644 --- a/server/encoder/encoder_settings.cpp +++ b/server/encoder/encoder_settings.cpp @@ -45,24 +45,22 @@ namespace wivrn // TODO: size independent bitrate static const uint64_t default_bitrate = 50'000'000; -// subsampling is also in monado's distortion shader -static const uint8_t passthrough_subsampling = 2; static const double passthrough_bitrate_factor = 0.05; -#define WIVRN_SPLIT_ENCODERS 1 - static bool is_nvidia(vk::PhysicalDevice physical_device) { auto props = physical_device.getProperties(); return props.vendorID == 0x10DE; } -static void split_bitrate(std::vector & encoders, uint64_t bitrate) +static void split_bitrate(std::array & encoders, uint64_t bitrate) { double total_weight = 0; - for (auto & encoder: encoders) + for (auto [i, encoder]: std::ranges::enumerate_view(encoders)) { double w = encoder.width * encoder.height; + if (i == 2) + w *= passthrough_bitrate_factor; switch (encoder.codec) { case wivrn::h264: @@ -84,7 +82,7 @@ static void split_bitrate(std::vector & encoders, uint6 } } -void print_encoders(const std::vector & encoders) +void print_encoders(const std::array & encoders) { int group = -1; std::stringstream str; @@ -99,8 +97,7 @@ void print_encoders(const std::vector & encoders) else str << "\n"; str << "\n\t\t" << encoder.encoder_name << " (" << magic_enum::enum_name(encoder.codec) << " " << encoder.bit_depth << "-bit)" - << "\n\t\tchannels: " << magic_enum::enum_name(encoder.channels) - << "\n\t\tsize: " << encoder.width << "x" << encoder.height << " offset: " << encoder.offset_x << "x" << encoder.offset_y + << "\n\t\tsize: " << encoder.width << "x" << encoder.height << "\n\t\tbitrate: " << encoder.bitrate / 1'000'000 << "Mbit/s"; } U_LOG_I("%s", str.str().c_str()); @@ -148,16 +145,13 @@ static std::optional filter_codecs_vaapi(wivrn_vk_bundle & b { video_encoder_ffmpeg::mute_logs mute; encoder_settings s{ - { - .width = 800, - .height = 600, - .video_width = 800, - .video_height = 600, - }, - "vaapi", - default_bitrate, + .width = 800, + .height = 600, + .fps = 60, + .encoder_name = "vaapi", + .bitrate = default_bitrate, + .bit_depth = bit_depth, }; - s.bit_depth = bit_depth; for (auto codec: codecs) { @@ -177,7 +171,7 @@ static std::optional filter_codecs_vaapi(wivrn_vk_bundle & b try { s.codec = codec; - video_encoder_va test(bundle, s, 60, 0); + video_encoder_va test(bundle, s, 0); return codec; } catch (...) @@ -195,20 +189,17 @@ static bool probe_nvenc(wivrn_vk_bundle & bundle, int bit_depth) { static bool res = [&]() { encoder_settings s{ - { - .width = 800, - .height = 608, - .video_width = 800, - .video_height = 608, - .codec = h264, - }, - encoder_nvenc, - default_bitrate, + .width = 800, + .height = 608, + .codec = h264, + .fps = 60, + .encoder_name = encoder_nvenc, + .bitrate = default_bitrate, + .bit_depth = bit_depth, }; - s.bit_depth = bit_depth; try { - video_encoder_nvenc test(bundle, s, 60, 0); + video_encoder_nvenc test(bundle, s, 0); return true; } catch (std::exception & e) @@ -308,44 +299,11 @@ static void fill_defaults(wivrn_vk_bundle & bundle, const std::vector get_encoder_default_settings(wivrn_vk_bundle & bundle, const std::vector & headset_codecs, int bit_depth) +static std::array get_encoder_default_settings(wivrn_vk_bundle & bundle, const std::vector & headset_codecs, int bit_depth) { configuration::encoder base; fill_defaults(bundle, headset_codecs, base, bit_depth); - -#ifdef WIVRN_SPLIT_ENCODERS - if (base.name != encoder_x264) - { - /* Split in 2 parts: - * +--------+--------+ - * | | | - * | left | right | - * | eye | eye | - * | | | - * +--------+--------+ - * Encoded sequentially, so the first eye is ready and transmitted earlier. - * Decoder can start work as fast as possible, reducing idle time. - * Splitting on eye boundaries allows for fast-path on headset. - * - */ - return { - { - .name = base.name, - .width = 0.5, - .group = 0, - .codec = base.codec, - }, - { - .name = base.name, - .width = 0.5, - .offset_x = 0.5, - .group = 0, - .codec = base.codec, - }, - }; - } -#endif - return {base}; + return {base, base, base}; } static uint16_t align(uint16_t value, uint16_t alignment) @@ -353,7 +311,7 @@ static uint16_t align(uint16_t value, uint16_t alignment) return ((value + alignment - 1) / alignment) * alignment; } -std::vector get_encoder_settings(wivrn_vk_bundle & bundle, uint32_t & width, uint32_t & height, const from_headset::headset_info_packet & info) +std::array get_encoder_settings(wivrn_vk_bundle & bundle, uint32_t & width, uint32_t & height, const from_headset::headset_info_packet & info) { configuration config; @@ -362,42 +320,27 @@ std::vector get_encoder_settings(wivrn_vk_bundle & bundle, uin if (config.encoders.empty()) config.encoders = get_encoder_default_settings(bundle, info.supported_codecs, config.bit_depth); - if (not config.encoder_passthrough) - config.encoder_passthrough = config.encoders.front(); - - config.encoder_passthrough->width = 1; - config.encoder_passthrough->height = 1; - config.encoder_passthrough->offset_x = 0; - config.encoder_passthrough->offset_y = 0; - fill_defaults(bundle, info.supported_codecs, *config.encoder_passthrough, config.bit_depth); uint64_t bitrate = config.bitrate.value_or(default_bitrate); std::array default_scale; default_scale.fill(info.eye_gaze ? 0.35 : 0.5); auto scale = config.scale.value_or(default_scale); - check_scale(config.encoder_passthrough->name, - *config.encoder_passthrough->codec, - // passthrough stream is subsampled - width / passthrough_subsampling, - height / passthrough_subsampling, - scale); - for (auto & encoder: config.encoders) { fill_defaults(bundle, info.supported_codecs, encoder, config.bit_depth); assert(encoder.codec); check_scale(encoder.name, *encoder.codec, - std::ceil(encoder.width.value_or(1) * width), - std::ceil(encoder.height.value_or(1) * height), + std::ceil(width), + std::ceil(height), scale); } width = align(width * scale[0], 64); height = align(height * scale[1], 64); - std::vector res; + std::array res; std::unordered_map groups; int next_group = 0; for (const auto & encoder: config.encoders) @@ -409,20 +352,15 @@ std::vector get_encoder_settings(wivrn_vk_bundle & bundle, uin } } - for (const auto & encoder: config.encoders) + for (const auto & [i, encoder]: std::ranges::enumerate_view(config.encoders)) { wivrn::encoder_settings settings{}; - settings.channels = to_headset::video_stream_description::channels_t::colour; - settings.subsampling = 1; settings.encoder_name = encoder.name; - settings.offset_x = align(std::ceil(encoder.offset_x.value_or(0) * width), 32); - settings.offset_y = align(std::ceil(encoder.offset_y.value_or(0) * height), 32); - settings.width = align(std::ceil(encoder.width.value_or(1) * width), 32); - settings.height = align(std::ceil(encoder.height.value_or(1) * height), 32); - settings.width = std::min(settings.width, width - settings.offset_x); - settings.height = std::min(settings.height, height - settings.offset_y); - settings.video_width = settings.width; - settings.video_height = settings.height; + settings.width = align(std::ceil(width), 32); + settings.height = align(std::ceil(height), 32); + // alpha is half resolution, but left and right side by side + if (i == 2) + settings.height /= 2; settings.codec = *encoder.codec; settings.bit_depth = config.bit_depth; if (encoder.group) @@ -436,40 +374,11 @@ std::vector get_encoder_settings(wivrn_vk_bundle & bundle, uin } settings.options = encoder.options; settings.device = encoder.device; + settings.fps = info.preferred_refresh_rate; - res.push_back(settings); + res[i] = settings; } split_bitrate(res, bitrate); - - // passthrough encoder - { - const auto & encoder = *config.encoder_passthrough; - wivrn::encoder_settings settings{}; - settings.channels = to_headset::video_stream_description::channels_t::alpha; - settings.subsampling = passthrough_subsampling; - settings.encoder_name = encoder.name; - settings.width = width / settings.subsampling; - settings.height = height / settings.subsampling; - assert(settings.width % 32 == 0); - assert(settings.height % 32 == 0); - settings.video_width = settings.width; - settings.video_height = settings.height; - settings.codec = *encoder.codec; - settings.bit_depth = config.bit_depth; - if (encoder.group) - settings.group = *encoder.group; - else - { - auto [it, inserted] = groups.emplace(encoder.name, next_group); - settings.group = it->second; - if (inserted) - ++next_group; - } - settings.options = encoder.options; - settings.device = encoder.device; - settings.bitrate = bitrate * passthrough_bitrate_factor; - res.push_back(settings); - } return res; } } // namespace wivrn diff --git a/server/encoder/encoder_settings.h b/server/encoder/encoder_settings.h index 0471b7a7..b54e2f34 100644 --- a/server/encoder/encoder_settings.h +++ b/server/encoder/encoder_settings.h @@ -24,14 +24,17 @@ #include #include #include -#include namespace wivrn { struct wivrn_vk_bundle; -struct encoder_settings : public to_headset::video_stream_description::item +struct encoder_settings { + uint16_t width; + uint16_t height; + video_codec codec; // left, right, alpha + float fps; // encoder identifier, such as nvenc, vaapi or x264 std::string encoder_name; uint64_t bitrate; // bit/s @@ -43,8 +46,8 @@ struct encoder_settings : public to_headset::video_stream_description::item std::optional device; }; -std::vector get_encoder_settings(wivrn_vk_bundle &, uint32_t & width, uint32_t & height, const from_headset::headset_info_packet & info); +std::array get_encoder_settings(wivrn_vk_bundle &, uint32_t & width, uint32_t & height, const from_headset::headset_info_packet & info); -void print_encoders(const std::vector & encoders); +void print_encoders(const std::array & encoders); } // namespace wivrn diff --git a/server/encoder/ffmpeg/video_encoder_ffmpeg.h b/server/encoder/ffmpeg/video_encoder_ffmpeg.h index e4932c75..75309324 100644 --- a/server/encoder/ffmpeg/video_encoder_ffmpeg.h +++ b/server/encoder/ffmpeg/video_encoder_ffmpeg.h @@ -37,8 +37,8 @@ public: }; protected: - video_encoder_ffmpeg(uint8_t stream_idx, to_headset::video_stream_description::channels_t channels, double bitrate_multiplier) : - wivrn::video_encoder(stream_idx, channels, std::make_unique(), bitrate_multiplier, true) {} + video_encoder_ffmpeg(uint8_t stream_idx, const encoder_settings & settings) : + wivrn::video_encoder(stream_idx, settings, std::make_unique(), true) {} virtual void push_frame(bool idr, uint8_t slot) = 0; diff --git a/server/encoder/ffmpeg/video_encoder_va.cpp b/server/encoder/ffmpeg/video_encoder_va.cpp index fda152c5..712d0a71 100644 --- a/server/encoder/ffmpeg/video_encoder_va.cpp +++ b/server/encoder/ffmpeg/video_encoder_va.cpp @@ -157,10 +157,9 @@ vk::Format drm_to_vulkan_fmt(uint32_t drm_fourcc, int bit_depth) } // namespace video_encoder_va::video_encoder_va(wivrn_vk_bundle & vk, - wivrn::encoder_settings & settings, - float fps, + const wivrn::encoder_settings & settings, uint8_t stream_idx) : - video_encoder_ffmpeg(stream_idx, settings.channels, settings.bitrate_multiplier), + video_encoder_ffmpeg(stream_idx, settings), synchronization2(vk.vk.features.synchronization_2) { auto drm_hw_ctx = make_drm_hw_ctx(vk.physical_device, settings.device); @@ -173,9 +172,6 @@ video_encoder_va::video_encoder_va(wivrn_vk_bundle & vk, throw std::system_error(err, av_error_category(), "FFMPEG vaapi hardware context creation failed"); av_buffer_ptr vaapi_hw_ctx(tmp); - settings.video_width += settings.video_width % 2; - settings.video_height += settings.video_height % 2; - AVPixelFormat sw_format; switch (settings.codec) @@ -196,19 +192,9 @@ video_encoder_va::video_encoder_va(wivrn_vk_bundle & vk, break; } - auto vaapi_frame_ctx = make_hwframe_ctx(vaapi_hw_ctx.get(), AV_PIX_FMT_VAAPI, sw_format, settings.video_width, settings.video_height); + auto vaapi_frame_ctx = make_hwframe_ctx(vaapi_hw_ctx.get(), AV_PIX_FMT_VAAPI, sw_format, extent.width, extent.height); assert(av_pix_fmt_count_planes(sw_format) == 2); - rect = vk::Rect2D{ - .offset = { - .x = settings.offset_x, - .y = settings.offset_y, - }, - .extent = { - .width = settings.width, - .height = settings.height, - }}; - err = av_hwframe_ctx_create_derived(&tmp, AV_PIX_FMT_DRM_PRIME, drm_hw_ctx.get(), @@ -257,11 +243,11 @@ video_encoder_va::video_encoder_va(wivrn_vk_bundle & vk, av_dict_set(&opts, option.first.c_str(), option.second.c_str(), 0); } - encoder_ctx->width = settings.video_width; - encoder_ctx->height = settings.video_height; + encoder_ctx->width = extent.width; + encoder_ctx->height = extent.height; encoder_ctx->time_base = {std::chrono::steady_clock::duration::period::num, std::chrono::steady_clock::duration::period::den}; - encoder_ctx->framerate = AVRational{(int)fps, 1}; + encoder_ctx->framerate = AVRational{(int)settings.fps * 1000, 1000}; encoder_ctx->sample_aspect_ratio = AVRational{1, 1}; encoder_ctx->pix_fmt = AV_PIX_FMT_VAAPI; encoder_ctx->color_range = AVCOL_RANGE_JPEG; @@ -466,20 +452,16 @@ std::pair video_encoder_va::present_image(vk::Image y_cbcr, vk::ImageCopy{ .srcSubresource = { .aspectMask = vk::ImageAspectFlagBits::ePlane0, - .baseArrayLayer = uint32_t(channels), + .baseArrayLayer = stream_idx, .layerCount = 1, }, - .srcOffset = { - .x = rect.offset.x, - .y = rect.offset.y, - }, .dstSubresource = { .aspectMask = vk::ImageAspectFlagBits::eColor, .layerCount = 1, }, .extent = { - .width = rect.extent.width, - .height = rect.extent.height, + .width = extent.width, + .height = extent.height, .depth = 1, }}); @@ -491,20 +473,16 @@ std::pair video_encoder_va::present_image(vk::Image y_cbcr, vk::ImageCopy{ .srcSubresource = { .aspectMask = vk::ImageAspectFlagBits::ePlane1, - .baseArrayLayer = uint32_t(channels), + .baseArrayLayer = stream_idx, .layerCount = 1, }, - .srcOffset = { - .x = rect.offset.x / 2, - .y = rect.offset.y / 2, - }, .dstSubresource = { .aspectMask = vk::ImageAspectFlagBits::eColor, .layerCount = 1, }, .extent = { - .width = rect.extent.width / 2, - .height = rect.extent.height / 2, + .width = extent.width / 2, + .height = extent.height / 2, .depth = 1, }}); diff --git a/server/encoder/ffmpeg/video_encoder_va.h b/server/encoder/ffmpeg/video_encoder_va.h index b2d2d97f..82c764be 100644 --- a/server/encoder/ffmpeg/video_encoder_va.h +++ b/server/encoder/ffmpeg/video_encoder_va.h @@ -43,11 +43,10 @@ class video_encoder_va : public video_encoder_ffmpeg }; av_buffer_ptr drm_frame_ctx; std::array in; - vk::Rect2D rect; bool synchronization2 = false; public: - video_encoder_va(wivrn_vk_bundle &, wivrn::encoder_settings & settings, float fps, uint8_t stream_index); + video_encoder_va(wivrn_vk_bundle &, const wivrn::encoder_settings & settings, uint8_t stream_index); std::pair present_image(vk::Image y_cbcr, vk::raii::CommandBuffer & cmd_buf, uint8_t slot, uint64_t frame_index) override; diff --git a/server/encoder/video_encoder.cpp b/server/encoder/video_encoder.cpp index aae2526f..ac82987b 100644 --- a/server/encoder/video_encoder.cpp +++ b/server/encoder/video_encoder.cpp @@ -102,26 +102,21 @@ std::shared_ptr video_encoder::sender::get() std::unique_ptr video_encoder::create( wivrn_vk_bundle & wivrn_vk, - encoder_settings & settings, - uint8_t stream_idx, - int input_width, - int input_height, - float fps) + const encoder_settings & settings, + uint8_t stream_idx) { using namespace std::string_literals; std::unique_ptr res; - settings.range = VK_SAMPLER_YCBCR_RANGE_ITU_FULL; - settings.color_model = VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_709; if (settings.encoder_name == encoder_vulkan) { #if WIVRN_USE_VULKAN_ENCODE switch (settings.codec) { case video_codec::h264: - res = video_encoder_vulkan_h264::create(wivrn_vk, settings, fps, stream_idx); + res = video_encoder_vulkan_h264::create(wivrn_vk, settings, stream_idx); break; case video_codec::h265: - res = video_encoder_vulkan_h265::create(wivrn_vk, settings, fps, stream_idx); + res = video_encoder_vulkan_h265::create(wivrn_vk, settings, stream_idx); break; case video_codec::av1: throw std::runtime_error("av1 not supported for vulkan video encode"); @@ -135,7 +130,7 @@ std::unique_ptr video_encoder::create( if (settings.encoder_name == encoder_x264) { #if WIVRN_USE_X264 - res = std::make_unique(wivrn_vk, settings, fps, stream_idx); + res = std::make_unique(wivrn_vk, settings, stream_idx); #else throw std::runtime_error("x264 encoder not enabled"); #endif @@ -143,7 +138,7 @@ std::unique_ptr video_encoder::create( if (settings.encoder_name == encoder_nvenc) { #if WIVRN_USE_NVENC - res = std::make_unique(wivrn_vk, settings, fps, stream_idx); + res = std::make_unique(wivrn_vk, settings, stream_idx); #else throw std::runtime_error("nvenc support not enabled"); #endif @@ -151,7 +146,7 @@ std::unique_ptr video_encoder::create( if (settings.encoder_name == encoder_vaapi) { #if WIVRN_USE_VAAPI - res = std::make_unique(wivrn_vk, settings, fps, stream_idx); + res = std::make_unique(wivrn_vk, settings, stream_idx); #else throw std::runtime_error("vaapi support not enabled"); #endif @@ -159,7 +154,7 @@ std::unique_ptr video_encoder::create( if (settings.encoder_name == encoder_raw) { - res = std::make_unique(wivrn_vk, settings, fps, stream_idx); + res = std::make_unique(wivrn_vk, settings, stream_idx); } if (not res) @@ -190,12 +185,18 @@ std::unique_ptr video_encoder::create( return res; } -video_encoder::video_encoder(uint8_t stream_idx, to_headset::video_stream_description::channels_t channels, std::unique_ptr idr, double bitrate_multiplier, bool async_send) : +video_encoder::video_encoder(uint8_t stream_idx, + const encoder_settings & settings, + std::unique_ptr idr, + bool async_send) : stream_idx(stream_idx), - channels(channels), - bitrate_multiplier(bitrate_multiplier), + bitrate_multiplier(settings.bitrate_multiplier), shared_sender(async_send ? sender::get() : nullptr), - idr(std::move(idr)) + idr(std::move(idr)), + extent{ + .width = settings.width, + .height = settings.height, + } { assert(this->idr); } @@ -315,7 +316,6 @@ void video_encoder::SendData(std::span data, bool end_of_frame, bool co ssize_t max_payload_size = cnx->has_stream() ? to_headset::video_stream_data_shard::max_payload_size : std::numeric_limits::max(); - shard.flags = to_headset::video_stream_data_shard::start_of_slice; auto begin = data.begin(); auto end = data.end(); while (begin != end) @@ -324,12 +324,8 @@ void video_encoder::SendData(std::span data, bool end_of_frame, bool co auto next = std::min(end, begin + payload_size); if (next == end) { - shard.flags |= to_headset::video_stream_data_shard::end_of_slice; if (end_of_frame) - { - shard.flags |= to_headset::video_stream_data_shard::end_of_frame; shard.timing_info = timing_info; - } } shard.payload = {begin, next}; try @@ -344,7 +340,6 @@ void video_encoder::SendData(std::span data, bool end_of_frame, bool co // Ignore network errors } ++shard.shard_idx; - shard.flags = 0; shard.view_info.reset(); begin = next; } diff --git a/server/encoder/video_encoder.h b/server/encoder/video_encoder.h index fc89106f..ca60cc84 100644 --- a/server/encoder/video_encoder.h +++ b/server/encoder/video_encoder.h @@ -76,7 +76,6 @@ private: public: const uint8_t stream_idx; - const to_headset::video_stream_description::channels_t channels; static const uint8_t num_slots = 2; const double bitrate_multiplier; @@ -108,17 +107,15 @@ protected: std::atomic_uint32_t pending_bitrate; std::atomic pending_framerate; std::unique_ptr idr; + const vk::Extent2D extent; public: static std::unique_ptr create( wivrn_vk_bundle &, - encoder_settings & settings, - uint8_t stream_idx, - int input_width, - int input_height, - float fps); + const encoder_settings & settings, + uint8_t stream_idx); - video_encoder(uint8_t stream_idx, to_headset::video_stream_description::channels_t channels, std::unique_ptr, double bitrate_multiplier, bool async_send); + video_encoder(uint8_t stream_idx, const encoder_settings & settings, std::unique_ptr, bool async_send); virtual ~video_encoder(); // return value: true if image should be transitioned to queue and layout for vulkan video encode diff --git a/server/encoder/video_encoder_nvenc.cpp b/server/encoder/video_encoder_nvenc.cpp index 55f1b92d..d8868bab 100644 --- a/server/encoder/video_encoder_nvenc.cpp +++ b/server/encoder/video_encoder_nvenc.cpp @@ -150,30 +150,19 @@ void video_encoder_nvenc::set_init_params_fps(float framerate) video_encoder_nvenc::video_encoder_nvenc( wivrn_vk_bundle & vk, - encoder_settings & settings, - float fps, + const encoder_settings & settings, uint8_t stream_idx) : - video_encoder(stream_idx, settings.channels, std::make_unique(), settings.bitrate_multiplier, true), + video_encoder(stream_idx, settings, std::make_unique(), true), vk(vk), shared_state(video_encoder_nvenc_shared_state::get()), - fps(fps), + fps(settings.fps), bitrate(settings.bitrate) { if (settings.bit_depth != 8 && settings.bit_depth != 10) throw std::runtime_error("nvenc encoder only supports 8-bit and 10-bit encoding"); - assert(settings.width % 32 == 0); - assert(settings.height % 32 == 0); - rect = vk::Rect2D{ - .offset = { - .x = settings.offset_x, - .y = settings.offset_y, - }, - .extent = { - .width = settings.width, - .height = settings.height, - }, - }; + assert(extent.width % 32 == 0); + assert(extent.height % 32 == 0); NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS session_params = { .version = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER, @@ -284,10 +273,10 @@ video_encoder_nvenc::video_encoder_nvenc( .version = NV_ENC_INITIALIZE_PARAMS_VER, .encodeGUID = encodeGUID, .presetGUID = presetGUID, - .encodeWidth = settings.video_width, - .encodeHeight = settings.video_height, - .darWidth = settings.video_width, - .darHeight = settings.video_height, + .encodeWidth = extent.width, + .encodeHeight = extent.height, + .darWidth = extent.width, + .darHeight = extent.height, .enableEncodeAsync = 0, .enablePTD = 1, .encodeConfig = &config, @@ -303,7 +292,7 @@ video_encoder_nvenc::video_encoder_nvenc( NVENC_CHECK(shared_state->fn.nvEncCreateBitstreamBuffer(session_handle, &out_buf_params)); outputBuffer = out_buf_params.bitstreamBuffer; - vk::DeviceSize buffer_size = rect.extent.width * settings.video_height * bytesPerPixel * 3 / 2; + vk::DeviceSize buffer_size = extent.width * extent.height * bytesPerPixel * 3 / 2; vk::StructureChain buffer_create_info{ vk::BufferCreateInfo{ @@ -365,9 +354,9 @@ video_encoder_nvenc::video_encoder_nvenc( NV_ENC_REGISTER_RESOURCE resource_params{ .version = NV_ENC_REGISTER_RESOURCE_VER, .resourceType = NV_ENC_INPUT_RESOURCE_TYPE_CUDADEVICEPTR, - .width = settings.video_width, - .height = settings.video_height, - .pitch = rect.extent.width * bytesPerPixel, + .width = extent.width, + .height = extent.height, + .pitch = extent.width * bytesPerPixel, .resourceToRegister = (void *)frame, .bufferFormat = (bitDepth == NV_ENC_BIT_DEPTH_10 ? NV_ENC_BUFFER_FORMAT_YUV420_10BIT : NV_ENC_BUFFER_FORMAT_NV12), .bufferUsage = NV_ENC_INPUT_IMAGE, @@ -392,35 +381,31 @@ std::pair video_encoder_nvenc::present_image(vk::Image y_cb *in[slot].yuv, std::array{ vk::BufferImageCopy{ - .bufferRowLength = rect.extent.width, + .bufferRowLength = extent.width, .imageSubresource = { .aspectMask = vk::ImageAspectFlagBits::ePlane0, - .baseArrayLayer = uint32_t(channels), + .baseArrayLayer = stream_idx, .layerCount = 1, }, - .imageOffset = { - .x = rect.offset.x, - .y = rect.offset.y, - }, .imageExtent = { - .width = rect.extent.width, - .height = rect.extent.height, + .width = extent.width, + .height = extent.height, .depth = 1, }}, - vk::BufferImageCopy{.bufferOffset = rect.extent.width * rect.extent.height * bytesPerPixel, .bufferRowLength = uint32_t(rect.extent.width / 2), .imageSubresource = { - .aspectMask = vk::ImageAspectFlagBits::ePlane1, - .baseArrayLayer = uint32_t(channels), - .layerCount = 1, - }, - .imageOffset = { - .x = rect.offset.x / 2, - .y = rect.offset.y / 2, - }, - .imageExtent = { - .width = rect.extent.width / 2, - .height = rect.extent.height / 2, - .depth = 1, - }}}); + vk::BufferImageCopy{ + .bufferOffset = extent.width * extent.height * bytesPerPixel, + .bufferRowLength = uint32_t(extent.width / 2), + .imageSubresource = { + .aspectMask = vk::ImageAspectFlagBits::ePlane1, + .baseArrayLayer = stream_idx, + .layerCount = 1, + }, + .imageExtent = { + .width = extent.width / 2, + .height = extent.height / 2, + .depth = 1, + }, + }}); return {false, nullptr}; } @@ -479,9 +464,9 @@ std::optional video_encoder_nvenc::encode(uint8_t slot, uin NV_ENC_PIC_PARAMS frame_params{ .version = NV_ENC_PIC_PARAMS_VER, - .inputWidth = rect.extent.width, - .inputHeight = rect.extent.height, - .inputPitch = rect.extent.width, + .inputWidth = extent.width, + .inputHeight = extent.height, + .inputPitch = extent.width, .encodePicFlags = 0, .frameIdx = 0, .inputTimeStamp = 0, diff --git a/server/encoder/video_encoder_nvenc.h b/server/encoder/video_encoder_nvenc.h index 1002cd5e..8c241d0b 100644 --- a/server/encoder/video_encoder_nvenc.h +++ b/server/encoder/video_encoder_nvenc.h @@ -34,8 +34,6 @@ class video_encoder_nvenc : public video_encoder { private: wivrn_vk_bundle & vk; - // relevant part of the input image to encode - vk::Rect2D rect; std::shared_ptr shared_state; @@ -60,7 +58,7 @@ private: void set_init_params_fps(float framerate); public: - video_encoder_nvenc(wivrn_vk_bundle & vk, encoder_settings & settings, float fps, uint8_t stream_idx); + video_encoder_nvenc(wivrn_vk_bundle & vk, const encoder_settings & settings, uint8_t stream_idx); ~video_encoder_nvenc(); std::pair present_image(vk::Image y_cbcr, vk::raii::CommandBuffer & cmd_buf, uint8_t slot, uint64_t frame_index) override; diff --git a/server/encoder/video_encoder_raw.cpp b/server/encoder/video_encoder_raw.cpp index 20cc939b..c5c9a5e9 100644 --- a/server/encoder/video_encoder_raw.cpp +++ b/server/encoder/video_encoder_raw.cpp @@ -37,33 +37,16 @@ public: wivrn::video_encoder_raw::video_encoder_raw( wivrn_vk_bundle & vk, - encoder_settings & settings, - float fps, + const encoder_settings & settings, uint8_t stream_idx) : - video_encoder(stream_idx, settings.channels, std::make_unique(), settings.bitrate_multiplier, true) + video_encoder(stream_idx, settings, std::make_unique(), true) { if (settings.bit_depth != 8) throw std::runtime_error("Raw encoding is only supported for 8 bit"); - rect = vk::Rect2D{ - .offset = { - .x = settings.offset_x, - .y = settings.offset_y, - }, - .extent = { - .width = settings.width, - .height = settings.height, - }, - }; - vk::DeviceSize buffer_size = settings.width * settings.height; - switch (settings.channels) - { - case to_headset::video_stream_description::channels_t::colour: - buffer_size += buffer_size / 2; - break; - case to_headset::video_stream_description::channels_t::alpha: - break; - } + vk::DeviceSize buffer_size = extent.width * extent.height; + if (stream_idx < 2) + buffer_size += buffer_size / 2; for (auto & slot: buffers) { slot = buffer_allocation( @@ -86,33 +69,25 @@ std::pair wivrn::video_encoder_raw::present_image(vk::Image vk::BufferImageCopy{ .imageSubresource = { .aspectMask = vk::ImageAspectFlagBits::ePlane0, - .baseArrayLayer = uint32_t(channels), + .baseArrayLayer = stream_idx, .layerCount = 1, }, - .imageOffset = { - .x = rect.offset.x, - .y = rect.offset.y, - }, .imageExtent = { - .width = rect.extent.width, - .height = rect.extent.height, + .width = extent.width, + .height = extent.height, .depth = 1, }, }, vk::BufferImageCopy{ - .bufferOffset = rect.extent.width * rect.extent.height, + .bufferOffset = extent.width * extent.height, .imageSubresource = { .aspectMask = vk::ImageAspectFlagBits::ePlane1, - .baseArrayLayer = uint32_t(channels), + .baseArrayLayer = stream_idx, .layerCount = 1, }, - .imageOffset = { - .x = rect.offset.x / 2, - .y = rect.offset.y / 2, - }, .imageExtent = { - .width = rect.extent.width / 2, - .height = rect.extent.height / 2, + .width = extent.width / 2, + .height = extent.height / 2, .depth = 1, }, }, @@ -122,7 +97,7 @@ std::pair wivrn::video_encoder_raw::present_image(vk::Image vk::ImageLayout::eTransferSrcOptimal, buffers[slot], std::span(regions.data(), - channels == to_headset::video_stream_description::channels_t::colour ? 2 : 1)); + stream_idx == 2 ? 2 : 1)); return {false, nullptr}; } diff --git a/server/encoder/video_encoder_raw.h b/server/encoder/video_encoder_raw.h index 3ef32923..41805bee 100644 --- a/server/encoder/video_encoder_raw.h +++ b/server/encoder/video_encoder_raw.h @@ -29,10 +29,9 @@ namespace wivrn class video_encoder_raw : public video_encoder { std::array buffers; - vk::Rect2D rect; public: - video_encoder_raw(wivrn_vk_bundle & vk, encoder_settings & settings, float fps, uint8_t stream_idx); + video_encoder_raw(wivrn_vk_bundle & vk, const encoder_settings & settings, 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; diff --git a/server/encoder/video_encoder_vulkan.cpp b/server/encoder/video_encoder_vulkan.cpp index 45cef4d2..d2158c8a 100644 --- a/server/encoder/video_encoder_vulkan.cpp +++ b/server/encoder/video_encoder_vulkan.cpp @@ -157,16 +157,13 @@ vk::VideoFormatPropertiesKHR wivrn::video_encoder_vulkan::select_video_format( wivrn::video_encoder_vulkan::video_encoder_vulkan( wivrn_vk_bundle & vk, - vk::Rect2D rect, const vk::VideoCapabilitiesKHR & video_caps, const vk::VideoEncodeCapabilitiesKHR & in_encode_caps, - float fps, uint8_t stream_idx, const encoder_settings & settings) : - video_encoder(stream_idx, settings.channels, std::make_unique(), settings.bitrate_multiplier, true), + video_encoder(stream_idx, settings, std::make_unique(), true), vk(vk), encode_caps(patch_capabilities(in_encode_caps)), - rect(rect), num_dpb_slots(std::min(video_caps.maxDpbSlots, 16u)) { // Initialize Rate control @@ -192,7 +189,7 @@ wivrn::video_encoder_vulkan::video_encoder_vulkan( rate_control_layer = vk::VideoEncodeRateControlLayerInfoKHR{ .averageBitrate = std::min(settings.bitrate, encode_caps.maxBitrate), .maxBitrate = std::min(2 * settings.bitrate, encode_caps.maxBitrate), - .frameRateNumerator = uint32_t(fps * 1'000'000), + .frameRateNumerator = uint32_t(settings.fps * 1'000'000), .frameRateDenominator = 1'000'000, }; rate_control = vk::VideoEncodeRateControlInfoKHR{ @@ -224,8 +221,8 @@ wivrn::video_encoder_vulkan::video_encoder_vulkan( std::max(video_caps.pictureAccessGranularity.height, encode_caps.encodeInputPictureGranularity.height); aligned_extent = vk::Extent3D{ - .width = align(rect.extent.width, std::max(cb_min_size, granWidth)), - .height = align(rect.extent.height, std::max(cb_min_size, granHeight)), + .width = align(extent.width, std::max(cb_min_size, granWidth)), + .height = align(extent.height, std::max(cb_min_size, granHeight)), .depth = 1, }; } @@ -291,7 +288,7 @@ void wivrn::video_encoder_vulkan::init(const vk::VideoCapabilitiesKHR & video_ca for (auto & item: slot_data) { // very conservative bound - size_t output_buffer_size = rect.extent.width * rect.extent.height * 3; + size_t output_buffer_size = extent.width * extent.height * 3; output_buffer_size = align(output_buffer_size, video_caps.minBitstreamBufferSizeAlignment); item.output_buffer = buffer_allocation( vk.device, @@ -371,11 +368,11 @@ void wivrn::video_encoder_vulkan::init(const vk::VideoCapabilitiesKHR & video_ca .subresourceRange = {.aspectMask = vk::ImageAspectFlagBits::eColor, .baseMipLevel = 0, .levelCount = 1, - .baseArrayLayer = uint32_t(channels), + .baseArrayLayer = stream_idx, .layerCount = 1}, }; - if (rect.offset != vk::Offset2D{0, 0} or not vk.vk.features.video_maintenance_1) + if (not vk.vk.features.video_maintenance_1) { image_view_template.subresourceRange.baseArrayLayer = 0; for (size_t i = 0; i < num_slots; ++i) @@ -386,8 +383,8 @@ void wivrn::video_encoder_vulkan::init(const vk::VideoCapabilitiesKHR & video_ca .imageType = vk::ImageType::e2D, .format = picture_format.format, .extent = { - .width = rect.extent.width, - .height = rect.extent.height, + .width = extent.width, + .height = extent.height, .depth = 1, }, .mipLevels = 1, @@ -444,7 +441,7 @@ void wivrn::video_encoder_vulkan::init(const vk::VideoCapabilitiesKHR & video_ca dpb.items.push_back({ .image_view = std::move(v), .resource = { - .codedExtent = rect.extent, + .codedExtent = extent, .imageViewBinding = v1, }, .info = dpb.infos[i], @@ -650,44 +647,34 @@ std::pair wivrn::video_encoder_vulkan::present_image(vk::Im vk::ImageCopy{ .srcSubresource = { .aspectMask = vk::ImageAspectFlagBits::ePlane0, - .baseArrayLayer = uint32_t(channels), + .baseArrayLayer = stream_idx, .layerCount = 1, }, - .srcOffset = { - .x = rect.offset.x, - .y = rect.offset.y, - .z = 0, - }, .dstSubresource = { .aspectMask = vk::ImageAspectFlagBits::ePlane0, .baseArrayLayer = 0, .layerCount = 1, }, .extent = { - .width = rect.extent.width, - .height = rect.extent.height, + .width = extent.width, + .height = extent.height, .depth = 1, }, }, vk::ImageCopy{ .srcSubresource = { .aspectMask = vk::ImageAspectFlagBits::ePlane1, - .baseArrayLayer = uint32_t(channels), + .baseArrayLayer = stream_idx, .layerCount = 1, }, - .srcOffset = { - .x = rect.offset.x / 2, - .y = rect.offset.y / 2, - .z = 0, - }, .dstSubresource = { .aspectMask = vk::ImageAspectFlagBits::ePlane1, .baseArrayLayer = 0, .layerCount = 1, }, .extent = { - .width = rect.extent.width / 2, - .height = rect.extent.height / 2, + .width = extent.width / 2, + .height = extent.height / 2, .depth = 1, }, }, diff --git a/server/encoder/video_encoder_vulkan.h b/server/encoder/video_encoder_vulkan.h index 234394d9..c0ac4ac9 100644 --- a/server/encoder/video_encoder_vulkan.h +++ b/server/encoder/video_encoder_vulkan.h @@ -66,7 +66,6 @@ class video_encoder_vulkan : public video_encoder const vk::PhysicalDeviceVideoFormatInfoKHR &); bool session_initialized = false; - const vk::Rect2D rect; protected: const uint8_t num_dpb_slots; @@ -75,10 +74,8 @@ protected: std::optional rate_control; video_encoder_vulkan(wivrn_vk_bundle & vk, - vk::Rect2D rect, const vk::VideoCapabilitiesKHR & video_caps, const vk::VideoEncodeCapabilitiesKHR & encode_caps, - float fps, uint8_t stream_idx, const encoder_settings & settings); diff --git a/server/encoder/video_encoder_vulkan_h264.cpp b/server/encoder/video_encoder_vulkan_h264.cpp index 47b99852..928491a9 100644 --- a/server/encoder/video_encoder_vulkan_h264.cpp +++ b/server/encoder/video_encoder_vulkan_h264.cpp @@ -71,13 +71,11 @@ static StdVideoH264LevelIdc compute_level(const StdVideoH264SequenceParameterSet wivrn::video_encoder_vulkan_h264::video_encoder_vulkan_h264( wivrn_vk_bundle & vk, - vk::Rect2D rect, const vk::VideoCapabilitiesKHR & video_caps, const vk::VideoEncodeCapabilitiesKHR & encode_caps, - float fps, uint8_t stream_idx, const encoder_settings & settings) : - video_encoder_vulkan(vk, rect, video_caps, encode_caps, fps, stream_idx, settings), + video_encoder_vulkan(vk, video_caps, encode_caps, stream_idx, settings), sps{ .flags = { @@ -94,7 +92,7 @@ wivrn::video_encoder_vulkan_h264::video_encoder_vulkan_h264( .separate_colour_plane_flag = 0, .gaps_in_frame_num_value_allowed_flag = 0, .qpprime_y_zero_transform_bypass_flag = 0, - .frame_cropping_flag = (rect.extent.width % 16) || (rect.extent.height) % 16, + .frame_cropping_flag = (extent.width % 16) || (extent.height) % 16, .seq_scaling_matrix_present_flag = 0, .vui_parameters_present_flag = 0, }, @@ -112,12 +110,12 @@ wivrn::video_encoder_vulkan_h264::video_encoder_vulkan_h264( .num_ref_frames_in_pic_order_cnt_cycle = 0, .max_num_ref_frames = uint8_t(num_dpb_slots - 1), .reserved1 = 0, - .pic_width_in_mbs_minus1 = (rect.extent.width - 1) / 16, - .pic_height_in_map_units_minus1 = (rect.extent.height - 1) / 16, + .pic_width_in_mbs_minus1 = (extent.width - 1) / 16, + .pic_height_in_map_units_minus1 = (extent.height - 1) / 16, .frame_crop_left_offset = 0, - .frame_crop_right_offset = (rect.extent.width % 16) / 2, + .frame_crop_right_offset = (extent.width % 16) / 2, .frame_crop_top_offset = 0, - .frame_crop_bottom_offset = (rect.extent.height % 16) / 2, + .frame_crop_bottom_offset = (extent.height % 16) / 2, .reserved2 = 0, .pOffsetForRefFrame = nullptr, .pScalingLists = nullptr, @@ -147,7 +145,7 @@ wivrn::video_encoder_vulkan_h264::video_encoder_vulkan_h264( .pScalingLists = nullptr, } { - sps.level_idc = compute_level(sps, fps, num_dpb_slots, settings.bitrate); + sps.level_idc = compute_level(sps, settings.fps, num_dpb_slots, settings.bitrate); if (not std::ranges::any_of(vk.device_extensions, [](std::string_view ext) { return ext == VK_KHR_VIDEO_ENCODE_H264_EXTENSION_NAME; })) { throw std::runtime_error("Vulkan video encode H264 extension not available"); @@ -213,27 +211,15 @@ auto get_video_caps(vk::raii::PhysicalDevice & phys_dev) std::unique_ptr wivrn::video_encoder_vulkan_h264::create( wivrn_vk_bundle & vk, - encoder_settings & settings, - float fps, + const encoder_settings & settings, uint8_t stream_idx) { - vk::Rect2D rect{ - .offset = { - .x = settings.offset_x, - .y = settings.offset_y, - }, - .extent = { - .width = settings.width, - .height = settings.height, - }, - }; - if (settings.bit_depth != 8) throw std::runtime_error("h264 codec only supports 8-bit encoding"); auto [video_caps, encode_caps, encode_h264_caps, video_profile_info] = get_video_caps(vk.physical_device); - std::unique_ptr self(new video_encoder_vulkan_h264(vk, rect, video_caps, encode_caps, fps, stream_idx, settings)); + std::unique_ptr self(new video_encoder_vulkan_h264(vk, video_caps, encode_caps, stream_idx, settings)); vk::VideoEncodeH264SessionParametersAddInfoKHR h264_add_info{}; h264_add_info.setStdSPSs(self->sps); diff --git a/server/encoder/video_encoder_vulkan_h264.h b/server/encoder/video_encoder_vulkan_h264.h index a98b7b05..dc4dd90e 100644 --- a/server/encoder/video_encoder_vulkan_h264.h +++ b/server/encoder/video_encoder_vulkan_h264.h @@ -49,10 +49,8 @@ class video_encoder_vulkan_h264 : public video_encoder_vulkan vk::VideoEncodeH264RateControlLayerInfoKHR rate_control_layer_h264; video_encoder_vulkan_h264(wivrn_vk_bundle & vk, - vk::Rect2D rect, const vk::VideoCapabilitiesKHR & video_caps, const vk::VideoEncodeCapabilitiesKHR & encode_caps, - float fps, uint8_t stream_idx, const encoder_settings & settings); @@ -66,8 +64,7 @@ protected: public: static std::unique_ptr create(wivrn_vk_bundle & vk, - encoder_settings & settings, - float fps, + const encoder_settings & settings, uint8_t stream_idx); std::vector get_sps_pps(); diff --git a/server/encoder/video_encoder_vulkan_h265.cpp b/server/encoder/video_encoder_vulkan_h265.cpp index 9030e974..6b9826ec 100644 --- a/server/encoder/video_encoder_vulkan_h265.cpp +++ b/server/encoder/video_encoder_vulkan_h265.cpp @@ -61,13 +61,11 @@ static uint32_t find_msb(uint32_t v) wivrn::video_encoder_vulkan_h265::video_encoder_vulkan_h265( wivrn_vk_bundle & vk, - vk::Rect2D rect, const vk::VideoCapabilitiesKHR & video_caps, const vk::VideoEncodeCapabilitiesKHR & encode_caps, - float fps, uint8_t stream_idx, const encoder_settings & settings) : - video_encoder_vulkan(vk, rect, video_caps, encode_caps, fps, stream_idx, settings), + video_encoder_vulkan(vk, video_caps, encode_caps, stream_idx, settings), vui{ .flags = { .aspect_ratio_info_present_flag = 1, @@ -97,7 +95,7 @@ wivrn::video_encoder_vulkan_h265::video_encoder_vulkan_h265( .general_frame_only_constraint_flag = 1, }, .general_profile_idc = (settings.bit_depth == 10) ? STD_VIDEO_H265_PROFILE_IDC_MAIN_10 : STD_VIDEO_H265_PROFILE_IDC_MAIN, - .general_level_idc = choose_level(rect.extent.width, rect.extent.height, fps)}, + .general_level_idc = choose_level(extent.width, extent.height, settings.fps)}, vps{ .flags = { .vps_temporal_id_nesting_flag = 1, // radv breaks without @@ -150,9 +148,9 @@ wivrn::video_encoder_vulkan_h265::video_encoder_vulkan_h265( .motion_vector_resolution_control_idc = 0, .sps_num_palette_predictor_initializers_minus1 = 0, .conf_win_left_offset = 0u, - .conf_win_right_offset = (aligned_extent.width - rect.extent.width) >> 1, // 4:2:0 + .conf_win_right_offset = (aligned_extent.width - extent.width) >> 1, // 4:2:0 .conf_win_top_offset = 0u, - .conf_win_bottom_offset = (aligned_extent.height - rect.extent.height) >> 1, // 4:2:0 + .conf_win_bottom_offset = (aligned_extent.height - extent.height) >> 1, // 4:2:0 .pProfileTierLevel = &ptl, .pDecPicBufMgr = &dpb, .pScalingLists = nullptr, @@ -272,19 +270,13 @@ static auto get_video_caps(vk::raii::PhysicalDevice & phys_dev, int bit_depth) std::unique_ptr wivrn::video_encoder_vulkan_h265::create( wivrn_vk_bundle & vk, - encoder_settings & settings, - float fps, + const encoder_settings & settings, uint8_t stream_idx) { - vk::Rect2D rect{ - .offset = {.x = settings.offset_x, .y = settings.offset_y}, - .extent = {.width = settings.width, .height = settings.height}, - }; - auto [video_caps, encode_caps, encode_h265_caps, video_profile_info] = get_video_caps(vk.physical_device, settings.bit_depth); std::unique_ptr self( - new video_encoder_vulkan_h265(vk, rect, video_caps, encode_caps, fps, stream_idx, settings)); + new video_encoder_vulkan_h265(vk, video_caps, encode_caps, stream_idx, settings)); vk::VideoEncodeH265SessionParametersAddInfoKHR add_info{}; add_info.setStdVPSs(self->vps); diff --git a/server/encoder/video_encoder_vulkan_h265.h b/server/encoder/video_encoder_vulkan_h265.h index 83680526..3dd2d193 100644 --- a/server/encoder/video_encoder_vulkan_h265.h +++ b/server/encoder/video_encoder_vulkan_h265.h @@ -60,10 +60,8 @@ class video_encoder_vulkan_h265 : public video_encoder_vulkan vk::VideoEncodeH265RateControlLayerInfoKHR rc_layer_h265{}; video_encoder_vulkan_h265(wivrn_vk_bundle & vk, - vk::Rect2D rect, const vk::VideoCapabilitiesKHR & video_caps, const vk::VideoEncodeCapabilitiesKHR & encode_caps, - float fps, uint8_t stream_idx, const encoder_settings & settings); @@ -77,8 +75,7 @@ protected: public: static std::unique_ptr create(wivrn_vk_bundle & vk, - encoder_settings & settings, - float fps, + const encoder_settings & settings, uint8_t stream_idx); std::vector get_vps_sps_pps(); diff --git a/server/encoder/video_encoder_x264.cpp b/server/encoder/video_encoder_x264.cpp index 4d88e663..1efadb85 100644 --- a/server/encoder/video_encoder_x264.cpp +++ b/server/encoder/video_encoder_x264.cpp @@ -88,47 +88,29 @@ void video_encoder_x264::InsertInPendingNal(pending_nal && nal) video_encoder_x264::video_encoder_x264( wivrn_vk_bundle & vk, - encoder_settings & settings, - float fps, + const encoder_settings & settings, uint8_t stream_idx) : - video_encoder(stream_idx, settings.channels, std::make_unique(), settings.bitrate_multiplier, false) + video_encoder(stream_idx, settings, std::make_unique(), false) { if (settings.bit_depth != 8) throw std::runtime_error("x264 encoder only supports 8-bit encoding"); if (settings.codec != h264) - { U_LOG_W("requested x264 encoder with codec != h264"); - settings.codec = h264; - } // encoder requires width and height to be even - settings.video_width += settings.video_width % 2; - settings.video_height += settings.video_height % 2; - chroma_width = settings.video_width / 2; + chroma_width = extent.width / 2; - // FIXME: enforce even values - rect = vk::Rect2D{ - .offset = { - .x = settings.offset_x, - .y = settings.offset_y, - }, - .extent = { - .width = settings.width, - .height = settings.height, - }, - }; - - num_mb = ((settings.video_width + 15) / 16) * ((settings.video_height + 15) / 16); + num_mb = ((extent.width + 15) / 16) * ((extent.height + 15) / 16); x264_param_default_preset(¶m, "ultrafast", "zerolatency"); param.nalu_process = &ProcessCb; // param.i_slice_max_size = 1300; param.i_slice_count = 32; - param.i_width = settings.video_width; - param.i_height = settings.video_height; + param.i_width = extent.width; + param.i_height = extent.height; param.i_log_level = X264_LOG_WARNING; - param.i_fps_num = fps * 1'000'000; + param.i_fps_num = settings.fps * 1'000'000; param.i_fps_den = 1'000'000; param.b_repeat_headers = 1; param.b_aud = 0; @@ -140,12 +122,12 @@ video_encoder_x264::video_encoder_x264( param.vui.i_colmatrix = 1; // BT.709 param.vui.i_transfer = 13; // sRGB - param.vui.i_sar_width = settings.width; - param.vui.i_sar_height = settings.height; + param.vui.i_sar_width = extent.width; + param.vui.i_sar_height = extent.height; param.rc.i_rc_method = X264_RC_ABR; param.rc.i_bitrate = settings.bitrate / 1000; // x264 uses kbit/s param.rc.i_vbv_max_bitrate = param.rc.i_bitrate; - param.rc.i_vbv_buffer_size = param.rc.i_bitrate / fps * 1.1; + param.rc.i_vbv_buffer_size = param.rc.i_bitrate / settings.fps * 1.1; x264_param_apply_profile(¶m, "main"); @@ -162,7 +144,7 @@ video_encoder_x264::video_encoder_x264( i.luma = buffer_allocation( vk.device, { - .size = vk::DeviceSize(settings.video_width * settings.video_height), + .size = vk::DeviceSize(extent.width * extent.height), .usage = vk::BufferUsageFlagBits::eTransferDst, }, { @@ -172,7 +154,7 @@ video_encoder_x264::video_encoder_x264( "x264 luma buffer"); i.chroma = buffer_allocation( vk.device, { - .size = vk::DeviceSize(settings.video_width * settings.video_height / 2), + .size = vk::DeviceSize(extent.width * extent.height / 2), .usage = vk::BufferUsageFlagBits::eTransferDst, }, { @@ -187,9 +169,9 @@ video_encoder_x264::video_encoder_x264( pic.img.i_csp = X264_CSP_NV12; pic.img.i_plane = 2; - pic.img.i_stride[0] = settings.video_width; + pic.img.i_stride[0] = extent.width; pic.img.plane[0] = (uint8_t *)i.luma.map(); - pic.img.i_stride[1] = settings.video_width; + pic.img.i_stride[1] = extent.width; pic.img.plane[1] = (uint8_t *)i.chroma.map(); } } @@ -204,16 +186,12 @@ std::pair video_encoder_x264::present_image(vk::Image y_cbc .bufferRowLength = chroma_width * 2, .imageSubresource = { .aspectMask = vk::ImageAspectFlagBits::ePlane0, - .baseArrayLayer = uint32_t(channels), + .baseArrayLayer = stream_idx, .layerCount = 1, }, - .imageOffset = { - .x = rect.offset.x, - .y = rect.offset.y, - }, .imageExtent = { - .width = rect.extent.width, - .height = rect.extent.height, + .width = extent.width, + .height = extent.height, .depth = 1, }}); cmd_buf.copyImageToBuffer( @@ -224,16 +202,12 @@ std::pair video_encoder_x264::present_image(vk::Image y_cbc .bufferRowLength = chroma_width, .imageSubresource = { .aspectMask = vk::ImageAspectFlagBits::ePlane1, - .baseArrayLayer = uint32_t(channels), + .baseArrayLayer = stream_idx, .layerCount = 1, }, - .imageOffset = { - .x = rect.offset.x / 2, - .y = rect.offset.y / 2, - }, .imageExtent = { - .width = rect.extent.width / 2, - .height = rect.extent.height / 2, + .width = extent.width / 2, + .height = extent.height / 2, .depth = 1, }}); return {false, nullptr}; diff --git a/server/encoder/video_encoder_x264.h b/server/encoder/video_encoder_x264.h index 3e1f9b31..36b4c99a 100644 --- a/server/encoder/video_encoder_x264.h +++ b/server/encoder/video_encoder_x264.h @@ -47,8 +47,6 @@ class video_encoder_x264 : public video_encoder std::array in; uint32_t chroma_width; - vk::Rect2D rect; - struct pending_nal { int first_mb; @@ -62,7 +60,7 @@ class video_encoder_x264 : public video_encoder std::list pending_nals; public: - video_encoder_x264(wivrn_vk_bundle & vk, encoder_settings & settings, float fps, uint8_t stream_idx); + video_encoder_x264(wivrn_vk_bundle & vk, const encoder_settings & settings, 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;