Move client/src/* to client/*

This commit is contained in:
Guillaume Meunier
2022-11-17 08:25:25 +01:00
parent ab2dd07105
commit f431543b47
81 changed files with 0 additions and 0 deletions
+849
View File
@@ -0,0 +1,849 @@
/*
* WiVRn VR streaming
* Copyright (C) 2022 Guillaume Meunier <guillaume.meunier@centraliens.net>
* Copyright (C) 2022 Patrick Nicolas <patricknicolas@laposte.net>
*
* 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 <https://www.gnu.org/licenses/>.
*/
#include "android_decoder.h"
#include "application.h"
#include "scenes/stream.h"
#include "utils/check.h"
#include "vk/device_memory.h"
#include <algorithm>
#include <android/hardware_buffer.h>
#include <cassert>
#include <chrono>
#include <media/NdkImage.h>
#include <media/NdkImageReader.h>
#include <media/NdkMediaCodec.h>
#include <media/NdkMediaFormat.h>
#include <mutex>
#include <spdlog/spdlog.h>
#include <thread>
#include <vulkan/vulkan_android.h>
#include <vulkan/vulkan_core.h>
#include "external/magic_enum.hpp"
DEUGLIFY(AMediaFormat)
struct wivrn::android::decoder::pipeline_context
{
VkDevice device;
VkAndroidHardwareBufferFormatPropertiesANDROID ahb_format;
VkSamplerYcbcrConversion ycbcr_conversion;
VkSampler sampler;
std::vector<VkFramebuffer> framebuffers;
VkDescriptorSetLayout descriptor_set_layout;
VkDescriptorPool descriptor_pool;
std::mutex descriptor_pool_mutex;
vk::pipeline_layout layout;
vk::pipeline pipeline;
~pipeline_context()
{
vkDestroyDescriptorPool(device, descriptor_pool, nullptr);
vkDestroyDescriptorSetLayout(device, descriptor_set_layout, nullptr);
vkDestroySampler(device, sampler, nullptr);
vkDestroySamplerYcbcrConversion(device, ycbcr_conversion, nullptr);
}
pipeline_context(VkDevice device, VkAndroidHardwareBufferFormatPropertiesANDROID & ahb_format, VkRenderPass renderpass, const to_headset::video_stream_description::item& description) :
device(device), ahb_format(ahb_format)
{
assert(ahb_format.externalFormat != 0);
spdlog::info("AndroidHardwareBufferProperties");
spdlog::info(" Vulkan format: {}", magic_enum::enum_name(ahb_format.format));
spdlog::info(" External format: {:#x}", ahb_format.externalFormat);
spdlog::info(" Format features: {:#x}", ahb_format.formatFeatures);
spdlog::info(" samplerYcbcrConversionComponents: ({}, {}, {}, {})",
magic_enum::enum_name(ahb_format.samplerYcbcrConversionComponents.r),
magic_enum::enum_name(ahb_format.samplerYcbcrConversionComponents.g),
magic_enum::enum_name(ahb_format.samplerYcbcrConversionComponents.b),
magic_enum::enum_name(ahb_format.samplerYcbcrConversionComponents.a));
spdlog::info(" Suggested YCbCr model: {}", magic_enum::enum_name(ahb_format.suggestedYcbcrModel));
spdlog::info(" Suggested YCbCr range: {}", magic_enum::enum_name(ahb_format.suggestedYcbcrRange));
spdlog::info(" Suggested X chroma offset: {}", magic_enum::enum_name(ahb_format.suggestedXChromaOffset));
spdlog::info(" Suggested Y chroma offset: {}", magic_enum::enum_name(ahb_format.suggestedYChromaOffset));
VkFilter yuv_filter;
if (ahb_format.formatFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_LINEAR_FILTER_BIT)
yuv_filter = VK_FILTER_LINEAR;
else
yuv_filter = VK_FILTER_NEAREST;
// Create VkSamplerYcbcrConversion
VkExternalFormatANDROID ycbcr_create_info2{.sType = VK_STRUCTURE_TYPE_EXTERNAL_FORMAT_ANDROID,
.externalFormat = ahb_format.externalFormat};
VkSamplerYcbcrConversionCreateInfo ycbcr_create_info{
.sType = VK_STRUCTURE_TYPE_SAMPLER_YCBCR_CONVERSION_CREATE_INFO,
.pNext = &ycbcr_create_info2,
.format = VK_FORMAT_UNDEFINED,
.ycbcrModel = ahb_format.suggestedYcbcrModel,
.ycbcrRange = ahb_format.suggestedYcbcrRange,
.components = ahb_format.samplerYcbcrConversionComponents,
.xChromaOffset = ahb_format.suggestedXChromaOffset,
.yChromaOffset = ahb_format.suggestedYChromaOffset,
.chromaFilter = yuv_filter,
};
// suggested values from decoder don't actually read the metadata, so it's garbage
if (description.range)
ycbcr_create_info.ycbcrRange = VkSamplerYcbcrRange(*description.range);
if (description.color_model)
ycbcr_create_info.ycbcrModel = VkSamplerYcbcrModelConversion(*description.color_model);
CHECK_VK(vkCreateSamplerYcbcrConversion(device, &ycbcr_create_info, nullptr, &ycbcr_conversion));
// Create VkSampler
VkSamplerYcbcrConversionInfo sampler_info2{
.sType = VK_STRUCTURE_TYPE_SAMPLER_YCBCR_CONVERSION_INFO,
.conversion = ycbcr_conversion,
};
VkSamplerCreateInfo sampler_info{
.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO,
.pNext = &sampler_info2,
.magFilter = yuv_filter,
.minFilter = yuv_filter,
.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST,
.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
.addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
.mipLodBias = 0.0f,
.anisotropyEnable = VK_FALSE,
.maxAnisotropy = 1,
.compareEnable = VK_FALSE,
.compareOp = VK_COMPARE_OP_NEVER,
.minLod = 0.0f,
.maxLod = 0.0f,
.borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE, // TODO TBC
.unnormalizedCoordinates = VK_FALSE,
};
CHECK_VK(vkCreateSampler(device, &sampler_info, nullptr, &sampler));
// Create VkDescriptorSetLayout with an immutable sampler
VkDescriptorSetLayoutBinding samplerLayoutBinding{
.binding = 0,
.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
.descriptorCount = 1,
.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT,
.pImmutableSamplers = &sampler,
};
VkDescriptorSetLayoutCreateInfo layoutInfo{
.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO,
.bindingCount = 1,
.pBindings = &samplerLayoutBinding,
};
CHECK_VK(vkCreateDescriptorSetLayout(device, &layoutInfo, nullptr, &descriptor_set_layout));
VkDescriptorPoolSize poolSize{};
poolSize.type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
poolSize.descriptorCount = 100;
VkDescriptorPoolCreateInfo poolInfo{};
poolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
poolInfo.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT;
poolInfo.poolSizeCount = 1;
poolInfo.pPoolSizes = &poolSize;
poolInfo.maxSets = poolSize.descriptorCount;
CHECK_VK(vkCreateDescriptorPool(device, &poolInfo, nullptr, &descriptor_pool));
// Create graphics pipeline
vk::shader vertex_shader(device, "stream.vert");
vk::shader fragment_shader(device, "stream.frag");
VkPipelineColorBlendAttachmentState pcbas{};
pcbas.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT;
layout = vk::pipeline_layout(
device, {.descriptor_set_layouts = {descriptor_set_layout}});
vk::pipeline::graphics_info pipeline_info{
.shader_stages =
{{.stage = VK_SHADER_STAGE_VERTEX_BIT, .module = vertex_shader, .pName = "main"},
{.stage = VK_SHADER_STAGE_FRAGMENT_BIT, .module = fragment_shader, .pName = "main"}},
.vertex_input_bindings = {},
.vertex_input_attributes = {},
.InputAssemblyState = {.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP},
.viewports = {{}},
.scissors = {{}},
.RasterizationState = {.polygonMode = VK_POLYGON_MODE_FILL, .lineWidth = 1},
.MultisampleState = {.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT},
.ColorBlendState = {.attachmentCount = 1, .pAttachments = &pcbas},
.dynamic_states = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR},
.renderPass = renderpass,
.subpass = 0,
};
pipeline = vk::pipeline(device, pipeline_info, layout);
}
};
struct wivrn::android::decoder::mapped_hardware_buffer
{
std::shared_ptr<pipeline_context> pipeline;
VkImageView image_view{};
VkImage vimage{};
VkDeviceMemory memory{};
VkDescriptorSet descriptor_set{};
VkImageLayout layout = VK_IMAGE_LAYOUT_UNDEFINED;
~mapped_hardware_buffer()
{
assert(pipeline);
auto device = pipeline->device;
{
std::unique_lock lock(pipeline->descriptor_pool_mutex);
vkFreeDescriptorSets(device, pipeline->descriptor_pool, 1, &descriptor_set);
}
vkDestroyImageView(device, image_view, nullptr);
vkFreeMemory(device, memory, nullptr);
vkDestroyImage(device, vimage, nullptr);
}
};
namespace
{
const char * mime(xrt::drivers::wivrn::video_codec codec)
{
using c = xrt::drivers::wivrn::video_codec;
switch (codec)
{
case c::h264:
return "video/avc";
case c::h265:
return "video/hevc";
}
assert(false);
}
void check(media_status_t status, const char * msg)
{
if (status != AMEDIA_OK)
{
spdlog::error("{}: MediaCodec error {}", msg, (int)status);
throw std::runtime_error("MediaCodec error");
}
}
namespace nal_h264
{
static const int sps = 7;
static const int pps = 8;
} // namespace nal_h264
namespace nal_h265
{
static const int vps = 32;
static const int sps = 33;
static const int pps = 34;
static const int aud = 35;
static const int filler = 38;
}; // namespace nal_h265
enum class nal_class
{
csd,
data,
garbage
};
nal_class get_nal_class_h264(uint8_t * nal)
{
uint8_t nal_type = (nal[2] == 0 ? nal[4] : nal[3]) & 0x1F;
// spdlog::info("H264 NAL type {}", (int)nal_type);
switch (nal_type)
{
case nal_h264::sps:
case nal_h264::pps:
return nal_class::csd;
default:
return nal_class::data;
}
}
nal_class get_nal_class_h265(uint8_t * nal)
{
uint8_t nal_type = ((nal[2] == 0 ? nal[4] : nal[3]) >> 1) & 0x3F;
// spdlog::info("H265 NAL type {}", (int)nal_type);
switch (nal_type)
{
case nal_h265::vps:
case nal_h265::sps:
case nal_h265::pps:
return nal_class::csd;
case nal_h265::aud:
case nal_h265::filler:
return nal_class::garbage;
default:
return nal_class::data;
}
}
nal_class get_nal_class(uint8_t * nal, xrt::drivers::wivrn::video_codec codec)
{
switch (codec)
{
case xrt::drivers::wivrn::video_codec::h264:
return get_nal_class_h264(nal);
case xrt::drivers::wivrn::video_codec::h265:
return get_nal_class_h265(nal);
}
}
std::pair<std::vector<uint8_t>, std::vector<uint8_t>> filter_csd(std::span<uint8_t> packet,
xrt::drivers::wivrn::video_codec codec)
{
if (packet.size() < 4)
return {};
std::array<uint8_t, 3> header = {{0, 0, 1}};
auto end = packet.end();
auto header_start = packet.begin();
std::pair<std::vector<uint8_t>, std::vector<uint8_t>> out;
while (header_start != end)
{
auto next_header = std::search(header_start + 3, end, header.begin(), header.end());
if (next_header != end and next_header[-1] == 0)
{
next_header--;
}
switch (get_nal_class(&*header_start, codec))
{
case nal_class::csd:
out.first.insert(out.first.end(), header_start, next_header);
break;
case nal_class::data:
out.second.insert(out.second.end(), header_start, next_header);
break;
case nal_class::garbage:
break;
}
header_start = next_header;
}
return out;
}
} // namespace
namespace wivrn::android
{
void decoder::push_nals(std::span<uint8_t> data, int64_t timestamp, uint32_t flags)
{
while (!data.empty())
{
auto t1 = application::now();
auto input_buffer = input_buffers.pop();
auto t2 = application::now();
assert(input_buffer >= 0);
if (t2 - t1 > 1'000'000)
spdlog::warn("input_buffers.pop() took {}µs", (t2 - t1) / 1000);
size_t size;
t1 = application::now();
uint8_t * buffer = AMediaCodec_getInputBuffer(media_codec.get(), input_buffer, &size);
t2 = application::now();
if (t2 - t1 > 1'000'000)
spdlog::warn("AMediaCodec_getInputBuffer() took {}µs", (t2 - t1) / 1000);
size = std::min(data.size(), size);
memcpy(buffer, data.data(), size);
data = data.subspan(size);
t1 = application::now();
check(AMediaCodec_queueInputBuffer(media_codec.get(), input_buffer, 0 /* offset */, size, timestamp, flags),
"AMediaCodec_queueInputBuffer");
t2 = application::now();
if (t2 - t1 > 1'000'000)
spdlog::warn("AMediaCodec_queueInputBuffer() took {}µs", (t2 - t1) / 1000);
}
}
decoder::decoder(
VkDevice device,
VkPhysicalDevice physical_device,
const xrt::drivers::wivrn::to_headset::video_stream_description::item & description,
float fps,
std::weak_ptr<scenes::stream> weak_scene,
shard_accumulator * accumulator) :
description(description), fps(fps), device(device), weak_scene(weak_scene), accumulator(accumulator)
{
AImageReader * ir;
check(AImageReader_newWithUsage(description.width, description.height, AIMAGE_FORMAT_PRIVATE, AHARDWAREBUFFER_USAGE_CPU_READ_NEVER | AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE, 5 /* maxImages */, &ir),
"AImageReader_newWithUsage");
image_reader.reset(ir);
AImageReader_ImageListener listener{this, on_image_available};
check(AImageReader_setImageListener(ir, &listener), "AImageReader_setImageListener");
vkGetAndroidHardwareBufferPropertiesANDROID =
application::get_vulkan_proc<PFN_vkGetAndroidHardwareBufferPropertiesANDROID>(
"vkGetAndroidHardwareBufferPropertiesANDROID");
output_releaser = std::thread([this]() {
while (true)
{
try
{
auto index = output_buffers.pop();
auto status = AMediaCodec_releaseOutputBuffer(media_codec.get(), index, true);
// will trigger on_image_available through ImageReader
if (status != AMEDIA_OK)
spdlog::error("AMediaCodec_releaseOutputBuffer: MediaCodec error {}",
(int)status);
}
catch (const utils::sync_queue_closed & e)
{
return;
}
catch (const std::exception & e)
{
spdlog::error("error in output releaser thread: {}", e.what());
}
}
});
}
decoder::~decoder()
{
input_buffers.close();
output_buffers.close();
output_releaser.join();
for (auto & i: blit_targets)
vkDestroyFramebuffer(device, i.framebuffer, nullptr);
}
void decoder::set_blit_targets(std::vector<decoder::blit_target> targets, VkFormat format)
{
// Create renderpass
VkAttachmentReference color_ref{.attachment = 0, .layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL};
vk::renderpass::info renderpass_info{.attachments = {VkAttachmentDescription{
.format = format,
.samples = VK_SAMPLE_COUNT_1_BIT,
.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD,
.storeOp = VK_ATTACHMENT_STORE_OP_STORE,
.initialLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
.finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
}},
.subpasses = {VkSubpassDescription{
.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS,
.colorAttachmentCount = 1,
.pColorAttachments = &color_ref,
}},
.dependencies = {}};
renderpass = vk::renderpass(device, renderpass_info);
// Remove old blit targets first
for (auto & i: blit_targets)
vkDestroyFramebuffer(device, i.framebuffer, nullptr);
blit_targets = std::move(targets);
for (auto & i: blit_targets)
{
VkFramebufferCreateInfo fb_create_info{};
fb_create_info.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
fb_create_info.renderPass = renderpass;
fb_create_info.attachmentCount = 1;
fb_create_info.pAttachments = &i.image_view;
fb_create_info.width = i.extent.width;
fb_create_info.height = i.extent.height;
fb_create_info.layers = 1;
CHECK_VK(vkCreateFramebuffer(device, &fb_create_info, nullptr, &i.framebuffer));
}
}
void decoder::push_data(std::span<uint8_t> data, uint64_t frame_index, bool partial)
{
auto [csd, not_csd] = filter_csd(data, description.codec);
if (!media_codec)
{
if (csd.empty())
{
// TODO request I frame
return;
}
AMediaFormat_ptr format(AMediaFormat_new());
AMediaFormat_setString(format.get(), AMEDIAFORMAT_KEY_MIME, mime(description.codec));
// AMediaFormat_setInt32(format.get(), "vendor.qti-ext-dec-low-latency.enable", 1); // Qualcomm low
// latency mode
AMediaFormat_setInt32(format.get(), AMEDIAFORMAT_KEY_WIDTH, description.width);
AMediaFormat_setInt32(format.get(), AMEDIAFORMAT_KEY_HEIGHT, description.height);
AMediaFormat_setInt32(format.get(), AMEDIAFORMAT_KEY_OPERATING_RATE, std::ceil(fps));
AMediaFormat_setInt32(format.get(), AMEDIAFORMAT_KEY_PRIORITY, 0);
// AMediaFormat_setBuffer(format.get(), AMEDIAFORMAT_KEY_CSD_0, csd.data(), csd.size());
media_codec.reset(AMediaCodec_createDecoderByType(mime(description.codec)));
char * codec_name;
check(AMediaCodec_getName(media_codec.get(), &codec_name), "AMediaCodec_getName");
spdlog::info("Created MediaCodec decoder \"{}\"", codec_name);
AMediaCodec_releaseName(media_codec.get(), codec_name);
ANativeWindow * window;
check(AImageReader_getWindow(image_reader.get(), &window), "AImageReader_getWindow");
AMediaCodecOnAsyncNotifyCallback callback{
.onAsyncInputAvailable = decoder::on_media_input_available,
.onAsyncOutputAvailable = decoder::on_media_output_available,
.onAsyncFormatChanged = decoder::on_media_format_changed,
.onAsyncError = decoder::on_media_error,
};
check(AMediaCodec_setAsyncNotifyCallback(media_codec.get(), callback, this),
"AMediaCodec_setAsyncNotifyCallback");
check(AMediaCodec_configure(media_codec.get(), format.get(), window, nullptr /* crypto */, 0 /* flags */),
"AMediaCodec_configure");
check(AMediaCodec_start(media_codec.get()), "AMediaCodec_start");
}
if (!csd.empty())
push_nals(csd, 0, AMEDIACODEC_BUFFER_FLAG_CODEC_CONFIG);
uint64_t fake_timestamp_us = frame_index * 10'000;
push_nals(not_csd, fake_timestamp_us, partial ? AMEDIACODEC_BUFFER_FLAG_PARTIAL_FRAME : 0);
}
void decoder::frame_completed(xrt::drivers::wivrn::from_headset::feedback & feedback, const xrt::drivers::wivrn::to_headset::video_stream_data_shard::view_info_t & view_info)
{
// nothing required for decoder, mediacodec will callback when done
feedback.sent_to_decoder = application::now();
frame_infos.push(std::make_pair(feedback, view_info));
}
void decoder::on_image_available(void * context, AImageReader * reader)
{
try
{
static_cast<decoder *>(context)->on_image_available(reader);
}
catch (std::exception & e)
{
spdlog::error("Exception in decoder::on_image_available: {}", e.what());
}
}
void decoder::on_image_available(AImageReader * reader)
{
assert(reader == image_reader.get());
// Executed on image reader thread
AImage * image = nullptr;
try
{
check(AImageReader_acquireLatestImage(image_reader.get(), &image), "AImageReader_acquireLatestImage");
int64_t fake_timestamp_ns;
check(AImage_getTimestamp(image, &fake_timestamp_ns), "AImage_getTimestamp");
uint64_t frame_index = (fake_timestamp_ns + 5'000'000) / (10'000'000);
frame_infos.drop_until([frame_index](auto & x) { return x.first.frame_index >= frame_index; });
auto info = frame_infos.pop_if([frame_index](auto & x) { return x.first.frame_index == frame_index; });
if (!info)
{
spdlog::warn("No frame info for frame {}, dropping frame", frame_index);
AImage_delete(image);
return;
}
auto [feedback, view_info] = *info;
feedback.received_from_decoder = application::now();
assert(feedback.frame_index == frame_index);
auto handle = std::make_shared<decoder::blit_handle>();
handle->feedback = feedback;
handle->view_info = view_info;
handle->vk_data = map_hardware_buffer(image);
handle->aimage = image;
if (auto scene = weak_scene.lock())
scene->push_blit_handle(accumulator, std::move(handle));
}
catch (...)
{
if (image)
AImage_delete(image);
}
}
std::shared_ptr<decoder::mapped_hardware_buffer> decoder::map_hardware_buffer(AImage * image)
{
AHardwareBuffer * hardware_buffer;
check(AImage_getHardwareBuffer(image, &hardware_buffer), "AImage_getHardwareBuffer");
std::lock_guard lock(hbm_mutex);
AHardwareBuffer_Desc buffer_desc{};
AHardwareBuffer_describe(hardware_buffer, &buffer_desc);
VkAndroidHardwareBufferFormatPropertiesANDROID format_properties{};
format_properties.sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_FORMAT_PROPERTIES_ANDROID;
VkAndroidHardwareBufferPropertiesANDROID properties{};
properties.sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_PROPERTIES_ANDROID;
properties.pNext = &format_properties;
CHECK_VK(vkGetAndroidHardwareBufferPropertiesANDROID(device, hardware_buffer, &properties));
if (!pipeline || memcmp(&pipeline->ahb_format, &format_properties, sizeof(format_properties)))
{
pipeline.reset();
pipeline = std::make_shared<pipeline_context>(device, format_properties, renderpass, description);
hardware_buffer_map.clear();
}
auto it = hardware_buffer_map.find(hardware_buffer);
if (it != hardware_buffer_map.end())
return it->second;
VkExternalFormatANDROID img_info3{.sType = VK_STRUCTURE_TYPE_EXTERNAL_FORMAT_ANDROID,
.externalFormat = format_properties.externalFormat};
VkExternalMemoryImageCreateInfo img_info2{
.sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO,
.pNext = &img_info3,
.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID};
VkImageCreateInfo img_info{.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
.pNext = &img_info2,
.flags = 0,
.imageType = VK_IMAGE_TYPE_2D,
.format = VK_FORMAT_UNDEFINED,
.extent = {buffer_desc.width, buffer_desc.height, 1},
.mipLevels = 1,
.arrayLayers = 1,
.samples = VK_SAMPLE_COUNT_1_BIT,
.tiling = VK_IMAGE_TILING_OPTIMAL,
.usage = VK_IMAGE_USAGE_SAMPLED_BIT,
.sharingMode = VK_SHARING_MODE_EXCLUSIVE,
.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED};
vk::image vimage(device, img_info);
VkImportAndroidHardwareBufferInfoANDROID mem_info3{
.sType = VK_STRUCTURE_TYPE_IMPORT_ANDROID_HARDWARE_BUFFER_INFO_ANDROID,
.buffer = hardware_buffer};
VkMemoryDedicatedAllocateInfo mem_info2{.sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO,
.pNext = &mem_info3,
.image = vimage};
assert(properties.memoryTypeBits != 0);
VkMemoryAllocateInfo mem_info{.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,
.pNext = &mem_info2,
.allocationSize = properties.allocationSize,
.memoryTypeIndex = (uint32_t)(ffs(properties.memoryTypeBits) - 1)};
vk::device_memory memory(device, mem_info);
CHECK_VK(vkBindImageMemory(device, vimage, memory, 0));
VkSamplerYcbcrConversionInfo ycbcr_info{.sType = VK_STRUCTURE_TYPE_SAMPLER_YCBCR_CONVERSION_INFO,
.conversion = pipeline->ycbcr_conversion};
VkImageViewCreateInfo iv_info{
.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
.pNext = &ycbcr_info,
.image = vimage,
.viewType = VK_IMAGE_VIEW_TYPE_2D,
.format = VK_FORMAT_UNDEFINED,
.components = {VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY},
.subresourceRange = {.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
.baseMipLevel = 0,
.levelCount = 1,
.baseArrayLayer = 0,
.layerCount = 1}};
// TODO: vk::image_view
VkImageView image_view;
application::ignore_debug_reports_for(vimage);
CHECK_VK(vkCreateImageView(device, &iv_info, nullptr, &image_view));
application::unignore_debug_reports_for(vimage);
// TODO: vk::descriptor_set
VkDescriptorSet descriptor_set;
VkDescriptorSetAllocateInfo descriptor_info{
.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO,
.descriptorPool = pipeline->descriptor_pool,
.descriptorSetCount = 1,
.pSetLayouts = &pipeline->descriptor_set_layout,
};
{
std::unique_lock lock(pipeline->descriptor_pool_mutex);
CHECK_VK(vkAllocateDescriptorSets(device, &descriptor_info, &descriptor_set));
}
VkDescriptorImageInfo image_info{
.imageView = image_view,
.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
};
VkWriteDescriptorSet descriptor_write{
.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET,
.dstSet = descriptor_set,
.dstBinding = 0,
.dstArrayElement = 0,
.descriptorCount = 1,
.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
.pImageInfo = &image_info,
};
vkUpdateDescriptorSets(device, 1, &descriptor_write, 0, nullptr);
auto handle = std::make_shared<mapped_hardware_buffer>();
handle->pipeline = pipeline;
handle->vimage = vimage.release();
handle->image_view = image_view;
handle->memory = memory.release();
handle->descriptor_set = descriptor_set;
hardware_buffer_map[hardware_buffer] = handle;
return handle;
}
void decoder::on_media_error(AMediaCodec *, void * userdata, media_status_t error, int32_t actionCode, const char * detail)
{
spdlog::warn("Mediacodec error: {}", detail);
}
void decoder::on_media_format_changed(AMediaCodec *, void * userdata, AMediaFormat *)
{
spdlog::info("Mediacodec format changed");
}
void decoder::on_media_input_available(AMediaCodec *, void * userdata, int32_t index)
{
auto self = (decoder *)userdata;
self->input_buffers.push(index);
}
void decoder::on_media_output_available(AMediaCodec * media_codec, void * userdata, int32_t index, AMediaCodecBufferInfo * bufferInfo)
{
auto self = (decoder *)userdata;
self->output_buffers.push(index);
// will be consumed by dedicated thread
}
void decoder::blit(VkCommandBuffer command_buffer, blit_handle & handle, std::span<int> target_indices)
{
if (handle.vk_data->layout != VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL)
{
VkImageMemoryBarrier memory_barrier{.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
.srcAccessMask = 0,
.dstAccessMask = VK_ACCESS_SHADER_READ_BIT,
.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = handle.vk_data->vimage,
.subresourceRange = {
.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
.baseMipLevel = 0,
.levelCount = 1,
.baseArrayLayer = 0,
.layerCount = 1,
}};
vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 0, nullptr, 0, nullptr, 1, &memory_barrier);
handle.vk_data->layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
}
for (size_t target_index: target_indices)
{
assert(target_index < blit_targets.size());
auto & target = blit_targets[target_index];
if (description.offset_x > target.offset.x + target.extent.width)
continue;
if (description.offset_x + description.width < target.offset.x)
continue;
int x0 = description.offset_x - target.offset.x;
int y0 = description.offset_y;
int x1 = x0 + description.width;
int y1 = y0 + description.height;
VkRenderPassBeginInfo begin_info{
.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO,
.renderPass = renderpass,
.framebuffer = target.framebuffer,
.renderArea =
{
.offset = {0, 0},
.extent = target.extent,
},
.clearValueCount = 0,
};
vkCmdBeginRenderPass(command_buffer, &begin_info, VK_SUBPASS_CONTENTS_INLINE);
vkCmdBindPipeline(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, handle.vk_data->pipeline->pipeline);
VkViewport viewport{.x = (float)x0,
.y = (float)y0,
.width = (float)description.width,
.height = (float)description.height,
.minDepth = 0,
.maxDepth = 1};
x0 = std::clamp<int>(x0, 0, target.extent.width);
x1 = std::clamp<int>(x1, 0, target.extent.width);
y0 = std::clamp<int>(y0, 0, target.extent.height);
y1 = std::clamp<int>(y1, 0, target.extent.height);
VkRect2D scissor{
.offset = {.x = x0, .y = y0},
.extent = {.width = (uint32_t)(x1 - x0), .height = (uint32_t)(y1 - y0)},
};
vkCmdSetViewport(command_buffer, 0, 1, &viewport);
vkCmdSetScissor(command_buffer, 0, 1, &scissor);
vkCmdBindDescriptorSets(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, handle.vk_data->pipeline->layout, 0, 1, &handle.vk_data->descriptor_set, 0, nullptr);
vkCmdDraw(command_buffer, 3, 1, 0, 0);
vkCmdEndRenderPass(command_buffer);
}
}
decoder::blit_handle::~blit_handle()
{
AImage_delete(aimage);
}
} // namespace wivrn::android
+161
View File
@@ -0,0 +1,161 @@
/*
* WiVRn VR streaming
* Copyright (C) 2022 Guillaume Meunier <guillaume.meunier@centraliens.net>
* Copyright (C) 2022 Patrick Nicolas <patricknicolas@laposte.net>
*
* 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 <https://www.gnu.org/licenses/>.
*/
#pragma once
#include "utils/sync_queue.h"
#include "vk/device_memory.h"
#include "vk/image.h"
#include "vk/renderpass.h"
#include "wivrn_packets.h"
#include <memory>
#include <optional>
#include <span>
#include <string>
#include <thread>
#include <unordered_map>
#include <vector>
#include <media/NdkImage.h>
#include <media/NdkImageReader.h>
#include <media/NdkMediaCodec.h>
#include <media/NdkMediaFormat.h>
#include <vulkan/vulkan_core.h>
#define DEUGLIFY(x) \
struct x##_deleter \
{ \
void operator()(x * ptr) \
{ \
x##_delete(ptr); \
} \
}; \
using x##_ptr = std::unique_ptr<x, x##_deleter>;
DEUGLIFY(AImageReader)
DEUGLIFY(AMediaCodec)
class shard_accumulator;
namespace scenes
{
class stream;
}
namespace wivrn::android
{
class decoder
{
public:
struct pipeline_context;
struct blit_target
{
VkImage image;
VkImageView image_view;
VkOffset2D offset;
VkExtent2D extent;
VkFramebuffer framebuffer;
std::shared_ptr<pipeline_context> pipeline;
};
struct mapped_hardware_buffer;
struct blit_handle
{
xrt::drivers::wivrn::from_headset::feedback feedback;
xrt::drivers::wivrn::to_headset::video_stream_data_shard::view_info_t view_info;
std::shared_ptr<mapped_hardware_buffer> vk_data;
AImage * aimage{};
~blit_handle();
};
private:
xrt::drivers::wivrn::to_headset::video_stream_description::item description;
float fps;
VkDevice device;
AImageReader_ptr image_reader;
AMediaCodec_ptr media_codec;
std::weak_ptr<scenes::stream> weak_scene;
shard_accumulator * accumulator;
PFN_vkGetAndroidHardwareBufferPropertiesANDROID vkGetAndroidHardwareBufferPropertiesANDROID;
void on_image_available(AImageReader * reader);
static void on_image_available(void * context, AImageReader * reader);
utils::sync_queue<int32_t> input_buffers;
utils::sync_queue<int32_t> output_buffers;
utils::sync_queue<std::pair<xrt::drivers::wivrn::from_headset::feedback, xrt::drivers::wivrn::to_headset::video_stream_data_shard::view_info_t>> frame_infos;
std::thread output_releaser;
static void on_media_error(AMediaCodec *, void * userdata, media_status_t error, int32_t actionCode, const char * detail);
static void on_media_format_changed(AMediaCodec *, void * userdata, AMediaFormat *);
static void on_media_input_available(AMediaCodec *, void * userdata, int32_t index);
static void on_media_output_available(AMediaCodec *, void * userdata, int32_t index, AMediaCodecBufferInfo * bufferInfo);
void push_nals(std::span<uint8_t> data, int64_t timestamp, uint32_t flags);
std::vector<blit_target> blit_targets;
std::shared_ptr<pipeline_context> pipeline;
std::mutex hbm_mutex;
std::unordered_map<AHardwareBuffer *, std::shared_ptr<mapped_hardware_buffer>> hardware_buffer_map;
vk::renderpass renderpass;
std::shared_ptr<mapped_hardware_buffer> map_hardware_buffer(AImage *);
public:
decoder(
VkDevice device,
VkPhysicalDevice physical_device,
const xrt::drivers::wivrn::to_headset::video_stream_description::item & description,
float fps,
std::weak_ptr<scenes::stream> scene,
shard_accumulator * accumulator);
decoder(const decoder &) = delete;
decoder(decoder &&) = delete;
~decoder();
void push_data(std::span<uint8_t> data, uint64_t frame_index, bool partial);
void frame_completed(xrt::drivers::wivrn::from_headset::feedback &, const xrt::drivers::wivrn::to_headset::video_stream_data_shard::view_info_t & view_info);
const auto & desc() const
{
return description;
}
static const VkImageLayout framebuffer_expected_layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
static const VkImageUsageFlagBits framebuffer_usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
void set_blit_targets(std::vector<blit_target> targets, VkFormat format);
void blit(VkCommandBuffer command_buffer, blit_handle & handle, std::span<int> target_indices);
void blit_finished(blit_handle & handle);
};
} // namespace wivrn::android
+258
View File
@@ -0,0 +1,258 @@
/*
* WiVRn VR streaming
* Copyright (C) 2022 Guillaume Meunier <guillaume.meunier@centraliens.net>
* Copyright (C) 2022 Patrick Nicolas <patricknicolas@laposte.net>
*
* 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 <https://www.gnu.org/licenses/>.
*/
#include "ffmpeg_decoder.h"
#include "scenes/stream.h"
#include "spdlog/spdlog.h"
#include "utils/check.h"
#include <cassert>
extern "C"
{
#include <libavcodec/avcodec.h>
#include <libavutil/buffer.h>
#include <libavutil/hwcontext.h>
#include <libavutil/hwcontext_vulkan.h>
#include <libswscale/swscale.h>
}
namespace ffmpeg
{
static void free_codec_context(AVCodecContext * ctx)
{
avcodec_free_context(&ctx);
}
static void free_frame(AVFrame * frame)
{
av_frame_free(&frame);
}
static AVCodecID codec_id(xrt::drivers::wivrn::video_codec codec)
{
using c = xrt::drivers::wivrn::video_codec;
switch (codec)
{
case c::h264:
return AV_CODEC_ID_H264;
case c::h265:
return AV_CODEC_ID_HEVC;
}
assert(false);
__builtin_unreachable();
}
decoder::blit_handle::~blit_handle()
{
std::lock_guard lock(self->mutex);
if (image_index < 0)
return;
self->free_images.push_back(image_index);
}
decoder::decoder(
VkDevice device,
VkPhysicalDevice physical_device,
const xrt::drivers::wivrn::to_headset::video_stream_description::item & description,
float fps,
std::weak_ptr<scenes::stream> scene,
shard_accumulator * accumulator) :
device(device), description(description), codec(nullptr, free_codec_context), sws(nullptr, sws_freeContext), weak_scene(scene), accumulator(accumulator)
{
free_images.resize(image_count);
for (int i = 0; i < image_count; i++)
{
free_images[i] = i;
VkImageCreateInfo image_info{};
image_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
image_info.imageType = VK_IMAGE_TYPE_2D;
image_info.format = VK_FORMAT_A8B8G8R8_SRGB_PACK32;
image_info.extent.width = description.width;
image_info.extent.height = description.height;
image_info.extent.depth = 1;
image_info.mipLevels = 1;
image_info.arrayLayers = 1;
image_info.samples = VK_SAMPLE_COUNT_1_BIT;
image_info.tiling = VK_IMAGE_TILING_LINEAR;
image_info.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
image_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
image_info.queueFamilyIndexCount = 0;
image_info.pQueueFamilyIndices = NULL;
image_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
decoded_images[i].image = vk::image(device, image_info);
decoded_images[i].memory = vk::device_memory(device, physical_device, decoded_images[i].image, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
decoded_images[i].memory.map_memory();
VkImageSubresource resource{};
resource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
vkGetImageSubresourceLayout(device, decoded_images[i].image, &resource, &decoded_images[i].layout);
}
auto avcodec = avcodec_find_decoder(codec_id(description.codec));
if (avcodec == nullptr)
{
throw std::runtime_error{"avcodec_find_decoder failed"};
}
codec.reset(avcodec_alloc_context3(avcodec));
int ret = avcodec_open2(codec.get(), avcodec, nullptr);
if (ret < 0)
throw std::runtime_error{"avcodec_open2 failed"};
}
void decoder::set_blit_targets(std::vector<blit_target> targets, VkFormat format)
{
blit_targets = std::move(targets);
}
void decoder::blit(VkCommandBuffer command_buffer, blit_handle & handle, std::span<int> blit_indices)
{
std::unique_lock lock(mutex);
// Transition layout to VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL
// TODO: transition only if needed
VkImageMemoryBarrier barrier{};
barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
barrier.image = handle.image;
barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
barrier.subresourceRange.levelCount = 1;
barrier.subresourceRange.layerCount = 1;
barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
barrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 0, nullptr, 0, nullptr, 1, &barrier);
for (int blit_index: blit_indices)
{
uint32_t left = blit_targets[blit_index].offset.x;
uint32_t right = left + blit_targets[blit_index].extent.width;
uint32_t width = blit_targets[blit_index].extent.width;
uint32_t height = blit_targets[blit_index].extent.height;
// check for intersection
if (description.offset_x >= right or description.offset_x + description.width <= left)
continue;
VkImageBlit blit{};
blit.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
blit.srcSubresource.layerCount = 1;
blit.srcOffsets[0].x = std::max<int32_t>(0, left - description.offset_x);
blit.srcOffsets[0].y = 0;
blit.srcOffsets[1].x = std::min<int32_t>(description.width, right - description.offset_x);
blit.srcOffsets[1].y = std::min<int32_t>(description.height, height - description.offset_y);
blit.srcOffsets[1].z = 1;
blit.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
blit.dstSubresource.layerCount = 1;
blit.dstOffsets[0].x = std::max<int32_t>(0, description.offset_x - left);
blit.dstOffsets[0].y = description.offset_y;
blit.dstOffsets[1].x = std::min<int32_t>(width, description.offset_x + description.width - left);
blit.dstOffsets[1].y = std::min<int32_t>(height, description.offset_y + description.height);
blit.dstOffsets[1].z = 1;
vkCmdBlitImage(command_buffer, handle.image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, blit_targets[blit_index].image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit, VK_FILTER_LINEAR);
}
}
void decoder::push_data(std::span<uint8_t> data, uint64_t frame_index, bool partial)
{
packet.insert(packet.end(), data.begin(), data.end());
this->frame_index = frame_index;
}
void decoder::frame_completed(const xrt::drivers::wivrn::from_headset::feedback & feedback, const xrt::drivers::wivrn::to_headset::video_stream_data_shard::view_info_t & view_info)
{
spdlog::trace("ffmpeg decoder:frame_completed {}", frame_index);
AVPacket packet{};
packet.pts = AV_NOPTS_VALUE;
packet.dts = AV_NOPTS_VALUE;
packet.data = this->packet.data();
packet.size = this->packet.size();
packet.pos = -1;
int res = AVERROR(EAGAIN);
while (res == AVERROR(EAGAIN))
{
res = avcodec_send_packet(codec.get(), &packet);
if (res == AVERROR(EAGAIN))
{
spdlog::warn("EAGAIN in avcodec_send_packet");
frame_completed(feedback, view_info);
}
}
if (res < 0)
throw std::runtime_error{"avcodec_send_packet failed"};
std::unique_ptr<AVFrame, void (*)(AVFrame *)> frame(av_frame_alloc(), free_frame);
res = avcodec_receive_frame(codec.get(), frame.get());
if (res == AVERROR(EAGAIN))
return;
if (res != 0)
throw std::runtime_error{"avcodec_receive_frame failed"};
this->packet.clear();
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));
}
std::unique_lock lock(mutex);
if (free_images.empty())
{
spdlog::warn("No free image");
return;
}
int index = free_images.back();
free_images.pop_back();
lock.unlock();
decoded_images[index].frame_index = frame_index;
int dstStride = decoded_images[index].layout.rowPitch;
uint8_t * out = (uint8_t *)decoded_images[index].memory.data();
res = sws_scale(sws.get(), frame->data, frame->linesize, 0, frame->height, &out, &dstStride);
if (res == 0)
throw std::runtime_error{"sws_scale failed"};
auto handle = std::make_shared<decoder::blit_handle>();
handle->feedback = feedback;
handle->view_info = view_info;
handle->image = decoded_images[index].image;
handle->image_index = index;
handle->self = this;
if (auto scene = weak_scene.lock())
scene->push_blit_handle(accumulator, std::move(handle));
}
} // namespace ffmpeg
+121
View File
@@ -0,0 +1,121 @@
/*
* WiVRn VR streaming
* Copyright (C) 2022 Guillaume Meunier <guillaume.meunier@centraliens.net>
* Copyright (C) 2022 Patrick Nicolas <patricknicolas@laposte.net>
*
* 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 <https://www.gnu.org/licenses/>.
*/
#pragma once
#include "vk/device_memory.h"
#include "vk/image.h"
#include "wivrn_packets.h"
#include <deque>
#include <memory>
#include <mutex>
#include <span>
#include <string>
#include <vector>
#include <vulkan/vulkan_core.h>
class shard_accumulator;
extern "C"
{
struct AVBufferRef;
struct AVCodecContext;
struct SwsContext;
}
namespace scenes
{
class stream;
}
namespace ffmpeg
{
class decoder
{
public:
struct blit_target
{
VkImage image;
VkImageView image_view;
VkOffset2D offset;
VkExtent2D extent;
};
private:
static const int image_count = 3;
struct image
{
vk::image image;
vk::device_memory memory;
VkSubresourceLayout layout;
uint64_t frame_index;
};
VkDevice device;
std::array<image, image_count> decoded_images;
std::vector<int> free_images;
xrt::drivers::wivrn::to_headset::video_stream_description::item description;
std::unique_ptr<AVCodecContext, void (*)(AVCodecContext *)> codec;
std::unique_ptr<SwsContext, void (*)(SwsContext *)> sws;
std::vector<uint8_t> packet;
uint64_t frame_index;
std::weak_ptr<scenes::stream> weak_scene;
shard_accumulator * accumulator;
std::vector<blit_target> blit_targets;
std::mutex mutex;
public:
decoder(
VkDevice device,
VkPhysicalDevice physical_device,
const xrt::drivers::wivrn::to_headset::video_stream_description::item & description,
float fps,
std::weak_ptr<scenes::stream> scene,
shard_accumulator * accumulator);
void push_data(std::span<uint8_t> data, uint64_t frame_index, bool partial);
void frame_completed(const xrt::drivers::wivrn::from_headset::feedback &, const xrt::drivers::wivrn::to_headset::video_stream_data_shard::view_info_t & view_info);
const auto & desc() const
{
return description;
}
struct blit_handle
{
xrt::drivers::wivrn::from_headset::feedback feedback;
xrt::drivers::wivrn::to_headset::video_stream_data_shard::view_info_t view_info;
int image_index;
VkImage image;
decoder * self;
~blit_handle();
};
static const VkImageLayout framebuffer_expected_layout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
static const VkImageUsageFlagBits framebuffer_usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT;
void set_blit_targets(std::vector<blit_target> targets, VkFormat format);
void blit(VkCommandBuffer command_buffer, blit_handle & handle, std::span<int> target_indices);
};
} // namespace ffmpeg
+349
View File
@@ -0,0 +1,349 @@
/*
* WiVRn VR streaming
* Copyright (C) 2022 Guillaume Meunier <guillaume.meunier@centraliens.net>
* Copyright (C) 2022 Patrick Nicolas <patricknicolas@laposte.net>
*
* 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 <https://www.gnu.org/licenses/>.
*/
#include "shard_accumulator.h"
#include "application.h"
#include "external/rs.h"
#include "scenes/stream.h"
#include "spdlog/spdlog.h"
#include "utils/typename.h"
#include "wivrn_serialization.h"
using namespace xrt::drivers::wivrn::to_headset;
using shard_set = shard_accumulator::shard_set;
using data_shard = shard_accumulator::data_shard;
using parity_shard = shard_accumulator::parity_shard;
shard_set::shard_set(uint8_t stream_index)
{
feedback.stream_index = stream_index;
}
void shard_set::reset(uint64_t frame_index)
{
num_shards = 0;
min_for_reconstruction = -1;
data.clear();
parity.clear();
uint8_t stream_index = feedback.stream_index;
feedback = {};
feedback.frame_index = frame_index;
feedback.stream_index = stream_index;
}
bool shard_set::empty() const
{
return num_shards == 0;
}
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))
return false;
for (const auto & shard: frame)
if (not shard)
return false;
return true;
}
uint16_t shard_set::insert(data_shard && shard)
{
XrTime now = application::now();
if (empty())
feedback.received_first_packet = now;
feedback.received_last_packet = now;
auto idx = shard.shard_idx;
if (idx >= data.size())
data.resize(idx + 1);
if (not data[idx])
++num_shards;
data[idx] = std::move(shard);
if (auto i = try_reconstruct())
return *i;
return idx;
}
std::optional<uint16_t> shard_set::insert(parity_shard && shard)
{
XrTime now = application::now();
if (empty())
feedback.received_first_packet = now;
feedback.received_last_packet = now;
auto idx = shard.parity_element;
min_for_reconstruction = shard.data_shard_count;
if (idx >= parity.size())
parity.resize(idx + 1);
if (not parity[idx])
++num_shards;
parity[idx] = std::move(shard);
return try_reconstruct();
}
parity_shard & shard_set::get_parity()
{
for (auto & shard: parity)
{
if (shard)
return *shard;
}
// this function shall be called only when at least one parity shard exists
assert(false);
__builtin_unreachable();
}
std::optional<uint16_t> shard_set::try_reconstruct()
{
if (parity.empty())
return {};
if (num_shards < min_for_reconstruction)
return {};
static std::once_flag once;
std::call_once(once, reed_solomon_init);
auto & p = get_parity();
std::unique_ptr<reed_solomon, void (*)(reed_solomon *)> rs(
reed_solomon_new(p.data_shard_count, p.num_parity_elements), reed_solomon_release);
size_t shard_size = p.payload.size();
std::vector<uint8_t *> rs_shards;
std::vector<uint8_t> rs_marks;
std::vector<std::vector<uint8_t>> data_raw;
data.resize(p.data_shard_count);
data_raw.reserve(p.data_shard_count);
for (auto & shard: data)
{
if (shard)
{
xrt::drivers::wivrn::serialization_packet s;
s.serialize(*shard);
data_raw.emplace_back(std::move(s)).resize(shard_size);
rs_marks.push_back(0);
}
else
{
data_raw.emplace_back(shard_size, 0);
rs_marks.push_back(1);
}
rs_shards.push_back(data_raw.back().data());
}
// WARNING: do not use p after this line, the array it points to has been modified
parity.resize(p.num_parity_elements);
std::vector<std::vector<uint8_t>> dummy;
dummy.reserve(p.num_parity_elements);
for (auto & shard: parity)
{
if (shard)
{
rs_shards.push_back(shard->payload.data());
rs_marks.push_back(0);
}
else
{
auto d = dummy.emplace_back(shard_size).data();
rs_shards.push_back(d);
rs_marks.push_back(1);
}
}
int err = reed_solomon_reconstruct(rs.get(), rs_shards.data(), rs_marks.data(), data.size() + parity.size(), shard_size);
if (err)
{
spdlog::info("reed_solomon_reconstruct failed");
return {};
}
std::optional<uint16_t> first_reconstructed;
for (size_t i = 0; i < data.size(); ++i)
{
if (not data[i])
{
xrt::drivers::wivrn::deserialization_packet d(data_raw[i]);
data[i] = d.deserialize<data_shard>();
if (not first_reconstructed)
first_reconstructed = i;
}
}
assert(first_reconstructed);
spdlog::info("reed_solomon_reconstruct success frame {}, reconstructed {} (out of {} shards)",
data[0]->frame_idx,
*first_reconstructed,
data.size());
feedback.reconstructed = application::now();
return first_reconstructed;
}
static void debug_why_not_sent(const shard_set & shards)
{
const auto & frame = shards.data;
if (frame.empty())
{
spdlog::info("frame {} was not sent because no shard was received", shards.frame_index());
return;
}
int frame_idx = -1;
int expected_data = -1;
int expected_parity = -1;
size_t data = 0;
size_t parity = 0;
for (const auto & shard: frame)
{
if (shard)
{
frame_idx = shard->frame_idx;
++data;
}
}
for (const auto & shard: shards.parity)
{
if (shard)
{
frame_idx = shard->frame_idx;
expected_data = shard->data_shard_count;
expected_parity = shard->num_parity_elements;
++parity;
}
}
spdlog::info("frame {} was not sent with {}/{} data, {}/{} parity shards)", frame_idx, data, expected_data, parity, expected_parity);
}
void shard_accumulator::advance()
{
std::swap(current, next);
next.reset(current.frame_index() + 1);
}
template <typename Shard>
void shard_accumulator::push_shard(Shard && shard)
{
assert(current.frame_index() + 1 == next.frame_index());
uint8_t frame_diff = shard.frame_idx - current.frame_index();
if (shard.frame_idx < current.frame_index())
{
// frame is in the past, drop it
}
else if (frame_diff == 0)
{
// Due to error correction, inserting a shard might create a valid one before
auto shard_idx = current.insert(std::move(shard));
try_submit_frame(shard_idx);
}
else if (frame_diff == 1)
{
next.insert(std::move(shard));
if (is_complete(next))
{
debug_why_not_sent(current);
send_feedback(current.feedback);
advance();
try_submit_frame(0);
}
}
else if (frame_diff == 2)
{
debug_why_not_sent(current);
send_feedback(current.feedback);
advance();
push_shard(std::move(shard));
}
else
{
// We have lost more than one frame
send_feedback(current.feedback);
send_feedback(next.feedback);
current.reset(shard.frame_idx);
next.reset(shard.frame_idx + 1);
push_shard(std::move(shard));
}
}
template void shard_accumulator::push_shard<parity_shard>(parity_shard && shard);
template void shard_accumulator::push_shard<video_stream_data_shard>(video_stream_data_shard && shard);
void shard_accumulator::try_submit_frame(std::optional<uint16_t> shard_idx)
{
if (shard_idx)
try_submit_frame(*shard_idx);
}
void shard_accumulator::try_submit_frame(uint16_t shard_idx)
{
auto & data_shards = current.data;
// Do not submit if the frame is not complete
for (const auto & shard: data_shards)
{
if (not shard)
return;
}
if (not(data_shards.back()->flags & video_stream_data_shard::end_of_frame))
return;
uint64_t frame_index = data_shards[0]->frame_idx;
if (data_shards.size() == 1)
decoder->push_data(data_shards[shard_idx]->payload, frame_index, false);
else
{
// Slice is over multiple shards, concatenate them
std::vector<uint8_t> payload;
size_t size = 0;
for (const auto & shard: data_shards)
{
size += shard->payload.size();
}
payload.reserve(size);
for (const auto & shard: data_shards)
{
payload.insert(payload.end(), shard->payload.begin(), shard->payload.end());
}
decoder->push_data(payload, frame_index, false);
}
auto feedback = current.feedback;
assert(data_shards.back()->view_info);
feedback.received_pose = data_shards.back()->view_info->pose;
// Try to extract a frame
decoder->frame_completed(feedback, *data_shards.back()->view_info);
advance();
}
void shard_accumulator::send_feedback(const xrt::drivers::wivrn::from_headset::feedback & feedback)
{
auto scene = weak_scene.lock();
if (scene)
scene->send_feedback(feedback);
}
+125
View File
@@ -0,0 +1,125 @@
/*
* WiVRn VR streaming
* Copyright (C) 2022 Guillaume Meunier <guillaume.meunier@centraliens.net>
* Copyright (C) 2022 Patrick Nicolas <patricknicolas@laposte.net>
*
* 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 <https://www.gnu.org/licenses/>.
*/
#pragma once
#include "xr/instance.h"
#include <memory>
#ifdef XR_USE_PLATFORM_ANDROID
#include "decoder/android/android_decoder.h"
using decoder_impl = ::wivrn::android::decoder;
#else
#include "decoder/ffmpeg/ffmpeg_decoder.h"
using decoder_impl = ::ffmpeg::decoder;
#endif
#include "wivrn_packets.h"
#include <array>
#include <atomic>
#include <mutex>
#include <optional>
#include <vector>
class shard_accumulator
{
std::shared_ptr<decoder_impl> decoder;
public:
using data_shard = xrt::drivers::wivrn::to_headset::video_stream_data_shard;
using parity_shard = xrt::drivers::wivrn::to_headset::video_stream_parity_shard;
struct shard_set
{
size_t num_shards = 0;
size_t min_for_reconstruction = -1;
std::vector<std::optional<data_shard>> data;
std::vector<std::optional<parity_shard>> parity;
void reset(uint64_t frame_index);
bool empty() const;
uint16_t insert(data_shard &&);
std::optional<uint16_t> insert(parity_shard &&);
parity_shard & get_parity();
std::optional<uint16_t> try_reconstruct();
xrt::drivers::wivrn::from_headset::feedback feedback{};
explicit shard_set(uint8_t stream_index);
shard_set(const shard_set &) = default;
shard_set(shard_set &&) = default;
shard_set & operator=(const shard_set &) = default;
shard_set & operator=(shard_set &&) = default;
uint64_t frame_index() const
{
return feedback.frame_index;
}
};
private:
shard_set current;
shard_set next;
std::weak_ptr<scenes::stream> weak_scene;
public:
explicit shard_accumulator(
VkDevice device,
VkPhysicalDevice physical_device,
const xrt::drivers::wivrn::to_headset::video_stream_description::item & description,
float fps,
std::weak_ptr<scenes::stream> scene,
uint8_t stream_index) :
decoder(std::make_shared<decoder_impl>(device, physical_device, description, fps, scene, this)),
current(stream_index),
next(stream_index),
weak_scene(scene)
{
next.reset(1);
}
template <typename Shard>
void push_shard(Shard &&);
auto & desc() const
{
return decoder->desc();
}
using blit_handle = decoder_impl::blit_handle;
using blit_target = decoder_impl::blit_target;
static const VkImageLayout framebuffer_expected_layout = decoder_impl::framebuffer_expected_layout;
static const VkImageUsageFlagBits framebuffer_usage = decoder_impl::framebuffer_usage;
void set_blit_targets(std::vector<blit_target> targets, VkFormat format)
{
decoder->set_blit_targets(std::move(targets), format);
}
void blit(VkCommandBuffer command_buffer, blit_handle & handle, std::span<int> blit_target_indices)
{
return decoder->blit(command_buffer, handle, blit_target_indices);
}
private:
void try_submit_frame(std::optional<uint16_t> shard_idx);
void try_submit_frame(uint16_t shard_idx);
void send_feedback(const xrt::drivers::wivrn::from_headset::feedback & feedback);
void advance();
};