Always do yuv conversion in vulkan

This commit is contained in:
Patrick Nicolas
2024-02-18 16:15:55 +01:00
parent 4d99392ced
commit e385e459ee
28 changed files with 1663 additions and 1502 deletions
-359
View File
@@ -1,359 +0,0 @@
/*
* 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");
}
}
-68
View File
@@ -1,68 +0,0 @@
/*
* 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;
};
-3
View File
@@ -63,9 +63,6 @@ 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 *);
@@ -17,11 +17,9 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "VideoEncoderFFMPEG.h"
#include <algorithm>
#include <array>
#include "video_encoder_ffmpeg.h"
#include "util/u_logging.h"
#include <stdexcept>
#include <string.h>
extern "C"
{
@@ -32,54 +30,6 @@ extern "C"
namespace
{
bool should_keep_nal_h264(const uint8_t * header_start)
{
uint8_t nal_type = (header_start[2] == 0 ? header_start[4] : header_start[3]) & 0x1F;
switch (nal_type)
{
case 6: // supplemental enhancement information
case 9: // access unit delimiter
return false;
default:
return true;
}
}
bool should_keep_nal_h265(const uint8_t * header_start)
{
uint8_t nal_type = ((header_start[2] == 0 ? header_start[4] : header_start[3]) >> 1) & 0x3F;
switch (nal_type)
{
case 35: // access unit delimiter
case 39: // supplemental enhancement information
return false;
default:
return true;
}
}
void filter_NAL(const uint8_t * input, size_t input_size, std::vector<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");
@@ -113,9 +63,9 @@ bool set_log_level()
bool VideoEncoderFFMPEG::once = set_log_level();
void VideoEncoderFFMPEG::Encode(int index, bool idr, std::chrono::steady_clock::time_point target_timestamp)
void VideoEncoderFFMPEG::Encode(bool idr, std::chrono::steady_clock::time_point target_timestamp)
{
PushFrame(index, idr, target_timestamp);
PushFrame(idr, target_timestamp);
av_packet_ptr enc_pkt(av_packet_alloc());
int err = avcodec_receive_packet(encoder_ctx.get(), enc_pkt.get());
if (err == 0)
@@ -19,10 +19,9 @@
#pragma once
#include "../video_encoder.h"
#include "encoder/video_encoder.h"
#include "ffmpeg_helper.h"
#include <chrono>
#include <cstdint>
class VideoEncoderFFMPEG : public xrt::drivers::wivrn::VideoEncoder
{
@@ -30,14 +29,13 @@ public:
using Codec = xrt::drivers::wivrn::video_codec;
void
Encode(int index, bool idr, std::chrono::steady_clock::time_point target_timestamp) override;
Encode(bool idr, std::chrono::steady_clock::time_point target_timestamp) override;
protected:
virtual void
PushFrame(uint32_t frame_index, bool idr, std::chrono::steady_clock::time_point pts) = 0;
PushFrame(bool idr, std::chrono::steady_clock::time_point pts) = 0;
av_codec_context_ptr encoder_ctx;
Codec codec;
private:
static bool once;
+416
View File
@@ -0,0 +1,416 @@
/*
* WiVRn VR streaming
* Copyright (C) 2022-2024 Guillaume Meunier <guillaume.meunier@centraliens.net>
* Copyright (C) 2022-2024 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/>.
*/
// must be included before vulkan_raii
#include "video_encoder_va.h"
#include "encoder/yuv_converter.h"
#include "util/u_logging.h"
#include "utils/wivrn_vk_bundle.h"
#include <drm_fourcc.h>
#include <filesystem>
#include <optional>
#include <unordered_map>
#include <vulkan/vulkan_raii.hpp>
extern "C"
{
#include <libavcodec/avcodec.h>
#include <libavutil/hwcontext.h>
#include <libavutil/hwcontext_drm.h>
#include <libavutil/pixdesc.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)));
}
av_buffer_ptr make_hwframe_ctx(AVBufferRef * hw_device_ctx, AVPixelFormat hw_format, AVPixelFormat sw_format, int width, int height)
{
av_buffer_ptr hw_frames_ref(av_hwframe_ctx_alloc(hw_device_ctx));
if (not hw_frames_ref)
{
throw std::runtime_error("Failed to create VAAPI frame context.");
}
auto frames_ctx = (AVHWFramesContext *)(hw_frames_ref->data);
frames_ctx->format = hw_format;
frames_ctx->sw_format = sw_format;
frames_ctx->width = width;
frames_ctx->height = height;
frames_ctx->initial_pool_size = 10;
if (int err = av_hwframe_ctx_init(hw_frames_ref.get()); err < 0)
{
throw std::system_error(err, av_error_category(), "Failed to initialize frame context");
}
return std::move(hw_frames_ref);
}
std::optional<std::filesystem::path>
get_render_device(vk::raii::PhysicalDevice & physical_device)
{
auto [props, drm_props] = physical_device.getProperties2<vk::PhysicalDeviceProperties2, vk::PhysicalDeviceDrmPropertiesEXT>();
if (!drm_props.hasRender)
{
U_LOG_E("Failed to find render DRM device");
throw std::runtime_error("Failed to find render DRM device");
}
std::filesystem::path path = "/dev/dri/renderD" + std::to_string(drm_props.renderMinor);
if (not std::filesystem::exists(path))
{
U_LOG_W("DRI device %s does not exist, reverting to default", path.c_str());
return std::nullopt;
}
return path;
}
av_buffer_ptr make_drm_hw_ctx(vk::raii::PhysicalDevice & physical_device)
{
const auto device = get_render_device(physical_device);
AVBufferRef * hw_ctx;
int err = av_hwdevice_ctx_create(&hw_ctx, AV_HWDEVICE_TYPE_DRM, device ? device->c_str() : NULL, NULL, 0);
if (err)
throw std::system_error(err, av_error_category(), "FFMPEG drm hardware context creation failed");
return av_buffer_ptr(hw_ctx);
}
std::unordered_map<uint32_t, vk::Format> vulkan_drm_format_map = {
{DRM_FORMAT_R8, vk::Format::eR8Unorm},
{DRM_FORMAT_R16, vk::Format::eR16Unorm},
{DRM_FORMAT_GR88, vk::Format::eR8G8Unorm},
{DRM_FORMAT_RG88, vk::Format::eR8G8Unorm},
{DRM_FORMAT_GR1616, vk::Format::eR16G16Unorm},
{DRM_FORMAT_RG1616, vk::Format::eR16G16Unorm},
{DRM_FORMAT_ARGB8888, vk::Format::eB8G8R8A8Unorm},
{DRM_FORMAT_XRGB8888, vk::Format::eB8G8R8A8Unorm},
{DRM_FORMAT_ABGR8888, vk::Format::eR8G8B8A8Unorm},
{DRM_FORMAT_XBGR8888, vk::Format::eR8G8B8A8Unorm},
};
vk::Format drm_to_vulkan_fmt(uint32_t drm_fourcc)
{
return vulkan_drm_format_map.at(drm_fourcc);
}
} // namespace
video_encoder_va::video_encoder_va(wivrn_vk_bundle & vk, xrt::drivers::wivrn::encoder_settings & settings, float fps) :
luma(nullptr), chroma(nullptr)
{
auto drm_hw_ctx = make_drm_hw_ctx(vk.physical_device);
AVBufferRef * tmp;
int err = av_hwdevice_ctx_create_derived(&tmp,
AV_HWDEVICE_TYPE_VAAPI,
drm_hw_ctx.get(),
0);
if (err)
throw std::system_error(err, av_error_category(), "FFMPEG vaapi hardware context creation failed");
av_buffer_ptr vaapi_hw_ctx(tmp);
settings.video_width += settings.video_width % 2;
settings.video_height += settings.video_height % 2;
auto vaapi_frame_ctx = make_hwframe_ctx(vaapi_hw_ctx.get(), AV_PIX_FMT_VAAPI, AV_PIX_FMT_NV12, settings.video_width, settings.video_height);
assert(av_pix_fmt_count_planes(AV_PIX_FMT_NV12) == 2);
rect = vk::Rect2D{
.offset = {
.x = settings.offset_x,
.y = settings.offset_y,
},
.extent = {
.width = settings.width,
.height = settings.height,
}};
err = av_hwframe_ctx_create_derived(&tmp,
AV_PIX_FMT_DRM_PRIME,
drm_hw_ctx.get(),
vaapi_frame_ctx.get(),
AV_HWFRAME_MAP_DIRECT);
if (err < 0)
{
throw std::system_error(err, av_error_category(), "Cannot create drm frame context");
}
drm_frame_ctx = av_buffer_ptr(tmp);
const char * encoder_name = encoder(settings.codec);
const AVCodec * codec = avcodec_find_encoder_by_name(encoder_name);
if (codec == nullptr)
{
throw std::runtime_error(std::string("Failed to find encoder ") + encoder_name);
}
encoder_ctx = av_codec_context_ptr(avcodec_alloc_context3(codec));
if (not encoder_ctx)
{
throw std::runtime_error("failed to allocate VAAPI encoder");
}
AVDictionary * opts = nullptr;
av_dict_set(&opts, "async_depth", "1", 0);
for (auto option: settings.options)
{
av_dict_set(&opts, option.first.c_str(), option.second.c_str(), 0);
}
switch (settings.codec)
{
case Codec::h264:
encoder_ctx->profile = FF_PROFILE_H264_MAIN;
break;
case Codec::h265:
encoder_ctx->profile = FF_PROFILE_HEVC_MAIN;
break;
}
encoder_ctx->width = settings.video_width;
encoder_ctx->height = settings.video_height;
encoder_ctx->time_base = {std::chrono::steady_clock::duration::period::num,
std::chrono::steady_clock::duration::period::den};
encoder_ctx->framerate = AVRational{(int)fps, 1};
encoder_ctx->sample_aspect_ratio = AVRational{1, 1};
encoder_ctx->pix_fmt = AV_PIX_FMT_VAAPI;
encoder_ctx->color_range = AVCOL_RANGE_JPEG;
encoder_ctx->colorspace = AVCOL_SPC_BT709;
encoder_ctx->color_trc = AVCOL_TRC_BT709;
encoder_ctx->color_primaries = AVCOL_PRI_BT709;
settings.range = VK_SAMPLER_YCBCR_RANGE_ITU_FULL;
settings.color_model = VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_709;
encoder_ctx->max_b_frames = 0;
encoder_ctx->bit_rate = settings.bitrate;
encoder_ctx->gop_size = std::numeric_limits<decltype(encoder_ctx->gop_size)>::max();
encoder_ctx->hw_frames_ctx = av_buffer_ref(vaapi_frame_ctx.get());
err = avcodec_open2(encoder_ctx.get(), codec, &opts);
av_dict_free(&opts);
if (err < 0)
{
throw std::system_error(err, av_error_category(), "Cannot open video encoder codec");
}
if (encoder_ctx->delay != 0)
{
U_LOG_W("Encoder %d reports a %d frame delay, reprojection will fail", stream_idx, encoder_ctx->delay);
}
va_frame = make_av_frame();
err = av_hwframe_get_buffer(vaapi_frame_ctx.get(), va_frame.get(), 0);
if (err < 0)
{
throw std::system_error(err, av_error_category(), "Cannot create vaapi frame");
}
drm_frame = make_av_frame();
err = av_hwframe_get_buffer(drm_frame_ctx.get(), drm_frame.get(), 0);
if (err < 0)
{
throw std::system_error(err, av_error_category(), "Cannot create vulkan frame");
}
av_hwframe_map(va_frame.get(), drm_frame.get(), AV_HWFRAME_MAP_DIRECT);
va_frame->color_range = AVCOL_RANGE_JPEG;
va_frame->colorspace = AVCOL_SPC_BT709;
va_frame->color_primaries = AVCOL_PRI_BT709;
va_frame->color_trc = AVCOL_TRC_BT709;
auto desc = (AVDRMFrameDescriptor *)drm_frame->data[0];
const bool has_modifiers =
std::ranges::any_of(vk.device_extensions, [](const char * ext) {
return strcmp(ext, VK_EXT_IMAGE_DRM_FORMAT_MODIFIER_EXTENSION_NAME) == 0;
});
assert(desc->nb_layers == desc->nb_objects);
for (int i = 0; i < desc->nb_layers; ++i)
{
std::vector<vk::SubresourceLayout> plane_layouts;
for (int plane = 0; plane < desc->layers[i].nb_planes; ++plane)
{
plane_layouts.push_back({
.offset = vk::DeviceSize(desc->layers[i].planes[plane].offset),
.rowPitch = vk::DeviceSize(desc->layers[i].planes[plane].pitch),
});
}
vk::ImageDrmFormatModifierExplicitCreateInfoEXT drm_info{
.drmFormatModifier = desc->objects[0].format_modifier,
.drmFormatModifierPlaneCount = uint32_t(plane_layouts.size()),
.pPlaneLayouts = plane_layouts.data(),
};
vk::StructureChain image_create_info{
vk::ImageCreateInfo{
.imageType = vk::ImageType::e2D,
.format = drm_to_vulkan_fmt(desc->layers[i].format),
.extent = {
.width = uint32_t(drm_frame->width / (i == 0 ? 1 : 2)),
.height = uint32_t(drm_frame->height / (i == 0 ? 1 : 2)),
.depth = 1,
},
.mipLevels = 1,
.arrayLayers = 1,
.samples = vk::SampleCountFlagBits::e1,
.tiling = has_modifiers ? vk::ImageTiling::eDrmFormatModifierEXT : (desc->objects[0].format_modifier == DRM_FORMAT_MOD_LINEAR ? vk::ImageTiling::eLinear : vk::ImageTiling::eOptimal),
.usage = vk::ImageUsageFlagBits::eTransferDst,
.sharingMode = vk::SharingMode::eExclusive,
.initialLayout = vk::ImageLayout::eUndefined,
},
vk::ExternalMemoryImageCreateInfo{
.pNext = has_modifiers ? &drm_info : nullptr,
.handleTypes = vk::ExternalMemoryHandleTypeFlagBits::eDmaBufEXT,
},
};
auto & image = (i == 0 ? luma : chroma);
image = vk.device.createImage(image_create_info.get());
auto memory_props = vk.device.getMemoryFdPropertiesKHR(vk::ExternalMemoryHandleTypeFlagBits::eDmaBufEXT, desc->objects[i].fd);
vk::StructureChain alloc_info{
vk::MemoryAllocateInfo{
.allocationSize = desc->objects[i].size,
.memoryTypeIndex = vk.get_memory_type(memory_props.memoryTypeBits, vk::MemoryPropertyFlagBits::eDeviceLocal),
},
vk::MemoryDedicatedAllocateInfo{
.image = *image,
},
vk::ImportMemoryFdInfoKHR{
.handleType = vk::ExternalMemoryHandleTypeFlagBits::eDmaBufEXT,
.fd = dup(desc->objects[i].fd),
},
};
try
{
mem.push_back(vk.device.allocateMemory(alloc_info.get()));
}
catch (...)
{
close(alloc_info.get<vk::ImportMemoryFdInfoKHR>().fd);
throw;
}
image.bindMemory(*mem.back(), 0);
}
}
void video_encoder_va::PresentImage(yuv_converter & src_yuv, vk::raii::CommandBuffer & cmd_buf)
{
std::array im_barriers = {
vk::ImageMemoryBarrier{
.srcAccessMask = vk::AccessFlagBits::eNone,
.dstAccessMask = vk::AccessFlagBits::eMemoryWrite,
.oldLayout = vk::ImageLayout::eUndefined,
.newLayout = vk::ImageLayout::eTransferDstOptimal,
.image = *luma,
.subresourceRange = {.aspectMask = vk::ImageAspectFlagBits::eColor,
.baseMipLevel = 0,
.levelCount = 1,
.baseArrayLayer = 0,
.layerCount = 1},
},
vk::ImageMemoryBarrier{
.srcAccessMask = vk::AccessFlagBits::eNone,
.dstAccessMask = vk::AccessFlagBits::eMemoryWrite,
.oldLayout = vk::ImageLayout::eUndefined,
.newLayout = vk::ImageLayout::eTransferDstOptimal,
.image = *chroma,
.subresourceRange = {.aspectMask = vk::ImageAspectFlagBits::eColor,
.baseMipLevel = 0,
.levelCount = 1,
.baseArrayLayer = 0,
.layerCount = 1},
},
};
cmd_buf.pipelineBarrier(
vk::PipelineStageFlagBits::eAllCommands,
vk::PipelineStageFlagBits::eTransfer,
{},
nullptr,
nullptr,
im_barriers);
cmd_buf.copyImage(
src_yuv.luma,
vk::ImageLayout::eTransferSrcOptimal,
*luma,
vk::ImageLayout::eTransferDstOptimal,
vk::ImageCopy{
.srcSubresource = {
.aspectMask = vk::ImageAspectFlagBits::eColor,
.layerCount = 1,
},
.srcOffset = {
.x = rect.offset.x,
.y = rect.offset.y,
},
.dstSubresource = {
.aspectMask = vk::ImageAspectFlagBits::eColor,
.layerCount = 1,
},
.extent = {
.width = rect.extent.width,
.height = rect.extent.height,
.depth = 1,
}});
cmd_buf.copyImage(
src_yuv.chroma,
vk::ImageLayout::eTransferSrcOptimal,
*chroma,
vk::ImageLayout::eTransferDstOptimal,
vk::ImageCopy{
.srcSubresource = {
.aspectMask = vk::ImageAspectFlagBits::eColor,
.layerCount = 1,
},
.srcOffset = {
.x = rect.offset.x / 2,
.y = rect.offset.y / 2,
},
.dstSubresource = {
.aspectMask = vk::ImageAspectFlagBits::eColor,
.layerCount = 1,
},
.extent = {
.width = rect.extent.width / 2,
.height = rect.extent.height / 2,
.depth = 1,
}});
}
void video_encoder_va::PushFrame(bool idr, std::chrono::steady_clock::time_point pts)
{
va_frame->pict_type = idr ? AV_PICTURE_TYPE_I : AV_PICTURE_TYPE_P;
va_frame->pts = pts.time_since_epoch().count();
int err = avcodec_send_frame(encoder_ctx.get(), va_frame.get());
if (err)
{
throw std::system_error(err, av_error_category(), "avcodec_send_frame failed");
}
}
+49
View File
@@ -0,0 +1,49 @@
/*
* WiVRn VR streaming
* Copyright (C) 2022-2024 Guillaume Meunier <guillaume.meunier@centraliens.net>
* Copyright (C) 2022-2024 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_ffmpeg.h"
#include "ffmpeg_helper.h"
#include "utils/wivrn_vk_bundle.h"
#include <vulkan/vulkan_raii.hpp>
namespace xrt::drivers::wivrn
{
struct encoder_settings;
}
class video_encoder_va : public VideoEncoderFFMPEG
{
av_buffer_ptr drm_frame_ctx;
av_frame_ptr va_frame;
av_frame_ptr drm_frame;
vk::Rect2D rect;
vk::raii::Image luma;
vk::raii::Image chroma;
std::vector<vk::raii::DeviceMemory> mem;
public:
video_encoder_va(wivrn_vk_bundle&, xrt::drivers::wivrn::encoder_settings & settings, float fps);
void PresentImage(yuv_converter & src_yuv, vk::raii::CommandBuffer & cmd_buf) override;
protected:
void PushFrame(bool idr, std::chrono::steady_clock::time_point pts) override;
};