Move encoder code into new directory
This commit is contained in:
@@ -0,0 +1,162 @@
|
||||
/*
|
||||
* 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 "encoder_settings.h"
|
||||
#include "driver/configuration.h"
|
||||
#include "video_encoder.h"
|
||||
#include "vk/vk_helpers.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <string>
|
||||
#include <vulkan/vulkan.h>
|
||||
|
||||
#include "wivrn_config.h"
|
||||
|
||||
#ifdef WIVRN_USE_VAAPI
|
||||
#include "ffmpeg/VideoEncoderVA.h"
|
||||
#endif
|
||||
|
||||
using namespace xrt::drivers::wivrn;
|
||||
|
||||
// TODO: size independent bitrate
|
||||
static const uint64_t default_bitrate = 50'000'000;
|
||||
|
||||
static bool is_nvidia(vk_bundle * vk)
|
||||
{
|
||||
VkPhysicalDeviceProperties physical_device_properties;
|
||||
vk->vkGetPhysicalDeviceProperties(vk->physical_device, &physical_device_properties);
|
||||
return physical_device_properties.vendorID == 0x10DE;
|
||||
}
|
||||
|
||||
static std::vector<xrt::drivers::wivrn::encoder_settings> get_encoder_default_settings(vk_bundle * vk, uint16_t width, uint16_t height)
|
||||
{
|
||||
xrt::drivers::wivrn::encoder_settings settings{};
|
||||
settings.width = width;
|
||||
settings.height = height;
|
||||
settings.codec = xrt::drivers::wivrn::h265;
|
||||
settings.bitrate = default_bitrate;
|
||||
|
||||
settings.video_height = settings.height;
|
||||
settings.video_width = settings.width;
|
||||
|
||||
if (is_nvidia(vk))
|
||||
{
|
||||
#ifdef WIVRN_USE_NVENC
|
||||
settings.encoder_name = encoder_nvenc;
|
||||
#elif defined(WIVRN_USE_X264)
|
||||
settings.encoder_name = encoder_x264;
|
||||
settings.codec = xrt::drivers::wivrn::h264;
|
||||
U_LOG_W("nvidia GPU detected, but cuda support not compiled");
|
||||
#else
|
||||
U_LOG_E("no suitable encoder available (compile with x264 or cuda support)");
|
||||
return {};
|
||||
#endif
|
||||
}
|
||||
else
|
||||
{
|
||||
#ifdef WIVRN_USE_VAAPI
|
||||
settings.encoder_name = encoder_vaapi;
|
||||
#elif defined(WIVRN_USE_X264)
|
||||
settings.encoder_name = encoder_x264;
|
||||
settings.codec = xrt::drivers::wivrn::h264;
|
||||
U_LOG_W("ffmpeg support not compiled, vaapi encoder not available");
|
||||
#else
|
||||
U_LOG_E("no suitable encoder available (compile with x264 or ffmpeg support)");
|
||||
return {};
|
||||
#endif
|
||||
}
|
||||
|
||||
return {settings};
|
||||
}
|
||||
|
||||
std::vector<encoder_settings> xrt::drivers::wivrn::get_encoder_settings(vk_bundle * vk, uint16_t width, uint16_t height)
|
||||
{
|
||||
try
|
||||
{
|
||||
const auto & config = configuration::read_user_configuration();
|
||||
if (config.encoders.empty())
|
||||
return get_encoder_default_settings(vk, width, height);
|
||||
std::vector<xrt::drivers::wivrn::encoder_settings> res;
|
||||
int next_group = 0;
|
||||
for (const auto & encoder: config.encoders)
|
||||
{
|
||||
xrt::drivers::wivrn::encoder_settings settings{};
|
||||
settings.encoder_name = encoder.name;
|
||||
settings.width = std::ceil(encoder.width.value_or(1) * width);
|
||||
settings.height = std::ceil(encoder.height.value_or(1) * height);
|
||||
settings.video_width = settings.width;
|
||||
settings.video_height = settings.height;
|
||||
settings.offset_x = std::ceil(encoder.offset_x.value_or(0) * width);
|
||||
settings.offset_y = std::ceil(encoder.offset_y.value_or(0) * height);
|
||||
settings.bitrate = encoder.bitrate.value_or(default_bitrate);
|
||||
settings.codec = encoder.codec.value_or(xrt::drivers::wivrn::h264);
|
||||
settings.group = encoder.group.value_or(next_group);
|
||||
settings.options = encoder.options;
|
||||
|
||||
next_group = std::max(next_group, settings.group + 1);
|
||||
res.push_back(settings);
|
||||
}
|
||||
return res;
|
||||
}
|
||||
catch (const std::exception & e)
|
||||
{
|
||||
U_LOG_E("Failed to read encoder configuration: %s", e.what());
|
||||
}
|
||||
return get_encoder_default_settings(vk, width, height);
|
||||
}
|
||||
|
||||
VkImageTiling xrt::drivers::wivrn::get_required_tiling(vk_bundle * vk,
|
||||
const std::vector<xrt::drivers::wivrn::encoder_settings> & settings)
|
||||
{
|
||||
bool can_optimal = true;
|
||||
bool can_drm = vk->has_EXT_image_drm_format_modifier;
|
||||
for (const auto & item: settings)
|
||||
{
|
||||
#ifdef WIVRN_USE_VAAPI
|
||||
if (item.encoder_name == encoder_vaapi)
|
||||
{
|
||||
can_optimal = false;
|
||||
if (not use_drm_format_modifiers)
|
||||
can_drm = false;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
if (can_optimal)
|
||||
return VK_IMAGE_TILING_OPTIMAL;
|
||||
if (can_drm)
|
||||
return VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT;
|
||||
return VK_IMAGE_TILING_LINEAR;
|
||||
}
|
||||
|
||||
VkExternalMemoryHandleTypeFlags xrt::drivers::wivrn::get_handle_types(const std::vector<encoder_settings> & settings)
|
||||
{
|
||||
VkExternalMemoryHandleTypeFlags result = 0;
|
||||
for (const auto & item: settings)
|
||||
{
|
||||
#ifdef WIVRN_USE_VAAPI
|
||||
if (item.encoder_name == encoder_vaapi)
|
||||
result |= VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT;
|
||||
#endif
|
||||
#ifdef WIVRN_USE_NVENC
|
||||
if (item.encoder_name == encoder_nvenc)
|
||||
result |= VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT;
|
||||
#endif
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
/*
|
||||
* 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/vk_helpers.h"
|
||||
#include "wivrn_packets.h"
|
||||
|
||||
#include <map>
|
||||
#include <string>
|
||||
|
||||
namespace xrt::drivers::wivrn
|
||||
{
|
||||
|
||||
struct encoder_settings : public to_headset::video_stream_description::item
|
||||
{
|
||||
// encoder identifier, such as nvenc, vaapi or x264
|
||||
std::string encoder_name;
|
||||
uint64_t bitrate; // bit/s
|
||||
std::map<std::string, std::string> options; // additional encoder-specific configuration
|
||||
// encoders in the same group are executed in sequence
|
||||
int group = 0;
|
||||
};
|
||||
|
||||
std::vector<encoder_settings> get_encoder_settings(vk_bundle * vk, uint16_t width, uint16_t height);
|
||||
|
||||
VkImageTiling get_required_tiling(vk_bundle * vk, const std::vector<encoder_settings> & settings);
|
||||
|
||||
VkExternalMemoryHandleTypeFlags get_handle_types(const std::vector<encoder_settings> & settings);
|
||||
|
||||
} // namespace xrt::drivers::wivrn
|
||||
@@ -0,0 +1,134 @@
|
||||
/*
|
||||
* 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 "VideoEncoderFFMPEG.h"
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <stdexcept>
|
||||
#include <string.h>
|
||||
|
||||
extern "C"
|
||||
{
|
||||
#include <libavcodec/avcodec.h>
|
||||
#include <libavutil/log.h>
|
||||
}
|
||||
|
||||
namespace
|
||||
{
|
||||
|
||||
bool should_keep_nal_h264(const uint8_t * header_start)
|
||||
{
|
||||
uint8_t nal_type = (header_start[2] == 0 ? header_start[4] : header_start[3]) & 0x1F;
|
||||
switch (nal_type)
|
||||
{
|
||||
case 6: // supplemental enhancement information
|
||||
case 9: // access unit delimiter
|
||||
return false;
|
||||
default:
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
bool should_keep_nal_h265(const uint8_t * header_start)
|
||||
{
|
||||
uint8_t nal_type = ((header_start[2] == 0 ? header_start[4] : header_start[3]) >> 1) & 0x3F;
|
||||
switch (nal_type)
|
||||
{
|
||||
case 35: // access unit delimiter
|
||||
case 39: // supplemental enhancement information
|
||||
return false;
|
||||
default:
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
void filter_NAL(const uint8_t * input, size_t input_size, std::vector<uint8_t> & out, VideoEncoderFFMPEG::Codec codec)
|
||||
{
|
||||
if (input_size < 4)
|
||||
return;
|
||||
std::array<uint8_t, 3> header = {{0, 0, 1}};
|
||||
auto end = input + input_size;
|
||||
auto header_start = input;
|
||||
while (header_start != end)
|
||||
{
|
||||
auto next_header = std::search(header_start + 3, end, header.begin(), header.end());
|
||||
if (next_header != end and next_header[-1] == 0)
|
||||
{
|
||||
next_header--;
|
||||
}
|
||||
if (codec == VideoEncoderFFMPEG::Codec::h264 and should_keep_nal_h264(header_start))
|
||||
out.insert(out.end(), header_start, next_header);
|
||||
if (codec == VideoEncoderFFMPEG::Codec::h265 and should_keep_nal_h265(header_start))
|
||||
out.insert(out.end(), header_start, next_header);
|
||||
header_start = next_header;
|
||||
}
|
||||
}
|
||||
|
||||
bool set_log_level()
|
||||
{
|
||||
const char * level = getenv("FFMPEG_LOG_LEVEL");
|
||||
if (level)
|
||||
{
|
||||
if (strcasecmp(level, "TRACE") == 0)
|
||||
av_log_set_level(AV_LOG_TRACE);
|
||||
else if (strcasecmp(level, "DEBUG") == 0)
|
||||
av_log_set_level(AV_LOG_DEBUG);
|
||||
else if (strcasecmp(level, "VERBOSE") == 0)
|
||||
av_log_set_level(AV_LOG_VERBOSE);
|
||||
else if (strcasecmp(level, "INFO") == 0)
|
||||
av_log_set_level(AV_LOG_INFO);
|
||||
else if (strcasecmp(level, "WARNING") == 0)
|
||||
av_log_set_level(AV_LOG_WARNING);
|
||||
else if (strcasecmp(level, "ERROR") == 0)
|
||||
av_log_set_level(AV_LOG_ERROR);
|
||||
else if (strcasecmp(level, "FATAL") == 0)
|
||||
av_log_set_level(AV_LOG_FATAL);
|
||||
else if (strcasecmp(level, "PANIC") == 0)
|
||||
av_log_set_level(AV_LOG_PANIC);
|
||||
else if (strcasecmp(level, "QUIET") == 0)
|
||||
av_log_set_level(AV_LOG_QUIET);
|
||||
else
|
||||
U_LOG_W("log level %s not recognized for FFMPEG_LOG_LEVEL", level);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool VideoEncoderFFMPEG::once = set_log_level();
|
||||
|
||||
void VideoEncoderFFMPEG::Encode(int index, bool idr, std::chrono::steady_clock::time_point target_timestamp)
|
||||
{
|
||||
PushFrame(index, idr, target_timestamp);
|
||||
av_packet_ptr enc_pkt(av_packet_alloc());
|
||||
int err = avcodec_receive_packet(encoder_ctx.get(), enc_pkt.get());
|
||||
if (err == 0)
|
||||
{
|
||||
SendData(std::span<uint8_t>(enc_pkt->data, enc_pkt->size), true);
|
||||
}
|
||||
if (err == AVERROR(EAGAIN))
|
||||
{
|
||||
U_LOG_W("EAGAIN in encoder %d", stream_idx);
|
||||
return;
|
||||
}
|
||||
if (err)
|
||||
{
|
||||
throw std::runtime_error("frame encoding failed, code " + std::to_string(err));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
/*
|
||||
* 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 "../video_encoder.h"
|
||||
#include "ffmpeg_helper.h"
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
|
||||
class VideoEncoderFFMPEG : public xrt::drivers::wivrn::VideoEncoder
|
||||
{
|
||||
public:
|
||||
using Codec = xrt::drivers::wivrn::video_codec;
|
||||
|
||||
void
|
||||
Encode(int index, bool idr, std::chrono::steady_clock::time_point target_timestamp) override;
|
||||
|
||||
protected:
|
||||
virtual void
|
||||
PushFrame(uint32_t frame_index, bool idr, std::chrono::steady_clock::time_point pts) = 0;
|
||||
|
||||
av_codec_context_ptr encoder_ctx;
|
||||
Codec codec;
|
||||
|
||||
private:
|
||||
static bool once;
|
||||
};
|
||||
@@ -0,0 +1,359 @@
|
||||
/*
|
||||
* 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 "VideoEncoderVA.h"
|
||||
#include "ffmpeg_helper.h"
|
||||
#include "vk/vk_helpers.h"
|
||||
#include <cassert>
|
||||
#include <chrono>
|
||||
#include <filesystem>
|
||||
#include <limits>
|
||||
#include <optional>
|
||||
#include <stdexcept>
|
||||
|
||||
extern "C"
|
||||
{
|
||||
#include <libavcodec/avcodec.h>
|
||||
#include <libavfilter/avfilter.h>
|
||||
#include <libavfilter/buffersink.h>
|
||||
#include <libavfilter/buffersrc.h>
|
||||
#include <libavutil/hwcontext.h>
|
||||
#include <libavutil/hwcontext_drm.h>
|
||||
#include <libavutil/hwcontext_vaapi.h>
|
||||
#include <libavutil/opt.h>
|
||||
}
|
||||
|
||||
namespace
|
||||
{
|
||||
|
||||
const char *
|
||||
encoder(VideoEncoderFFMPEG::Codec codec)
|
||||
{
|
||||
switch (codec)
|
||||
{
|
||||
case VideoEncoderFFMPEG::Codec::h264:
|
||||
return "h264_vaapi";
|
||||
case VideoEncoderFFMPEG::Codec::h265:
|
||||
return "hevc_vaapi";
|
||||
}
|
||||
throw std::runtime_error("invalid codec " + std::to_string(int(codec)));
|
||||
}
|
||||
|
||||
void set_hwframe_ctx(AVCodecContext * ctx, AVBufferRef * hw_device_ctx)
|
||||
{
|
||||
av_buffer_ptr hw_frames_ref(av_hwframe_ctx_alloc(hw_device_ctx));
|
||||
int err = 0;
|
||||
|
||||
if (not hw_frames_ref)
|
||||
{
|
||||
throw std::runtime_error("Failed to create VAAPI frame context.");
|
||||
}
|
||||
auto frames_ctx = (AVHWFramesContext *)(hw_frames_ref->data);
|
||||
frames_ctx->format = AV_PIX_FMT_VAAPI;
|
||||
frames_ctx->sw_format = AV_PIX_FMT_NV12;
|
||||
frames_ctx->width = ctx->width;
|
||||
frames_ctx->height = ctx->height;
|
||||
frames_ctx->initial_pool_size = 3;
|
||||
if ((err = av_hwframe_ctx_init(hw_frames_ref.get())) < 0)
|
||||
{
|
||||
throw std::system_error(err, av_error_category(), "Failed to initialize VAAPI frame context");
|
||||
}
|
||||
ctx->hw_frames_ctx = av_buffer_ref(hw_frames_ref.get());
|
||||
if (!ctx->hw_frames_ctx)
|
||||
err = AVERROR(ENOMEM);
|
||||
}
|
||||
|
||||
std::optional<std::filesystem::path>
|
||||
get_render_device(vk_bundle * vk)
|
||||
{
|
||||
VkPhysicalDeviceDrmPropertiesEXT drmProps{};
|
||||
drmProps.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRM_PROPERTIES_EXT;
|
||||
|
||||
VkPhysicalDeviceProperties2 props{};
|
||||
props.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2;
|
||||
props.pNext = &drmProps;
|
||||
|
||||
vk->vkGetPhysicalDeviceProperties2(vk->physical_device, &props);
|
||||
|
||||
if (!drmProps.hasRender)
|
||||
{
|
||||
U_LOG_E("Failed to find render DRM device");
|
||||
throw std::runtime_error("Failed to find render DRM device");
|
||||
}
|
||||
std::filesystem::path path = "/dev/dri/renderD" + std::to_string(drmProps.renderMinor);
|
||||
if (not std::filesystem::exists(path))
|
||||
{
|
||||
U_LOG_W("DRI device %s does not exist, reverting to default", path.c_str());
|
||||
return std::nullopt;
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
VideoEncoderVA::VideoEncoderVA(vk_bundle * vk, const xrt::drivers::wivrn::encoder_settings & settings, float fps) :
|
||||
vk(vk), width(settings.width), height(settings.height), offset_x(settings.offset_x), offset_y(settings.offset_y)
|
||||
{
|
||||
codec = settings.codec;
|
||||
/* VAAPI Encoding pipeline
|
||||
* The encoding pipeline has 3 frame types:
|
||||
* - input vulkan frames, only used to initialize the mapped frames
|
||||
* - mapped frames, one per input frame, same format, and point to the same memory on the device
|
||||
* - encoder frame, with a format compatible with the encoder, created by the filter
|
||||
* Each frame type has a corresponding hardware frame context, the vulkan one is provided
|
||||
*
|
||||
* The pipeline is simply made of a scale_vaapi object, that does the conversion between formats
|
||||
* and the encoder that takes the converted frame and produces packets.
|
||||
*/
|
||||
|
||||
AVBufferRef * tmp;
|
||||
const auto device = get_render_device(vk);
|
||||
int err = av_hwdevice_ctx_create(&tmp, AV_HWDEVICE_TYPE_VAAPI, device ? device->c_str() : NULL, NULL, 0);
|
||||
if (err < 0)
|
||||
{
|
||||
throw std::system_error(err, av_error_category(), "Failed create VAAPI device" + (device ? (" " + device->string()) : std::string()));
|
||||
}
|
||||
hw_ctx_vaapi.reset(tmp);
|
||||
|
||||
const char * encoder_name = encoder(codec);
|
||||
const AVCodec * codec = avcodec_find_encoder_by_name(encoder_name);
|
||||
if (codec == nullptr)
|
||||
{
|
||||
throw std::runtime_error(std::string("Failed to find encoder ") + encoder_name);
|
||||
}
|
||||
|
||||
encoder_ctx.reset(avcodec_alloc_context3(codec));
|
||||
if (not encoder_ctx)
|
||||
{
|
||||
throw std::runtime_error("failed to allocate VAAPI encoder");
|
||||
}
|
||||
|
||||
AVDictionary * opts = nullptr;
|
||||
av_dict_set(&opts, "async_depth", "1", 0);
|
||||
for (auto option: settings.options)
|
||||
{
|
||||
av_dict_set(&opts, option.first.c_str(), option.second.c_str(), 0);
|
||||
}
|
||||
switch (this->codec)
|
||||
{
|
||||
case Codec::h264:
|
||||
encoder_ctx->profile = FF_PROFILE_H264_MAIN;
|
||||
break;
|
||||
case Codec::h265:
|
||||
encoder_ctx->profile = FF_PROFILE_HEVC_MAIN;
|
||||
break;
|
||||
}
|
||||
|
||||
encoder_ctx->width = width;
|
||||
encoder_ctx->height = height;
|
||||
encoder_ctx->time_base = {std::chrono::steady_clock::duration::period::num,
|
||||
std::chrono::steady_clock::duration::period::den};
|
||||
encoder_ctx->framerate = AVRational{(int)fps, 1};
|
||||
encoder_ctx->sample_aspect_ratio = AVRational{1, 1};
|
||||
encoder_ctx->pix_fmt = AV_PIX_FMT_VAAPI;
|
||||
encoder_ctx->max_b_frames = 0;
|
||||
encoder_ctx->bit_rate = settings.bitrate;
|
||||
encoder_ctx->gop_size = std::numeric_limits<decltype(encoder_ctx->gop_size)>::max();
|
||||
|
||||
set_hwframe_ctx(encoder_ctx.get(), hw_ctx_vaapi.get());
|
||||
|
||||
err = avcodec_open2(encoder_ctx.get(), codec, &opts);
|
||||
av_dict_free(&opts);
|
||||
if (err < 0)
|
||||
{
|
||||
throw std::system_error(err, av_error_category(), "Cannot open video encoder codec");
|
||||
}
|
||||
|
||||
if (encoder_ctx->delay != 0)
|
||||
{
|
||||
U_LOG_W("Encoder %d reports a %d frame delay, reprojection will fail", stream_idx, encoder_ctx->delay);
|
||||
}
|
||||
}
|
||||
|
||||
void VideoEncoderVA::PushFrame(uint32_t frame_index, bool idr, std::chrono::steady_clock::time_point pts)
|
||||
{
|
||||
assert(frame_index < mapped_frames.size());
|
||||
av_frame_ptr encoder_frame = make_av_frame();
|
||||
int err = av_buffersrc_add_frame_flags(filter_in, mapped_frames[frame_index].get(), AV_BUFFERSRC_FLAG_PUSH | AV_BUFFERSRC_FLAG_KEEP_REF);
|
||||
if (err != 0)
|
||||
{
|
||||
throw std::system_error(err, av_error_category(), "av_buffersrc_add_frame failed");
|
||||
}
|
||||
err = av_buffersink_get_frame(filter_out, encoder_frame.get());
|
||||
if (err != 0)
|
||||
{
|
||||
throw std::system_error(err, av_error_category(), "av_buffersink_get_frame failed");
|
||||
}
|
||||
|
||||
encoder_frame->pict_type = idr ? AV_PICTURE_TYPE_I : AV_PICTURE_TYPE_P;
|
||||
encoder_frame->pts = pts.time_since_epoch().count();
|
||||
err = avcodec_send_frame(encoder_ctx.get(), encoder_frame.get());
|
||||
if (err)
|
||||
{
|
||||
throw std::system_error(err, av_error_category(), "avcodec_send_frame failed");
|
||||
}
|
||||
}
|
||||
|
||||
void VideoEncoderVA::SetImages(
|
||||
int width,
|
||||
int height,
|
||||
VkFormat format,
|
||||
int num_images,
|
||||
VkImage * images,
|
||||
VkImageView * views,
|
||||
VkDeviceMemory * memory)
|
||||
{
|
||||
mapped_frames.clear();
|
||||
av_buffer_ptr va_ctx(av_hwframe_ctx_alloc(hw_ctx_vaapi.get()));
|
||||
if (!va_ctx)
|
||||
{
|
||||
throw std::runtime_error("Failed to create VAAPI frame context.");
|
||||
}
|
||||
AVHWFramesContext * va_frames_ctx = (AVHWFramesContext *)(va_ctx->data);
|
||||
va_frames_ctx->format = AV_PIX_FMT_VAAPI;
|
||||
va_frames_ctx->sw_format = vk_format_to_av_format(format);
|
||||
va_frames_ctx->width = width;
|
||||
va_frames_ctx->height = height;
|
||||
va_frames_ctx->initial_pool_size = num_images;
|
||||
int err = av_hwframe_ctx_init(va_ctx.get());
|
||||
if (err)
|
||||
{
|
||||
throw std::system_error(err, av_error_category(), "Failed to create VAAPI frame context");
|
||||
}
|
||||
|
||||
mapped_frames.reserve(num_images);
|
||||
for (int i = 0; i < num_images; ++i)
|
||||
{
|
||||
VkMemoryRequirements req;
|
||||
vk->vkGetImageMemoryRequirements(vk->device, images[i], &req);
|
||||
|
||||
int fd;
|
||||
VkMemoryGetFdInfoKHR export_info{};
|
||||
export_info.sType = VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR;
|
||||
export_info.memory = memory[i];
|
||||
export_info.handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT;
|
||||
vk->vkGetMemoryFdKHR(vk->device, &export_info, &fd);
|
||||
|
||||
auto drm_frame = make_av_frame();
|
||||
drm_frame->format = AV_PIX_FMT_DRM_PRIME;
|
||||
drm_frame->width = width;
|
||||
drm_frame->height = height;
|
||||
drm_frame->buf[0] = av_buffer_alloc(sizeof(AVDRMFrameDescriptor));
|
||||
drm_frame->data[0] = drm_frame->buf[0]->data;
|
||||
auto & drm_frame_desc = *(AVDRMFrameDescriptor *)drm_frame->data[0];
|
||||
drm_frame_desc.nb_objects = 1;
|
||||
drm_frame_desc.objects[0].fd = fd;
|
||||
drm_frame_desc.objects[0].size = req.size;
|
||||
drm_frame_desc.nb_layers = 1;
|
||||
drm_frame_desc.layers[0].format = vk_format_to_fourcc(format);
|
||||
drm_frame_desc.layers[0].nb_planes = 1;
|
||||
drm_frame_desc.layers[0].planes[0].object_index = 0;
|
||||
|
||||
// DRM format modifiers seem to be broken on ffmpeg or radeon, or both
|
||||
bool drm_tiling = use_drm_format_modifiers and vk->has_EXT_image_drm_format_modifier;
|
||||
if (drm_tiling)
|
||||
{
|
||||
VkImageDrmFormatModifierPropertiesEXT modifiers{};
|
||||
modifiers.sType = VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_PROPERTIES_EXT;
|
||||
vk->vkGetImageDrmFormatModifierPropertiesEXT(vk->device, images[i], &modifiers);
|
||||
drm_frame_desc.objects[0].format_modifier = modifiers.drmFormatModifier;
|
||||
}
|
||||
// if we don't have modifiers, we did linear tiling
|
||||
VkImageSubresource subresource{(use_drm_format_modifiers and vk->has_EXT_image_drm_format_modifier)
|
||||
? VK_IMAGE_ASPECT_MEMORY_PLANE_0_BIT_EXT
|
||||
: VK_IMAGE_ASPECT_COLOR_BIT,
|
||||
0,
|
||||
0};
|
||||
VkSubresourceLayout layout;
|
||||
vk->vkGetImageSubresourceLayout(vk->device, images[i], &subresource, &layout);
|
||||
drm_frame_desc.layers[0].planes[0].offset = layout.offset;
|
||||
drm_frame_desc.layers[0].planes[0].pitch = layout.rowPitch;
|
||||
|
||||
auto va_frame = make_av_frame();
|
||||
err = av_hwframe_get_buffer(va_ctx.get(), va_frame.get(), 0);
|
||||
if (err)
|
||||
throw std::system_error(err, av_error_category(), "Failed to create VAAPI frame");
|
||||
err = av_hwframe_map(va_frame.get(), drm_frame.get(), AV_HWFRAME_MAP_DIRECT);
|
||||
if (err)
|
||||
throw std::system_error(err, av_error_category(), "Failed to map DRM frame to VAAPI frame");
|
||||
va_frame->crop_left = offset_x;
|
||||
va_frame->crop_right = width - this->width - offset_x;
|
||||
va_frame->crop_top = offset_y;
|
||||
va_frame->crop_bottom = height - this->height - offset_y;
|
||||
mapped_frames.push_back(std::move(va_frame));
|
||||
}
|
||||
|
||||
InitFilterGraph();
|
||||
}
|
||||
|
||||
void VideoEncoderVA::InitFilterGraph()
|
||||
{
|
||||
assert(not mapped_frames.empty());
|
||||
|
||||
filter_graph.reset(avfilter_graph_alloc());
|
||||
|
||||
AVFilterInOut * outputs = avfilter_inout_alloc();
|
||||
AVFilterInOut * inputs = avfilter_inout_alloc();
|
||||
|
||||
std::stringstream buffer_filter_args;
|
||||
buffer_filter_args << "video_size=" << mapped_frames[0]->width << "x" << mapped_frames[0]->height;
|
||||
buffer_filter_args << ":pix_fmt=" << mapped_frames[0]->format;
|
||||
buffer_filter_args << ":time_base=" << encoder_ctx->time_base.num << "/" << encoder_ctx->time_base.den;
|
||||
int err;
|
||||
if ((err = avfilter_graph_create_filter(&filter_in, avfilter_get_by_name("buffer"), "in", buffer_filter_args.str().c_str(), NULL, filter_graph.get())))
|
||||
{
|
||||
throw std::system_error(err, av_error_category(), "filter_in creation failed");
|
||||
}
|
||||
AVBufferSrcParameters * par = av_buffersrc_parameters_alloc();
|
||||
memset(par, 0, sizeof(*par));
|
||||
par->format = AV_PIX_FMT_NONE;
|
||||
par->hw_frames_ctx = av_buffer_ref(mapped_frames[0]->hw_frames_ctx);
|
||||
av_buffersrc_parameters_set(filter_in, par);
|
||||
av_free(par);
|
||||
|
||||
if ((err = avfilter_graph_create_filter(&filter_out, avfilter_get_by_name("buffersink"), "out", NULL, NULL, filter_graph.get())))
|
||||
{
|
||||
throw std::system_error(err, av_error_category(), "filter_out creation failed");
|
||||
}
|
||||
|
||||
outputs->name = av_strdup("in");
|
||||
outputs->filter_ctx = filter_in;
|
||||
outputs->pad_idx = 0;
|
||||
outputs->next = NULL;
|
||||
|
||||
inputs->name = av_strdup("out");
|
||||
inputs->filter_ctx = filter_out;
|
||||
inputs->pad_idx = 0;
|
||||
inputs->next = NULL;
|
||||
|
||||
std::string scale_param = "scale_vaapi=format=nv12:w=" + std::to_string(encoder_ctx->width) +
|
||||
":h=" + std::to_string(encoder_ctx->height);
|
||||
err = avfilter_graph_parse_ptr(filter_graph.get(), scale_param.c_str(), &inputs, &outputs, NULL);
|
||||
avfilter_inout_free(&outputs);
|
||||
avfilter_inout_free(&inputs);
|
||||
if (err < 0)
|
||||
{
|
||||
throw std::system_error(err, av_error_category(), "avfilter_graph_parse_ptr failed");
|
||||
}
|
||||
|
||||
if ((err = avfilter_graph_config(filter_graph.get(), NULL)))
|
||||
{
|
||||
throw std::system_error(err, av_error_category(), "avfilter_graph_config failed");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
/*
|
||||
* 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 "VideoEncoderFFMPEG.h"
|
||||
#include "ffmpeg_helper.h"
|
||||
#include "vk/vk_helpers.h"
|
||||
|
||||
extern "C"
|
||||
{
|
||||
#include <libavutil/version.h>
|
||||
}
|
||||
|
||||
// DRM format modifiers are not implemented before ffmpeg 5
|
||||
inline const bool use_drm_format_modifiers = LIBAVUTIL_VERSION_MAJOR >= 57;
|
||||
|
||||
struct AVFilterContext;
|
||||
|
||||
class VideoEncoderVA : public VideoEncoderFFMPEG
|
||||
{
|
||||
public:
|
||||
VideoEncoderVA(vk_bundle * vk, const xrt::drivers::wivrn::encoder_settings & settings, float fps);
|
||||
|
||||
void
|
||||
SetImages(int width,
|
||||
int height,
|
||||
VkFormat format,
|
||||
int num_images,
|
||||
VkImage * images,
|
||||
VkImageView * views,
|
||||
VkDeviceMemory * memory) override;
|
||||
|
||||
void
|
||||
PushFrame(uint32_t frame_index, bool idr, std::chrono::steady_clock::time_point pts) override;
|
||||
|
||||
private:
|
||||
void
|
||||
InitFilterGraph();
|
||||
|
||||
vk_bundle * vk;
|
||||
int width;
|
||||
int height;
|
||||
// relevant part of the input image to encode
|
||||
int offset_x;
|
||||
int offset_y;
|
||||
av_buffer_ptr hw_ctx_vaapi;
|
||||
std::vector<av_frame_ptr> mapped_frames;
|
||||
av_filter_graph_ptr filter_graph;
|
||||
AVFilterContext * filter_in = nullptr;
|
||||
AVFilterContext * filter_out = nullptr;
|
||||
};
|
||||
@@ -0,0 +1,122 @@
|
||||
/*
|
||||
* 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_helper.h"
|
||||
#include <libdrm/drm_fourcc.h>
|
||||
#include <vulkan/vulkan.h>
|
||||
|
||||
extern "C"
|
||||
{
|
||||
#include <libavcodec/avcodec.h>
|
||||
#include <libavfilter/avfilter.h>
|
||||
#include <libavutil/hwcontext.h>
|
||||
#include <libavutil/opt.h>
|
||||
}
|
||||
|
||||
namespace
|
||||
{
|
||||
struct : public std::error_category
|
||||
{
|
||||
const char *
|
||||
name() const noexcept override
|
||||
{
|
||||
return "ffmpeg";
|
||||
}
|
||||
std::string
|
||||
message(int averror) const override
|
||||
{
|
||||
char av_msg[AV_ERROR_MAX_STRING_SIZE];
|
||||
av_strerror(averror, av_msg, sizeof(av_msg));
|
||||
return av_msg;
|
||||
}
|
||||
} error_category;
|
||||
} // namespace
|
||||
|
||||
const std::error_category &
|
||||
av_error_category()
|
||||
{
|
||||
return error_category;
|
||||
};
|
||||
|
||||
// it seems that ffmpeg does not provide this mapping
|
||||
// todo: for monado async reprojection, VK_FORMAT_B8G8R8A8_UNORM has to be supported
|
||||
AVPixelFormat
|
||||
vk_format_to_av_format(VkFormat vk_fmt)
|
||||
{
|
||||
switch (vk_fmt)
|
||||
{
|
||||
case VK_FORMAT_B8G8R8A8_SRGB:
|
||||
return AV_PIX_FMT_BGRA;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
throw std::runtime_error("unsupported vulkan pixel format " + std::to_string((VkFormat)vk_fmt));
|
||||
}
|
||||
|
||||
uint32_t
|
||||
vk_format_to_fourcc(VkFormat vk_fmt)
|
||||
{
|
||||
switch (vk_fmt)
|
||||
{
|
||||
case VK_FORMAT_B8G8R8A8_SRGB:
|
||||
return DRM_FORMAT_ARGB8888;
|
||||
case VK_FORMAT_B8G8R8A8_UNORM:
|
||||
return DRM_FORMAT_ARGB8888;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
throw std::runtime_error("unsupported vulkan pixel format " + std::to_string((VkFormat)vk_fmt));
|
||||
}
|
||||
|
||||
void AvDeleter::operator()(AVBufferRef * x)
|
||||
{
|
||||
av_buffer_unref(&x);
|
||||
}
|
||||
|
||||
void AvDeleter::operator()(AVFrame * x)
|
||||
{
|
||||
av_frame_unref(x);
|
||||
}
|
||||
|
||||
void AvDeleter::operator()(AVCodecContext * x)
|
||||
{
|
||||
avcodec_free_context(&x);
|
||||
}
|
||||
|
||||
void AvDeleter::operator()(AVFilterGraph * x)
|
||||
{
|
||||
avfilter_graph_free(&x);
|
||||
}
|
||||
|
||||
void AvDeleter::operator()(AVPacket * x)
|
||||
{
|
||||
av_packet_free(&x);
|
||||
}
|
||||
|
||||
av_frame_ptr
|
||||
make_av_frame(AVFrame * frame)
|
||||
{
|
||||
return av_frame_ptr(frame);
|
||||
}
|
||||
|
||||
av_frame_ptr
|
||||
make_av_frame()
|
||||
{
|
||||
return make_av_frame(av_frame_alloc());
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
/*
|
||||
* 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 <memory>
|
||||
#include <system_error>
|
||||
#include <vulkan/vulkan_core.h>
|
||||
|
||||
struct AVBufferRef;
|
||||
struct AVFilterGraph;
|
||||
struct AVFrame;
|
||||
struct AVCodecContext;
|
||||
struct AVPacket;
|
||||
|
||||
extern "C"
|
||||
{
|
||||
#include <libavutil/avutil.h>
|
||||
}
|
||||
|
||||
const std::error_category &
|
||||
av_error_category();
|
||||
|
||||
AVPixelFormat
|
||||
vk_format_to_av_format(VkFormat vk_fmt);
|
||||
|
||||
uint32_t
|
||||
vk_format_to_fourcc(VkFormat vk_fmt);
|
||||
|
||||
struct AvDeleter
|
||||
{
|
||||
void
|
||||
operator()(AVBufferRef *);
|
||||
void
|
||||
operator()(AVFrame *);
|
||||
void
|
||||
operator()(AVCodecContext *);
|
||||
void
|
||||
operator()(AVFilterGraph *);
|
||||
void
|
||||
operator()(AVPacket *);
|
||||
};
|
||||
|
||||
using av_buffer_ptr = std::unique_ptr<AVBufferRef, AvDeleter>;
|
||||
using av_frame_ptr = std::unique_ptr<AVFrame, AvDeleter>;
|
||||
using av_codec_context_ptr = std::unique_ptr<AVCodecContext, AvDeleter>;
|
||||
using av_filter_graph_ptr = std::unique_ptr<AVFilterGraph, AvDeleter>;
|
||||
using av_packet_ptr = std::unique_ptr<AVPacket, AvDeleter>;
|
||||
|
||||
av_buffer_ptr
|
||||
make_av_buffer(AVBufferRef *);
|
||||
|
||||
av_frame_ptr
|
||||
make_av_frame(AVFrame *);
|
||||
|
||||
av_frame_ptr
|
||||
make_av_frame();
|
||||
@@ -0,0 +1,46 @@
|
||||
/*
|
||||
* 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/>.
|
||||
*/
|
||||
|
||||
#version 450
|
||||
|
||||
layout (binding = 0) uniform sampler2D image;
|
||||
|
||||
layout (location = 0) in vec2 pos;
|
||||
|
||||
layout (location = 0) out vec2 uv;
|
||||
|
||||
float gamma(float x)
|
||||
{
|
||||
if (x <= 0.0031308)
|
||||
return 12.92 * x;
|
||||
else
|
||||
return 1.055 * pow(x, 1/2.4) - 0.055;
|
||||
}
|
||||
|
||||
vec4 gamma4(vec4 x)
|
||||
{
|
||||
return vec4(gamma(x.r), gamma(x.g), gamma(x.b), gamma(x.a));
|
||||
}
|
||||
|
||||
void main() {
|
||||
vec4 rgba = gamma4(texture(image, pos));
|
||||
uv.x = 0.5 + rgba.r * -0.1146 + rgba.g * -0.3854 + rgba.b * 0.5;
|
||||
uv.y = 0.5 + rgba.r * 0.5 + rgba.g * -0.4542 + rgba.b * -0.0458;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
/*
|
||||
* 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/>.
|
||||
*/
|
||||
|
||||
#version 450
|
||||
|
||||
layout (location = 0) out vec2 outUV;
|
||||
|
||||
void main() {
|
||||
outUV = vec2((gl_VertexIndex << 1) & 2, gl_VertexIndex & 2); // [(0, 0), (2, 0), (0, 2)]
|
||||
gl_Position = vec4(outUV * 2.0f + -1.0f, 0.0f, 1.0f); // [(-1, -1), (3, -1), (-1, 3)]
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
/*
|
||||
* 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/>.
|
||||
*/
|
||||
|
||||
#version 450
|
||||
|
||||
layout (binding = 0) uniform sampler2D image;
|
||||
|
||||
layout (location = 0) in vec2 pos;
|
||||
|
||||
layout (location = 0) out float y;
|
||||
|
||||
float gamma(float x)
|
||||
{
|
||||
if (x <= 0.0031308)
|
||||
return 12.92 * x;
|
||||
else
|
||||
return 1.055 * pow(x, 1/2.4) - 0.055;
|
||||
}
|
||||
|
||||
vec4 gamma4(vec4 x)
|
||||
{
|
||||
return vec4(gamma(x.r), gamma(x.g), gamma(x.b), gamma(x.a));
|
||||
}
|
||||
|
||||
void main() {
|
||||
vec4 rgba = gamma4(texture(image, pos));
|
||||
y = rgba.r * 0.2126 + rgba.g * 0.7152 + rgba.b * 0.0722;
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
/*
|
||||
* 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 first because of incompatibility between Eigen and X includes
|
||||
#include "driver/wivrn_session.h"
|
||||
|
||||
#include "video_encoder.h"
|
||||
#include "util/u_logging.h"
|
||||
|
||||
#include <string>
|
||||
|
||||
#include "wivrn_config.h"
|
||||
|
||||
#ifdef WIVRN_USE_NVENC
|
||||
#include "video_encoder_nvenc.h"
|
||||
#endif
|
||||
#ifdef WIVRN_USE_VAAPI
|
||||
#include "ffmpeg/VideoEncoderVA.h"
|
||||
#endif
|
||||
#ifdef WIVRN_USE_X264
|
||||
#include "video_encoder_x264.h"
|
||||
#endif
|
||||
|
||||
namespace xrt::drivers::wivrn
|
||||
{
|
||||
|
||||
std::unique_ptr<VideoEncoder> VideoEncoder::Create(
|
||||
vk_bundle * vk,
|
||||
vk_cmd_pool & pool,
|
||||
encoder_settings & settings,
|
||||
uint8_t stream_idx,
|
||||
int input_width,
|
||||
int input_height,
|
||||
float fps)
|
||||
{
|
||||
using namespace std::string_literals;
|
||||
std::unique_ptr<VideoEncoder> res;
|
||||
#ifdef WIVRN_USE_X264
|
||||
if (settings.encoder_name == encoder_x264)
|
||||
{
|
||||
res = std::make_unique<VideoEncoderX264>(vk, pool, settings, input_width, input_height, fps);
|
||||
}
|
||||
#endif
|
||||
#ifdef WIVRN_USE_NVENC
|
||||
if (settings.encoder_name == encoder_nvenc)
|
||||
{
|
||||
res = std::make_unique<VideoEncoderNvenc>(vk, settings, fps);
|
||||
}
|
||||
#endif
|
||||
#ifdef WIVRN_USE_VAAPI
|
||||
if (settings.encoder_name == encoder_vaapi)
|
||||
{
|
||||
res = std::make_unique<VideoEncoderVA>(vk, settings, fps);
|
||||
}
|
||||
#endif
|
||||
if (res)
|
||||
{
|
||||
res->stream_idx = stream_idx;
|
||||
}
|
||||
else
|
||||
{
|
||||
U_LOG_E("No video encoder %s", settings.encoder_name.c_str());
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
void VideoEncoder::SyncNeeded()
|
||||
{
|
||||
sync_needed = true;
|
||||
}
|
||||
|
||||
void VideoEncoder::Encode(wivrn_session & cnx,
|
||||
const to_headset::video_stream_data_shard::view_info_t & view_info,
|
||||
uint64_t frame_index,
|
||||
int index)
|
||||
{
|
||||
this->cnx = &cnx;
|
||||
auto target_timestamp = std::chrono::steady_clock::time_point(std::chrono::nanoseconds(view_info.display_time));
|
||||
bool idr = sync_needed.exchange(false);
|
||||
const char* extra = idr ? ",idr" : ",p";
|
||||
cnx.dump_time("encode_begin", frame_index, os_monotonic_get_ns(), stream_idx, extra);
|
||||
|
||||
// Prepare the video shard template
|
||||
shard.stream_item_idx = stream_idx;
|
||||
shard.frame_idx = frame_index;
|
||||
shard.shard_idx = 0;
|
||||
shard.view_info = view_info;
|
||||
|
||||
Encode(index, idr, target_timestamp);
|
||||
cnx.dump_time("encode_end", frame_index, os_monotonic_get_ns(), stream_idx, extra);
|
||||
}
|
||||
|
||||
void VideoEncoder::SendData(std::span<uint8_t> data, bool end_of_frame)
|
||||
{
|
||||
std::lock_guard lock(mutex);
|
||||
#if 0
|
||||
std::ofstream debug("/tmp/video_dump-" + std::to_string(stream_idx), std::ios::app);
|
||||
debug.write((char*)data.data(), data.size());
|
||||
#endif
|
||||
if (shard.shard_idx == 0)
|
||||
cnx->dump_time("send_begin", shard.frame_idx, os_monotonic_get_ns(), stream_idx);
|
||||
|
||||
shard.flags = to_headset::video_stream_data_shard::start_of_slice;
|
||||
auto begin = data.begin();
|
||||
auto end = data.end();
|
||||
while (begin != end)
|
||||
{
|
||||
const size_t view_info_size = sizeof(to_headset::video_stream_data_shard::view_info_t);
|
||||
const size_t max_payload_size = to_headset::video_stream_data_shard::max_payload_size - (shard.view_info ? view_info_size : 0);
|
||||
auto next = std::min(end, begin + max_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.payload = {begin, next};
|
||||
cnx->send_stream(shard);
|
||||
++shard.shard_idx;
|
||||
shard.flags = 0;
|
||||
shard.view_info.reset();
|
||||
begin = next;
|
||||
}
|
||||
if (end_of_frame)
|
||||
cnx->dump_time("send_end", shard.frame_idx, os_monotonic_get_ns(), stream_idx);
|
||||
}
|
||||
|
||||
} // namespace xrt::drivers::wivrn
|
||||
@@ -0,0 +1,98 @@
|
||||
/*
|
||||
* 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/vk_cmd_pool.h"
|
||||
#include "vk/vk_helpers.h"
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <vulkan/vulkan.h>
|
||||
|
||||
#include "encoder_settings.h"
|
||||
#include "wivrn_packets.h"
|
||||
|
||||
namespace xrt::drivers::wivrn
|
||||
{
|
||||
|
||||
class wivrn_session;
|
||||
|
||||
inline const char * encoder_nvenc = "nvenc";
|
||||
inline const char * encoder_vaapi = "vaapi";
|
||||
inline const char * encoder_x264 = "x264";
|
||||
|
||||
class VideoEncoder
|
||||
{
|
||||
std::mutex mutex;
|
||||
|
||||
protected:
|
||||
uint8_t stream_idx;
|
||||
|
||||
private:
|
||||
// temporary data
|
||||
wivrn_session * cnx;
|
||||
|
||||
// shard to send
|
||||
to_headset::video_stream_data_shard shard;
|
||||
|
||||
std::atomic_bool sync_needed = true;
|
||||
|
||||
public:
|
||||
static std::unique_ptr<VideoEncoder> Create(vk_bundle * vk,
|
||||
vk_cmd_pool & pool,
|
||||
encoder_settings & settings,
|
||||
uint8_t stream_idx,
|
||||
int input_width,
|
||||
int input_height,
|
||||
float fps);
|
||||
|
||||
virtual ~VideoEncoder() = default;
|
||||
|
||||
// set input images to be encoded.
|
||||
// later referred by index only
|
||||
virtual void SetImages(int width,
|
||||
int height,
|
||||
VkFormat format,
|
||||
int num_images,
|
||||
VkImage * images,
|
||||
VkImageView * views,
|
||||
VkDeviceMemory * memory) = 0;
|
||||
|
||||
// optional entrypoint, called on present to submit command buffers for the image.
|
||||
virtual void PresentImage(int index, VkCommandBuffer * out_buffer)
|
||||
{}
|
||||
|
||||
// The other end lost a frame and needs to resynchronize
|
||||
void SyncNeeded();
|
||||
|
||||
void Encode(wivrn_session & cnx,
|
||||
const to_headset::video_stream_data_shard::view_info_t & view_info,
|
||||
uint64_t frame_index,
|
||||
int index);
|
||||
|
||||
protected:
|
||||
// encode the image at provided index.
|
||||
virtual void Encode(int index, bool idr, std::chrono::steady_clock::time_point target_timestamp) = 0;
|
||||
|
||||
void SendData(std::span<uint8_t> data, bool end_of_frame);
|
||||
};
|
||||
|
||||
} // namespace xrt::drivers::wivrn
|
||||
@@ -0,0 +1,292 @@
|
||||
/*
|
||||
* 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 "video_encoder_nvenc.h"
|
||||
|
||||
#include "vk/vk_helpers.h"
|
||||
#include <stdexcept>
|
||||
|
||||
#define NVENC_CHECK_NOENCODER(x) \
|
||||
do \
|
||||
{ \
|
||||
NVENCSTATUS status = x; \
|
||||
if (status != NV_ENC_SUCCESS) \
|
||||
{ \
|
||||
U_LOG_E("%s:%d: %d", __FILE__, __LINE__, status); \
|
||||
throw std::runtime_error("TODO"); \
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
#define NVENC_CHECK(x) \
|
||||
do \
|
||||
{ \
|
||||
NVENCSTATUS status = x; \
|
||||
if (status != NV_ENC_SUCCESS) \
|
||||
{ \
|
||||
U_LOG_E("%s:%d: %d, %s", __FILE__, __LINE__, status, fn.nvEncGetLastErrorString(session_handle)); \
|
||||
throw std::runtime_error("TODO"); \
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
#define CU_CHECK(x) \
|
||||
do \
|
||||
{ \
|
||||
CUresult status = x; \
|
||||
if (status != CUDA_SUCCESS) \
|
||||
{ \
|
||||
const char * error_string; \
|
||||
cuGetErrorString(status, &error_string); \
|
||||
U_LOG_E("%s:%d: %s (%d)", __FILE__, __LINE__, error_string, (int)status); \
|
||||
throw std::runtime_error("TODO"); \
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
namespace xrt::drivers::wivrn
|
||||
{
|
||||
|
||||
VideoEncoderNvenc::VideoEncoderNvenc(vk_bundle * vk, const encoder_settings & settings, float fps) :
|
||||
vk(vk), offset_x(settings.offset_x), offset_y(settings.offset_y), width(settings.width), height(settings.height), codec(settings.codec), fps(fps), bitrate(settings.bitrate)
|
||||
{
|
||||
CU_CHECK(cuInit(0));
|
||||
|
||||
CU_CHECK(cuCtxCreate(&cuda, 0, 0));
|
||||
|
||||
fn.version = NV_ENCODE_API_FUNCTION_LIST_VER;
|
||||
NVENC_CHECK_NOENCODER(NvEncodeAPICreateInstance(&fn));
|
||||
|
||||
NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS params{};
|
||||
params.version = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER;
|
||||
params.deviceType = NV_ENC_DEVICE_TYPE_CUDA;
|
||||
params.device = cuda;
|
||||
params.apiVersion = NVENCAPI_VERSION;
|
||||
|
||||
NVENC_CHECK_NOENCODER(fn.nvEncOpenEncodeSessionEx(¶ms, &session_handle));
|
||||
|
||||
uint32_t count;
|
||||
std::vector<GUID> presets;
|
||||
auto encodeGUID = codec == video_codec::h264 ? NV_ENC_CODEC_H264_GUID : NV_ENC_CODEC_HEVC_GUID;
|
||||
NVENC_CHECK(fn.nvEncGetEncodePresetCount(session_handle, encodeGUID, &count));
|
||||
presets.resize(count);
|
||||
NVENC_CHECK(fn.nvEncGetEncodePresetGUIDs(session_handle, encodeGUID, presets.data(), count, &count));
|
||||
|
||||
switch (codec)
|
||||
{
|
||||
case video_codec::h264:
|
||||
printf("%d H264 presets\n", count);
|
||||
break;
|
||||
|
||||
case video_codec::h265:
|
||||
printf("%d HEVC presets\n", count);
|
||||
break;
|
||||
}
|
||||
|
||||
for (GUID & i: presets)
|
||||
{
|
||||
printf(" Preset {%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}\n", i.Data1, i.Data2, i.Data3, i.Data4[0], i.Data4[1], i.Data4[2], i.Data4[3], i.Data4[4], i.Data4[5], i.Data4[6], i.Data4[7]);
|
||||
}
|
||||
|
||||
NV_ENC_CAPS_PARAM cap_param{};
|
||||
cap_param.version = NV_ENC_CAPS_PARAM_VER;
|
||||
cap_param.capsToQuery = NV_ENC_CAPS_SUPPORT_REF_PIC_INVALIDATION;
|
||||
int cap_value;
|
||||
NVENC_CHECK(fn.nvEncGetEncodeCaps(session_handle, encodeGUID, &cap_param, &cap_value));
|
||||
supports_frame_invalidation = cap_value;
|
||||
if (supports_frame_invalidation)
|
||||
printf("Frame invalidation supported\n");
|
||||
else
|
||||
printf("Frame invalidation not supported\n");
|
||||
}
|
||||
|
||||
void VideoEncoderNvenc::SetImages(int full_width,
|
||||
int full_height,
|
||||
VkFormat format,
|
||||
int num_images,
|
||||
VkImage * images,
|
||||
VkImageView * views,
|
||||
VkDeviceMemory * memory)
|
||||
{
|
||||
auto encodeGUID = codec == video_codec::h264 ? NV_ENC_CODEC_H264_GUID : NV_ENC_CODEC_HEVC_GUID;
|
||||
// auto presetGUID = codec == video_codec::h264 ? NV_ENC_PRESET_LOW_LATENCY_DEFAULT_GUID :
|
||||
// NV_ENC_PRESET_P7_GUID;
|
||||
#pragma GCC diagnostic push
|
||||
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
|
||||
auto presetGUID = NV_ENC_PRESET_LOW_LATENCY_HQ_GUID;
|
||||
#pragma GCC diagnostic pop
|
||||
NV_ENC_PRESET_CONFIG preset_config;
|
||||
preset_config.version = NV_ENC_PRESET_CONFIG_VER;
|
||||
preset_config.presetCfg.version = NV_ENC_CONFIG_VER;
|
||||
NVENC_CHECK(fn.nvEncGetEncodePresetConfig(session_handle, encodeGUID, presetGUID, &preset_config));
|
||||
|
||||
NV_ENC_CONFIG params = preset_config.presetCfg;
|
||||
|
||||
// Bitrate control
|
||||
params.rcParams.rateControlMode = NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ;
|
||||
params.rcParams.averageBitRate = bitrate;
|
||||
params.rcParams.maxBitRate = bitrate;
|
||||
params.rcParams.vbvBufferSize = bitrate / fps;
|
||||
params.rcParams.vbvInitialDelay = bitrate / fps;
|
||||
|
||||
params.gopLength = NVENC_INFINITE_GOPLENGTH;
|
||||
params.frameIntervalP = 1;
|
||||
|
||||
switch (codec)
|
||||
{
|
||||
case video_codec::h264:
|
||||
params.encodeCodecConfig.h264Config.repeatSPSPPS = 1;
|
||||
params.encodeCodecConfig.h264Config.maxNumRefFrames = 0;
|
||||
params.encodeCodecConfig.h264Config.idrPeriod = NVENC_INFINITE_GOPLENGTH;
|
||||
break;
|
||||
case video_codec::h265:
|
||||
params.encodeCodecConfig.hevcConfig.repeatSPSPPS = 1;
|
||||
params.encodeCodecConfig.hevcConfig.maxNumRefFramesInDPB = 0;
|
||||
params.encodeCodecConfig.hevcConfig.idrPeriod = NVENC_INFINITE_GOPLENGTH;
|
||||
break;
|
||||
}
|
||||
|
||||
NV_ENC_INITIALIZE_PARAMS params2{};
|
||||
params2.version = NV_ENC_INITIALIZE_PARAMS_VER;
|
||||
params2.encodeGUID = encodeGUID;
|
||||
params2.presetGUID = presetGUID;
|
||||
params2.encodeWidth = uint32_t(width);
|
||||
params2.encodeHeight = uint32_t(height);
|
||||
params2.darWidth = uint32_t(width);
|
||||
params2.darHeight = uint32_t(height);
|
||||
params2.frameRateNum = (uint32_t)fps;
|
||||
params2.frameRateDen = 1;
|
||||
params2.enableEncodeAsync = 0;
|
||||
params2.enablePTD = 1;
|
||||
params2.reportSliceOffsets = 0;
|
||||
params2.enableSubFrameWrite = 0;
|
||||
params2.enableExternalMEHints = 0;
|
||||
params2.enableMEOnlyMode = 0;
|
||||
params2.enableWeightedPrediction = 0;
|
||||
params2.enableOutputInVidmem = 0;
|
||||
params2.encodeConfig = ¶ms;
|
||||
params2.maxEncodeWidth = 0;
|
||||
params2.maxEncodeHeight = 0;
|
||||
params2.bufferFormat = NV_ENC_BUFFER_FORMAT_UNDEFINED;
|
||||
NVENC_CHECK(fn.nvEncInitializeEncoder(session_handle, ¶ms2));
|
||||
|
||||
NV_ENC_CREATE_BITSTREAM_BUFFER params3;
|
||||
params3.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
|
||||
NVENC_CHECK(fn.nvEncCreateBitstreamBuffer(session_handle, ¶ms3));
|
||||
bitstreamBuffer = params3.bitstreamBuffer;
|
||||
|
||||
// TODO: cleanup on error
|
||||
this->images.resize(num_images);
|
||||
CU_CHECK(cuCtxPushCurrent(cuda));
|
||||
for (int i = 0; i < num_images; i++)
|
||||
{
|
||||
VkMemoryGetFdInfoKHR getinfo{};
|
||||
getinfo.sType = VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR;
|
||||
getinfo.pNext = nullptr;
|
||||
getinfo.memory = memory[i];
|
||||
getinfo.handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT;
|
||||
|
||||
int fd;
|
||||
VkResult res = vk->vkGetMemoryFdKHR(vk->device, &getinfo, &fd);
|
||||
VK_CHK_WITH_RET(res, "vkGetMemoryFdKHR", );
|
||||
|
||||
VkMemoryRequirements memoryreq;
|
||||
vk->vkGetImageMemoryRequirements(vk->device, images[i], &memoryreq);
|
||||
|
||||
CUexternalMemory extmem;
|
||||
CUDA_EXTERNAL_MEMORY_HANDLE_DESC param{};
|
||||
param.type = CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD;
|
||||
param.handle.fd = fd;
|
||||
param.size = memoryreq.size;
|
||||
param.flags = 0;
|
||||
CU_CHECK(cuImportExternalMemory(&extmem, ¶m));
|
||||
|
||||
CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC param2{};
|
||||
param2.offset = 0;
|
||||
param2.arrayDesc.Width = (size_t)full_width;
|
||||
param2.arrayDesc.Height = (size_t)full_height, param2.arrayDesc.Depth = 0;
|
||||
param2.arrayDesc.Format = CU_AD_FORMAT_UNSIGNED_INT32, param2.arrayDesc.NumChannels = 1;
|
||||
param2.arrayDesc.Flags = 0; // CUDA_ARRAY3D_SURFACE_LDST,
|
||||
param2.numLevels = 1;
|
||||
CU_CHECK(cuExternalMemoryGetMappedMipmappedArray(&this->images[i].cuda_image, extmem, ¶m2));
|
||||
CU_CHECK(cuMipmappedArrayGetLevel(&this->images[i].cuda_array, this->images[i].cuda_image, 0));
|
||||
}
|
||||
|
||||
CU_CHECK(cuMemAllocPitch(&frame, &pitch, width * 4, height, 4));
|
||||
|
||||
NV_ENC_REGISTER_RESOURCE param3{};
|
||||
param3.version = NV_ENC_REGISTER_RESOURCE_VER;
|
||||
param3.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_CUDADEVICEPTR;
|
||||
param3.width = width;
|
||||
param3.height = height;
|
||||
param3.pitch = pitch;
|
||||
param3.resourceToRegister = (void *)frame;
|
||||
param3.bufferFormat = NV_ENC_BUFFER_FORMAT_ARGB;
|
||||
param3.bufferUsage = NV_ENC_INPUT_IMAGE;
|
||||
NVENC_CHECK(fn.nvEncRegisterResource(session_handle, ¶m3));
|
||||
nvenc_resource = param3.registeredResource;
|
||||
CU_CHECK(cuCtxPopCurrent(NULL));
|
||||
}
|
||||
|
||||
void VideoEncoderNvenc::Encode(int index, bool idr, std::chrono::steady_clock::time_point pts)
|
||||
{
|
||||
CU_CHECK(cuCtxPushCurrent(cuda));
|
||||
CUDA_MEMCPY2D copy{};
|
||||
copy.srcXInBytes = offset_x * 4;
|
||||
copy.srcY = offset_y;
|
||||
copy.srcMemoryType = CU_MEMORYTYPE_ARRAY;
|
||||
copy.srcArray = images[index].cuda_array;
|
||||
copy.dstMemoryType = CU_MEMORYTYPE_DEVICE;
|
||||
copy.dstDevice = frame;
|
||||
copy.dstPitch = pitch;
|
||||
copy.WidthInBytes = width * 4;
|
||||
copy.Height = height;
|
||||
CU_CHECK(cuMemcpy2D(©));
|
||||
|
||||
NV_ENC_MAP_INPUT_RESOURCE param4{};
|
||||
param4.version = NV_ENC_MAP_INPUT_RESOURCE_VER;
|
||||
param4.registeredResource = nvenc_resource;
|
||||
NVENC_CHECK(fn.nvEncMapInputResource(session_handle, ¶m4));
|
||||
|
||||
NV_ENC_PIC_PARAMS param{};
|
||||
param.version = NV_ENC_PIC_PARAMS_VER;
|
||||
param.inputWidth = width;
|
||||
param.inputHeight = height;
|
||||
param.inputPitch = width;
|
||||
param.encodePicFlags = (uint32_t)(idr ? NV_ENC_PIC_TYPE_IDR : NV_ENC_PIC_TYPE_P);
|
||||
param.frameIdx = 0;
|
||||
param.inputTimeStamp = 0;
|
||||
param.inputBuffer = param4.mappedResource;
|
||||
param.outputBitstream = bitstreamBuffer;
|
||||
param.bufferFmt = param4.mappedBufferFmt;
|
||||
param.pictureStruct = NV_ENC_PIC_STRUCT_FRAME;
|
||||
NVENC_CHECK(fn.nvEncEncodePicture(session_handle, ¶m));
|
||||
|
||||
NV_ENC_LOCK_BITSTREAM param2{};
|
||||
param2.version = NV_ENC_LOCK_BITSTREAM_VER;
|
||||
param2.doNotWait = 0;
|
||||
param2.outputBitstream = bitstreamBuffer;
|
||||
NVENC_CHECK(fn.nvEncLockBitstream(session_handle, ¶m2));
|
||||
|
||||
SendData(
|
||||
{(uint8_t *)param2.bitstreamBufferPtr, (uint8_t *)param2.bitstreamBufferPtr + param2.bitstreamSizeInBytes}, true);
|
||||
|
||||
NVENC_CHECK(fn.nvEncUnlockBitstream(session_handle, bitstreamBuffer));
|
||||
|
||||
CU_CHECK(cuCtxPopCurrent(NULL));
|
||||
}
|
||||
|
||||
} // namespace xrt::drivers::wivrn
|
||||
@@ -0,0 +1,72 @@
|
||||
/*
|
||||
* 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 "nvEncodeAPI.h"
|
||||
#include "video_encoder.h"
|
||||
#include <cuda.h>
|
||||
|
||||
namespace xrt::drivers::wivrn
|
||||
{
|
||||
|
||||
class VideoEncoderNvenc : public VideoEncoder
|
||||
{
|
||||
vk_bundle * vk;
|
||||
// relevant part of the input image to encode
|
||||
int offset_x;
|
||||
int offset_y;
|
||||
int width;
|
||||
int height;
|
||||
|
||||
NV_ENCODE_API_FUNCTION_LIST fn;
|
||||
CUcontext cuda;
|
||||
void * session_handle;
|
||||
NV_ENC_OUTPUT_PTR bitstreamBuffer;
|
||||
|
||||
struct image_data
|
||||
{
|
||||
CUmipmappedArray cuda_image;
|
||||
CUarray cuda_array;
|
||||
};
|
||||
std::vector<image_data> images;
|
||||
CUdeviceptr frame;
|
||||
size_t pitch;
|
||||
NV_ENC_REGISTERED_PTR nvenc_resource;
|
||||
video_codec codec;
|
||||
float fps;
|
||||
int bitrate;
|
||||
|
||||
bool supports_frame_invalidation;
|
||||
|
||||
public:
|
||||
VideoEncoderNvenc(vk_bundle * vk, const encoder_settings & settings, float fps);
|
||||
|
||||
void SetImages(int width,
|
||||
int height,
|
||||
VkFormat format,
|
||||
int num_images,
|
||||
VkImage * images,
|
||||
VkImageView * views,
|
||||
VkDeviceMemory * memory) override;
|
||||
|
||||
void Encode(int index, bool idr, std::chrono::steady_clock::time_point pts) override;
|
||||
};
|
||||
|
||||
} // namespace xrt::drivers::wivrn
|
||||
@@ -0,0 +1,199 @@
|
||||
/*
|
||||
* 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 "video_encoder_x264.h"
|
||||
|
||||
#include <stdexcept>
|
||||
|
||||
namespace xrt::drivers::wivrn
|
||||
{
|
||||
|
||||
void VideoEncoderX264::ProcessCb(x264_t * h, x264_nal_t * nal, void * opaque)
|
||||
{
|
||||
VideoEncoderX264 * self = (VideoEncoderX264 *)opaque;
|
||||
std::vector<uint8_t> data(nal->i_payload * 3 / 2 + 5 + 64, 0);
|
||||
x264_nal_encode(h, data.data(), nal);
|
||||
data.resize(nal->i_payload);
|
||||
switch (nal->i_type)
|
||||
{
|
||||
case NAL_SPS:
|
||||
case NAL_PPS: {
|
||||
self->SendData(data, false);
|
||||
break;
|
||||
}
|
||||
case NAL_SLICE:
|
||||
case NAL_SLICE_DPA:
|
||||
case NAL_SLICE_DPB:
|
||||
case NAL_SLICE_DPC:
|
||||
case NAL_SLICE_IDR:
|
||||
self->ProcessNal({nal->i_first_mb, nal->i_last_mb, std::move(data)});
|
||||
}
|
||||
}
|
||||
|
||||
void VideoEncoderX264::ProcessNal(pending_nal && nal)
|
||||
{
|
||||
std::lock_guard lock(mutex);
|
||||
if (nal.first_mb == next_mb)
|
||||
{
|
||||
next_mb = nal.last_mb + 1;
|
||||
SendData(nal.data, next_mb == num_mb);
|
||||
}
|
||||
else
|
||||
{
|
||||
InsertInPendingNal(std::move(nal));
|
||||
}
|
||||
while ((not pending_nals.empty()) and pending_nals.front().first_mb == next_mb)
|
||||
{
|
||||
next_mb = pending_nals.front().last_mb + 1;
|
||||
SendData(pending_nals.front().data, next_mb == num_mb);
|
||||
pending_nals.pop_front();
|
||||
}
|
||||
}
|
||||
|
||||
void VideoEncoderX264::InsertInPendingNal(pending_nal && nal)
|
||||
{
|
||||
auto it = pending_nals.begin();
|
||||
auto end = pending_nals.end();
|
||||
for (; it != end; ++it)
|
||||
{
|
||||
if (it->first_mb > nal.last_mb)
|
||||
{
|
||||
pending_nals.insert(it, std::move(nal));
|
||||
return;
|
||||
}
|
||||
}
|
||||
pending_nals.push_back(std::move(nal));
|
||||
}
|
||||
|
||||
VideoEncoderX264::VideoEncoderX264(
|
||||
vk_bundle * vk,
|
||||
vk_cmd_pool & pool,
|
||||
encoder_settings & settings,
|
||||
int input_width,
|
||||
int input_height,
|
||||
float fps) :
|
||||
vk(vk)
|
||||
{
|
||||
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;
|
||||
|
||||
num_mb = ((settings.video_width + 15) / 16)
|
||||
* ((settings.video_height + 15) / 16);
|
||||
|
||||
converter = std::make_unique<YuvConverter>(
|
||||
vk,
|
||||
pool,
|
||||
VkExtent3D{uint32_t(settings.video_width), uint32_t(settings.video_height), 1},
|
||||
settings.offset_x,
|
||||
settings.offset_y,
|
||||
input_width,
|
||||
input_height);
|
||||
|
||||
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_log_level = X264_LOG_WARNING;
|
||||
param.i_fps_num = fps * 1'000'000;
|
||||
param.i_fps_den = 1'000'000;
|
||||
param.b_repeat_headers = 1;
|
||||
param.b_aud = 0;
|
||||
param.i_keyint_max = X264_KEYINT_MAX_INFINITE;
|
||||
|
||||
// colour definitions, actually ignored by decoder
|
||||
param.vui.b_fullrange = 1;
|
||||
settings.range = VK_SAMPLER_YCBCR_RANGE_ITU_FULL;
|
||||
param.vui.i_colorprim = 1; // BT.709
|
||||
param.vui.i_colmatrix = 1; // BT.709
|
||||
settings.color_model = VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_709;
|
||||
param.vui.i_transfer = 13; // sRGB
|
||||
|
||||
param.vui.i_sar_width = settings.width;
|
||||
param.vui.i_sar_height = settings.height;
|
||||
param.rc.i_rc_method = X264_RC_ABR;
|
||||
param.rc.i_bitrate = settings.bitrate / 1000; // x264 uses kbit/s
|
||||
enc = x264_encoder_open(¶m);
|
||||
if (not enc)
|
||||
{
|
||||
throw std::runtime_error("failed to create x264 encoder");
|
||||
}
|
||||
|
||||
assert(x264_encoder_maximum_delayed_frames(enc) == 0);
|
||||
|
||||
auto & pic = pic_in;
|
||||
x264_picture_init(&pic);
|
||||
pic.opaque = this;
|
||||
pic.img.i_csp = X264_CSP_NV12;
|
||||
pic.img.i_plane = 2;
|
||||
|
||||
pic.img.i_stride[0] = converter->y.stride;
|
||||
pic.img.plane[0] = (uint8_t *)converter->y.mapped_memory;
|
||||
pic.img.i_stride[1] = converter->uv.stride;
|
||||
pic.img.plane[1] = (uint8_t *)converter->uv.mapped_memory;
|
||||
}
|
||||
|
||||
void VideoEncoderX264::SetImages(int width, int height, VkFormat format, int num_images, VkImage * images, VkImageView * views, VkDeviceMemory * memory)
|
||||
{
|
||||
converter->SetImages(num_images, images, views);
|
||||
}
|
||||
|
||||
void VideoEncoderX264::PresentImage(int index, VkCommandBuffer * out_buffer)
|
||||
{
|
||||
*out_buffer = converter->command_buffers[index];
|
||||
}
|
||||
|
||||
void VideoEncoderX264::Encode(int index, bool idr, std::chrono::steady_clock::time_point pts)
|
||||
{
|
||||
int num_nal;
|
||||
x264_nal_t * nal;
|
||||
pic_in.i_type = idr ? X264_TYPE_IDR : X264_TYPE_P;
|
||||
pic_in.i_pts = pts.time_since_epoch().count();
|
||||
next_mb = 0;
|
||||
assert(pending_nals.empty());
|
||||
int size = x264_encoder_encode(enc, &nal, &num_nal, &pic_in, &pic_out);
|
||||
if (next_mb != num_mb)
|
||||
{
|
||||
U_LOG_W("unexpected macroblock count: %d", next_mb);
|
||||
}
|
||||
if (size < 0)
|
||||
{
|
||||
U_LOG_W("x264_encoder_encode failed: %d", size);
|
||||
return;
|
||||
}
|
||||
if (size == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
VideoEncoderX264::~VideoEncoderX264()
|
||||
{
|
||||
x264_encoder_close(enc);
|
||||
}
|
||||
|
||||
} // namespace xrt::drivers::wivrn
|
||||
@@ -0,0 +1,79 @@
|
||||
/*
|
||||
* 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 "video_encoder.h"
|
||||
#include "x264.h"
|
||||
#include "yuv_converter.h"
|
||||
|
||||
#include <list>
|
||||
#include <mutex>
|
||||
|
||||
namespace xrt::drivers::wivrn
|
||||
{
|
||||
|
||||
class VideoEncoderX264 : public VideoEncoder
|
||||
{
|
||||
x264_param_t param = {};
|
||||
x264_t * enc;
|
||||
|
||||
vk_bundle * vk;
|
||||
x264_picture_t pic_in;
|
||||
x264_picture_t pic_out = {};
|
||||
std::unique_ptr<YuvConverter> converter;
|
||||
|
||||
struct pending_nal
|
||||
{
|
||||
int first_mb;
|
||||
int last_mb;
|
||||
std::vector<uint8_t> data;
|
||||
};
|
||||
|
||||
std::mutex mutex;
|
||||
int next_mb;
|
||||
int num_mb; // Number of macroblocks in a frame
|
||||
std::list<pending_nal> pending_nals;
|
||||
|
||||
public:
|
||||
VideoEncoderX264(vk_bundle * vk, vk_cmd_pool & pool, encoder_settings & settings, int input_width, int input_height, float fps);
|
||||
|
||||
void SetImages(int width,
|
||||
int height,
|
||||
VkFormat format,
|
||||
int num_images,
|
||||
VkImage * images,
|
||||
VkImageView * views,
|
||||
VkDeviceMemory * memory) override;
|
||||
|
||||
void PresentImage(int index, VkCommandBuffer * out_buffer) override;
|
||||
|
||||
void Encode(int index, bool idr, std::chrono::steady_clock::time_point pts) override;
|
||||
|
||||
~VideoEncoderX264();
|
||||
|
||||
private:
|
||||
static void ProcessCb(x264_t * h, x264_nal_t * nal, void * opaque);
|
||||
|
||||
void ProcessNal(pending_nal && nal);
|
||||
|
||||
void InsertInPendingNal(pending_nal && nal);
|
||||
};
|
||||
|
||||
} // namespace xrt::drivers::wivrn
|
||||
@@ -0,0 +1,412 @@
|
||||
/*
|
||||
* 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 "yuv_converter.h"
|
||||
#include <iterator>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
extern const std::map<std::string, std::vector<uint32_t>> shaders;
|
||||
|
||||
static const VkFormat y_format = VK_FORMAT_R8_UNORM;
|
||||
static const VkFormat uv_format = VK_FORMAT_R8G8_UNORM;
|
||||
|
||||
static int bytes_per_pixel(VkFormat format)
|
||||
{
|
||||
switch (format)
|
||||
{
|
||||
case VK_FORMAT_R8_SRGB:
|
||||
case VK_FORMAT_R8_UNORM:
|
||||
return 1;
|
||||
case VK_FORMAT_R8G8_UNORM:
|
||||
return 2;
|
||||
default:
|
||||
assert(false);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
static VkResult create_image(vk_bundle & vk_, VkExtent2D extent, VkFormat format, YuvConverter::image_bundle & bundle)
|
||||
{
|
||||
auto vk = &vk_;
|
||||
VkResult res = vk_create_image_simple(vk, extent, format, VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, &bundle.image_memory, &bundle.image);
|
||||
VK_CHK_AND_RET(res, "vk_create_image_simple");
|
||||
|
||||
bundle.stride = extent.width * bytes_per_pixel(format);
|
||||
|
||||
if (!vk_buffer_init(vk, extent.height * bundle.stride, VK_BUFFER_USAGE_TRANSFER_DST_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT | VK_MEMORY_PROPERTY_HOST_CACHED_BIT, &bundle.buffer, &bundle.buffer_memory))
|
||||
{
|
||||
return VK_ERROR_OUT_OF_DEVICE_MEMORY;
|
||||
}
|
||||
|
||||
res = vk->vkMapMemory(vk->device, bundle.buffer_memory, 0, VK_WHOLE_SIZE, 0, &bundle.mapped_memory);
|
||||
VK_CHK_AND_RET(res, "vkMapMemory");
|
||||
|
||||
VkImageSubresourceRange subresource_range{};
|
||||
subresource_range.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
|
||||
subresource_range.baseMipLevel = 0;
|
||||
subresource_range.levelCount = 1;
|
||||
subresource_range.baseArrayLayer = 0;
|
||||
subresource_range.layerCount = 1;
|
||||
|
||||
res = vk_create_view(vk, bundle.image, VK_IMAGE_VIEW_TYPE_2D, format, subresource_range, &bundle.view);
|
||||
VK_CHK_AND_RET(res, "vk_create_view");
|
||||
return VK_SUCCESS;
|
||||
}
|
||||
|
||||
static VkResult shader_load(struct vk_bundle * vk, const std::vector<uint32_t> & code, VkShaderModule * out_module)
|
||||
{
|
||||
VkResult ret;
|
||||
|
||||
VkShaderModuleCreateInfo info{};
|
||||
info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
|
||||
info.codeSize = code.size() * sizeof(uint32_t);
|
||||
info.pCode = code.data();
|
||||
|
||||
VkShaderModule module;
|
||||
ret = vk->vkCreateShaderModule(vk->device, //
|
||||
&info, //
|
||||
NULL, //
|
||||
&module); //
|
||||
if (ret != VK_SUCCESS)
|
||||
{
|
||||
VK_ERROR(vk, "vkCreateShaderModule failed: %s", vk_result_string(ret));
|
||||
return ret;
|
||||
}
|
||||
|
||||
*out_module = module;
|
||||
|
||||
return VK_SUCCESS;
|
||||
}
|
||||
|
||||
static void destroy_all(YuvConverter * ptr)
|
||||
{
|
||||
auto vk = &ptr->vk;
|
||||
vk->vkDestroyDescriptorPool(vk->device, ptr->descriptor_pool, nullptr);
|
||||
vk->vkDestroyDescriptorSetLayout(vk->device, ptr->descriptor_set_layout, nullptr);
|
||||
for (auto & comp: {ptr->y, ptr->uv})
|
||||
{
|
||||
vk->vkDestroyPipeline(vk->device, comp.pipeline, nullptr);
|
||||
vk->vkDestroyFramebuffer(vk->device, comp.frame_buffer, nullptr);
|
||||
vk->vkDestroyRenderPass(vk->device, comp.render_pass, nullptr);
|
||||
vk->vkDestroyShaderModule(vk->device, comp.frag, nullptr);
|
||||
|
||||
vk->vkUnmapMemory(vk->device, comp.buffer_memory);
|
||||
vk->vkDestroyBuffer(vk->device, comp.buffer, nullptr);
|
||||
vk->vkFreeMemory(vk->device, comp.buffer_memory, nullptr);
|
||||
vk->vkDestroyImageView(vk->device, comp.view, nullptr);
|
||||
vk->vkDestroyImage(vk->device, comp.image, nullptr);
|
||||
vk->vkFreeMemory(vk->device, comp.image_memory, nullptr);
|
||||
}
|
||||
vk->vkDestroyPipelineLayout(vk->device, ptr->pipeline_layout, nullptr);
|
||||
|
||||
vk->vkDestroyShaderModule(vk->device, ptr->vert, nullptr);
|
||||
}
|
||||
|
||||
#define vk_check_throw(fun, res) \
|
||||
do \
|
||||
{ \
|
||||
if (res != VK_SUCCESS) \
|
||||
{ \
|
||||
vk_print_result(&this->vk, __FILE__, __LINE__, __func__, res, fun); \
|
||||
throw std::runtime_error(fun "failed"); \
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
YuvConverter::YuvConverter(vk_bundle * vk, vk_cmd_pool & pool, VkExtent3D extent, int offset_x, int offset_y, int input_width, int input_height) :
|
||||
vk(*vk), pool(pool)
|
||||
{
|
||||
std::unique_ptr<YuvConverter, decltype(&destroy_all)> deleter(this, destroy_all);
|
||||
|
||||
y.extent = {extent.width, extent.height};
|
||||
uv.extent = {extent.width / 2, extent.height / 2};
|
||||
|
||||
assert(y_format != VK_FORMAT_UNDEFINED);
|
||||
assert(uv_format != VK_FORMAT_UNDEFINED);
|
||||
|
||||
VkResult res = create_image(*vk, y.extent, y_format, y);
|
||||
vk_check_throw("create_image (y)", res);
|
||||
|
||||
res = create_image(*vk, uv.extent, uv_format, uv);
|
||||
vk_check_throw("create_image (uv)", res);
|
||||
|
||||
VkDescriptorSetLayoutBinding samplerLayoutBinding{};
|
||||
samplerLayoutBinding.binding = 0;
|
||||
samplerLayoutBinding.descriptorCount = 1;
|
||||
samplerLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
|
||||
samplerLayoutBinding.pImmutableSamplers = nullptr;
|
||||
samplerLayoutBinding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
|
||||
|
||||
VkDescriptorSetLayoutCreateInfo layoutInfo{};
|
||||
layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
|
||||
layoutInfo.bindingCount = 1;
|
||||
layoutInfo.pBindings = &samplerLayoutBinding;
|
||||
|
||||
res = vk->vkCreateDescriptorSetLayout(vk->device, &layoutInfo, nullptr, &descriptor_set_layout);
|
||||
vk_check_throw("vkCreateDescriptorSetLayout", res);
|
||||
|
||||
VkPipelineLayoutCreateInfo pipelineLayoutInfo{};
|
||||
pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
|
||||
pipelineLayoutInfo.pSetLayouts = &descriptor_set_layout;
|
||||
pipelineLayoutInfo.setLayoutCount = 1;
|
||||
res = vk->vkCreatePipelineLayout(vk->device, &pipelineLayoutInfo, nullptr, &pipeline_layout);
|
||||
vk_check_throw("vkCreatePipelineLayout", res);
|
||||
|
||||
res = shader_load(vk, shaders.at("yuv_converter.vert"), &vert);
|
||||
vk_check_throw("shader_load", res);
|
||||
|
||||
res = shader_load(vk, shaders.at("yuv_converter.y.frag"), &y.frag);
|
||||
vk_check_throw("shader_load", res);
|
||||
res =
|
||||
shader_load(vk, shaders.at("yuv_converter.uv.frag"), &uv.frag);
|
||||
vk_check_throw("shader_load", res);
|
||||
|
||||
for (int i = 0; i < 2; ++i)
|
||||
{
|
||||
VkAttachmentDescription colorAttachment{};
|
||||
VkAttachmentReference colorAttachmentRef{};
|
||||
auto & comp = (i == 0) ? y : uv;
|
||||
double scale = (i == 0) ? 1.0 : 0.5;
|
||||
colorAttachment.samples = VK_SAMPLE_COUNT_1_BIT;
|
||||
colorAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
|
||||
colorAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
|
||||
colorAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
|
||||
colorAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
|
||||
colorAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
|
||||
colorAttachment.finalLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
|
||||
|
||||
colorAttachmentRef.attachment = 0;
|
||||
colorAttachmentRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
|
||||
|
||||
colorAttachment.format = (i == 0) ? y_format : uv_format;
|
||||
|
||||
VkSubpassDescription subpass{};
|
||||
subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
|
||||
subpass.colorAttachmentCount = 1;
|
||||
subpass.pColorAttachments = &colorAttachmentRef;
|
||||
|
||||
VkRenderPassCreateInfo renderPassInfo{};
|
||||
renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
|
||||
renderPassInfo.attachmentCount = 1;
|
||||
renderPassInfo.pAttachments = &colorAttachment;
|
||||
renderPassInfo.subpassCount = 1;
|
||||
renderPassInfo.pSubpasses = &subpass;
|
||||
|
||||
res = vk->vkCreateRenderPass(vk->device, &renderPassInfo, nullptr, &comp.render_pass);
|
||||
vk_check_throw("vkCreateRenderPass", res);
|
||||
|
||||
VkFramebufferCreateInfo framebufferInfo{};
|
||||
framebufferInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
|
||||
framebufferInfo.renderPass = comp.render_pass;
|
||||
framebufferInfo.attachmentCount = 1;
|
||||
framebufferInfo.pAttachments = &comp.view;
|
||||
framebufferInfo.width = comp.extent.width;
|
||||
framebufferInfo.height = comp.extent.height;
|
||||
framebufferInfo.layers = 1;
|
||||
|
||||
res = vk->vkCreateFramebuffer(vk->device, &framebufferInfo, nullptr, &comp.frame_buffer);
|
||||
vk_check_throw("vkCreateFramebuffer", res);
|
||||
|
||||
VkPipelineShaderStageCreateInfo shaderStages[2] = {};
|
||||
|
||||
shaderStages[0].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
|
||||
shaderStages[0].stage = VK_SHADER_STAGE_VERTEX_BIT;
|
||||
shaderStages[0].module = vert;
|
||||
shaderStages[0].pName = "main";
|
||||
|
||||
shaderStages[1].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
|
||||
shaderStages[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT;
|
||||
shaderStages[1].module = comp.frag;
|
||||
shaderStages[1].pName = "main";
|
||||
|
||||
VkPipelineVertexInputStateCreateInfo vertexInputInfo{};
|
||||
vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
|
||||
vertexInputInfo.vertexBindingDescriptionCount = 0;
|
||||
vertexInputInfo.vertexAttributeDescriptionCount = 0;
|
||||
|
||||
VkPipelineInputAssemblyStateCreateInfo inputAssembly{};
|
||||
inputAssembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
|
||||
inputAssembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
|
||||
inputAssembly.primitiveRestartEnable = VK_FALSE;
|
||||
|
||||
VkViewport viewport{};
|
||||
viewport.x = -offset_x * scale;
|
||||
viewport.y = -offset_y * scale;
|
||||
viewport.width = input_width * scale;
|
||||
viewport.height = input_height * scale;
|
||||
viewport.minDepth = 0.0f;
|
||||
viewport.maxDepth = 1.0f;
|
||||
|
||||
VkRect2D scissor{};
|
||||
scissor.offset = {0, 0};
|
||||
scissor.extent = comp.extent;
|
||||
|
||||
VkPipelineViewportStateCreateInfo viewportState{};
|
||||
viewportState.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
|
||||
viewportState.viewportCount = 1;
|
||||
viewportState.pViewports = &viewport;
|
||||
viewportState.scissorCount = 1;
|
||||
viewportState.pScissors = &scissor;
|
||||
|
||||
VkPipelineRasterizationStateCreateInfo rasterizer{};
|
||||
rasterizer.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
|
||||
rasterizer.depthClampEnable = VK_FALSE;
|
||||
rasterizer.polygonMode = VK_POLYGON_MODE_FILL;
|
||||
rasterizer.lineWidth = 1.0f;
|
||||
|
||||
VkPipelineMultisampleStateCreateInfo multisampling{};
|
||||
multisampling.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
|
||||
multisampling.sampleShadingEnable = VK_FALSE;
|
||||
multisampling.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
|
||||
|
||||
VkPipelineColorBlendAttachmentState colorBlendAttachment{};
|
||||
colorBlendAttachment.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT;
|
||||
colorBlendAttachment.blendEnable = VK_FALSE;
|
||||
|
||||
VkPipelineColorBlendStateCreateInfo colorBlending{};
|
||||
colorBlending.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
|
||||
colorBlending.logicOpEnable = VK_FALSE;
|
||||
colorBlending.attachmentCount = 1;
|
||||
colorBlending.pAttachments = &colorBlendAttachment;
|
||||
|
||||
VkGraphicsPipelineCreateInfo pipelineInfo{};
|
||||
pipelineInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
|
||||
pipelineInfo.stageCount = std::size(shaderStages);
|
||||
pipelineInfo.pStages = shaderStages;
|
||||
pipelineInfo.pVertexInputState = &vertexInputInfo;
|
||||
pipelineInfo.pInputAssemblyState = &inputAssembly;
|
||||
pipelineInfo.pViewportState = &viewportState;
|
||||
pipelineInfo.pRasterizationState = &rasterizer;
|
||||
pipelineInfo.pMultisampleState = &multisampling;
|
||||
pipelineInfo.pColorBlendState = &colorBlending;
|
||||
pipelineInfo.layout = pipeline_layout;
|
||||
pipelineInfo.renderPass = comp.render_pass;
|
||||
pipelineInfo.subpass = 0;
|
||||
|
||||
res = vk->vkCreateGraphicsPipelines(vk->device, VK_NULL_HANDLE, 1, &pipelineInfo, nullptr, &comp.pipeline);
|
||||
vk_check_throw("vkCreateGraphicsPipelines", res);
|
||||
}
|
||||
|
||||
VkSamplerCreateInfo samplerInfo{};
|
||||
samplerInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
|
||||
samplerInfo.magFilter = VK_FILTER_LINEAR;
|
||||
samplerInfo.minFilter = VK_FILTER_LINEAR;
|
||||
samplerInfo.anisotropyEnable = VK_FALSE;
|
||||
res = vk->vkCreateSampler(vk->device, &samplerInfo, nullptr, &sampler);
|
||||
vk_check_throw("vkCreateSampler", res);
|
||||
|
||||
(void)deleter.release();
|
||||
}
|
||||
|
||||
YuvConverter::~YuvConverter()
|
||||
{
|
||||
destroy_all(this);
|
||||
}
|
||||
|
||||
void YuvConverter::SetImages(int num_images, VkImage * images, VkImageView * views)
|
||||
{
|
||||
// os_mutex_lock(&vk.cmd_pool_mutex);
|
||||
assert(command_buffers.empty());
|
||||
assert(descriptor_sets.empty());
|
||||
descriptor_sets.resize(num_images);
|
||||
VkDescriptorPoolSize poolSize{};
|
||||
poolSize.type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
|
||||
poolSize.descriptorCount = num_images;
|
||||
|
||||
VkDescriptorPoolCreateInfo poolInfo{};
|
||||
poolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
|
||||
poolInfo.poolSizeCount = 1;
|
||||
poolInfo.pPoolSizes = &poolSize;
|
||||
poolInfo.maxSets = num_images;
|
||||
VkResult res = vk.vkCreateDescriptorPool(vk.device, &poolInfo, nullptr, &descriptor_pool);
|
||||
vk_check_throw("vkCreateDescriptorPool", res);
|
||||
for (int i = 0; i < num_images; ++i)
|
||||
{
|
||||
const auto & view = views[i];
|
||||
auto & descriptor_set = descriptor_sets[i];
|
||||
|
||||
VkDescriptorSetAllocateInfo allocInfo{};
|
||||
allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
|
||||
allocInfo.descriptorPool = descriptor_pool;
|
||||
allocInfo.descriptorSetCount = 1;
|
||||
allocInfo.pSetLayouts = &descriptor_set_layout;
|
||||
res = vk.vkAllocateDescriptorSets(vk.device, &allocInfo, &descriptor_set);
|
||||
vk_check_throw("vkAllocateDescriptorSets", res);
|
||||
|
||||
VkDescriptorImageInfo imageInfo{};
|
||||
imageInfo.imageLayout = VK_IMAGE_LAYOUT_GENERAL;
|
||||
imageInfo.imageView = view;
|
||||
imageInfo.sampler = sampler;
|
||||
|
||||
VkWriteDescriptorSet descriptorWrite{};
|
||||
descriptorWrite.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
|
||||
descriptorWrite.dstSet = descriptor_set;
|
||||
descriptorWrite.dstBinding = 0;
|
||||
descriptorWrite.dstArrayElement = 0;
|
||||
descriptorWrite.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
|
||||
descriptorWrite.descriptorCount = 1;
|
||||
descriptorWrite.pImageInfo = &imageInfo;
|
||||
|
||||
vk.vkUpdateDescriptorSets(vk.device, 1, &descriptorWrite, 0, nullptr);
|
||||
|
||||
VkCommandBuffer cmdBuffer;
|
||||
res = vk_cmd_pool_create_and_begin_cmd_buffer(&vk, &pool, VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, &cmdBuffer);
|
||||
vk_check_throw("vk_cmd_pool_create_and_begin_cmd_buffer", res);
|
||||
|
||||
for (auto & comp: {y, uv})
|
||||
{
|
||||
VkRenderPassBeginInfo render_pass_info{};
|
||||
render_pass_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
|
||||
render_pass_info.renderPass = comp.render_pass;
|
||||
render_pass_info.framebuffer = comp.frame_buffer;
|
||||
render_pass_info.renderArea.extent = comp.extent;
|
||||
|
||||
vk.vkCmdBeginRenderPass(cmdBuffer, &render_pass_info, VK_SUBPASS_CONTENTS_INLINE);
|
||||
vk.vkCmdBindPipeline(cmdBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, comp.pipeline);
|
||||
vk.vkCmdBindDescriptorSets(cmdBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layout, 0, 1, &descriptor_set, 0, nullptr);
|
||||
vk.vkCmdDraw(cmdBuffer, 3, 1, 0, 0);
|
||||
vk.vkCmdEndRenderPass(cmdBuffer);
|
||||
|
||||
if (comp.buffer != VK_NULL_HANDLE)
|
||||
{
|
||||
VkBufferImageCopy copy{};
|
||||
copy.bufferOffset = 0;
|
||||
copy.bufferRowLength = 0;
|
||||
copy.bufferImageHeight = 0;
|
||||
copy.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
|
||||
copy.imageSubresource.mipLevel = 0;
|
||||
copy.imageSubresource.baseArrayLayer = 0;
|
||||
copy.imageSubresource.layerCount = 1;
|
||||
copy.imageOffset = {0, 0, 0};
|
||||
copy.imageExtent = {comp.extent.width, comp.extent.height, 1};
|
||||
// TODO synchronisation?
|
||||
vk.vkCmdCopyImageToBuffer(cmdBuffer, comp.image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, comp.buffer, 1, ©);
|
||||
}
|
||||
}
|
||||
|
||||
res = vk.vkEndCommandBuffer(cmdBuffer);
|
||||
vk_check_throw("vkEndCommandBuffer", res);
|
||||
|
||||
command_buffers.push_back(cmdBuffer);
|
||||
}
|
||||
// os_mutex_unlock(&vk.cmd_pool_mutex);
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
/*
|
||||
* 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/vk_cmd_pool.h"
|
||||
#include "vk/vk_helpers.h"
|
||||
#include <vector>
|
||||
#include <vulkan/vulkan_core.h>
|
||||
|
||||
class YuvConverter
|
||||
{
|
||||
public:
|
||||
struct image_bundle
|
||||
{
|
||||
VkDeviceMemory image_memory = VK_NULL_HANDLE;
|
||||
VkImage image = VK_NULL_HANDLE;
|
||||
VkImageView view = VK_NULL_HANDLE;
|
||||
VkDeviceMemory buffer_memory = VK_NULL_HANDLE;
|
||||
VkBuffer buffer = VK_NULL_HANDLE;
|
||||
void * mapped_memory = nullptr;
|
||||
VkRenderPass render_pass = VK_NULL_HANDLE;
|
||||
VkFramebuffer frame_buffer = VK_NULL_HANDLE;
|
||||
VkShaderModule frag = VK_NULL_HANDLE;
|
||||
VkPipeline pipeline = VK_NULL_HANDLE;
|
||||
VkExtent2D extent;
|
||||
int stride;
|
||||
};
|
||||
vk_bundle & vk;
|
||||
vk_cmd_pool & pool;
|
||||
image_bundle y;
|
||||
image_bundle uv;
|
||||
VkSampler sampler = VK_NULL_HANDLE;
|
||||
VkDescriptorSetLayout descriptor_set_layout = VK_NULL_HANDLE;
|
||||
VkDescriptorPool descriptor_pool = VK_NULL_HANDLE;
|
||||
|
||||
VkShaderModule vert = VK_NULL_HANDLE;
|
||||
|
||||
VkPipelineLayout pipeline_layout = VK_NULL_HANDLE;
|
||||
|
||||
std::vector<VkCommandBuffer> command_buffers;
|
||||
std::vector<VkDescriptorSet> descriptor_sets;
|
||||
|
||||
YuvConverter(vk_bundle * vk, vk_cmd_pool & pool, VkExtent3D extent, int offset_x, int offset_y, int input_width, int input_height);
|
||||
~YuvConverter();
|
||||
|
||||
void SetImages(int num_images, VkImage * images, VkImageView * views);
|
||||
};
|
||||
Reference in New Issue
Block a user