13#include <libavcodec/avcodec.h>
14#include <libavutil/pixdesc.h>
17#if !VA_CHECK_VERSION(1, 9, 0)
25 return VA_STATUS_ERROR_UNIMPLEMENTED;
39using namespace std::literals;
41extern "C" struct AVBufferRef;
44 constexpr auto SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME_2 = 0x40000000;
45 constexpr auto EXPORT_SURFACE_WRITE_ONLY = 0x0002;
46 constexpr auto EXPORT_SURFACE_SEPARATE_LAYERS = 0x0004;
48 using VADisplay =
void *;
50 using VAGenericID =
unsigned int;
51 using VASurfaceID = VAGenericID;
71 uint64_t drm_format_modifier;
85 uint32_t object_index[4];
95 using display_t = util::safe_ptr_v2<void, VAStatus, vaTerminate>;
101 int init(
int in_width,
int in_height, file_t &&render_device) {
102 file = std::move(render_device);
104 if (!gbm::create_device) {
105 BOOST_LOG(warning) <<
"libgbm not initialized"sv;
109 this->data = (
void *) vaapi_init_avcodec_hardware_input_buffer;
111 gbm.reset(gbm::create_device(file.el));
114 BOOST_LOG(error) <<
"Couldn't create GBM device: ["sv << strerror_r(errno,
string,
sizeof(
string)) <<
']';
118 display = egl::make_display(gbm.get());
123 auto ctx_opt = egl::make_ctx(display.get());
128 ctx = std::move(*ctx_opt);
142 std::vector<VAEntrypoint> entrypoints(vaMaxNumEntrypoints(va_display));
144 auto status = vaQueryConfigEntrypoints(va_display, profile, entrypoints.data(), &num_eps);
145 if (status != VA_STATUS_SUCCESS) {
146 BOOST_LOG(error) <<
"Failed to query VA entrypoints: "sv << vaErrorStr(status);
147 return (VAEntrypoint) 0;
149 entrypoints.resize(num_eps);
152 VAEntrypoint ep_preferences[] = {
153 VAEntrypointEncSliceLP,
154 VAEntrypointEncSlice,
155 VAEntrypointEncPicture
157 for (
auto ep_pref : ep_preferences) {
158 if (std::find(entrypoints.begin(), entrypoints.end(), ep_pref) != entrypoints.end()) {
163 return (VAEntrypoint) 0;
172 std::vector<VAProfile> profiles(vaMaxNumProfiles(va_display));
174 auto status = vaQueryConfigProfiles(va_display, profiles.data(), &num_profs);
175 if (status != VA_STATUS_SUCCESS) {
176 BOOST_LOG(error) <<
"Failed to query VA profiles: "sv << vaErrorStr(status);
179 profiles.resize(num_profs);
181 return std::find(profiles.begin(), profiles.end(), profile) != profiles.end();
190 if (ctx->codec_id == AV_CODEC_ID_H264) {
192 return VAProfileH264High;
193 }
else if (ctx->codec_id == AV_CODEC_ID_HEVC) {
194 switch (ctx->profile) {
195 case AV_PROFILE_HEVC_REXT:
196 switch (av_pix_fmt_desc_get(ctx->sw_pix_fmt)->comp[0].depth) {
198 return VAProfileHEVCMain444_10;
200 return VAProfileHEVCMain444;
203 case AV_PROFILE_HEVC_MAIN_10:
204 return VAProfileHEVCMain10;
205 case AV_PROFILE_HEVC_MAIN:
206 return VAProfileHEVCMain;
208 }
else if (ctx->codec_id == AV_CODEC_ID_AV1) {
209 switch (ctx->profile) {
210 case AV_PROFILE_AV1_HIGH:
211 return VAProfileAV1Profile1;
212 case AV_PROFILE_AV1_MAIN:
213 return VAProfileAV1Profile0;
217 BOOST_LOG(error) <<
"Unknown encoder profile: "sv << ctx->profile;
218 return VAProfileNone;
229 if (va_entrypoint == 0) {
234 auto vendor = vaQueryVendorString(va_display);
236 if (va_entrypoint == VAEntrypointEncSliceLP) {
237 BOOST_LOG(info) <<
"Using LP encoding mode"sv;
238 av_dict_set_int(options,
"low_power", 1, 0);
240 BOOST_LOG(info) <<
"Using normal encoding mode"sv;
243 VAConfigAttrib rc_attr = {VAConfigAttribRateControl};
244 auto status = vaGetConfigAttributes(va_display, va_profile, va_entrypoint, &rc_attr, 1);
245 if (status != VA_STATUS_SUCCESS) {
250 VAConfigAttrib slice_attr = {VAConfigAttribEncMaxSlices};
251 status = vaGetConfigAttributes(va_display, va_profile, va_entrypoint, &slice_attr, 1);
252 if (status != VA_STATUS_SUCCESS) {
254 slice_attr.value = 1;
256 if (ctx->slices > slice_attr.value) {
257 BOOST_LOG(info) <<
"Limiting slice count to encoder maximum: "sv << slice_attr.value;
258 ctx->slices = slice_attr.value;
272 const bool amd_or_mesa_vaapi = vendor && (
273 strstr(vendor,
"AMD") ||
274 strstr(vendor,
"Mesa") ||
275 strstr(vendor,
"RADV") ||
276 strstr(vendor,
"radeonsi")
278 if (config::video.vaapi.strict_rc_buffer ||
279 (vendor && strstr(vendor,
"Intel")) ||
281 ctx->codec_id == AV_CODEC_ID_AV1) {
282 ctx->rc_buffer_size = ctx->bit_rate * ctx->framerate.den / ctx->framerate.num;
289 const bool radeonsi = vendor && strstr(vendor,
"radeonsi");
291 if (radeonsi && (rc_attr.value & VA_RC_CBR)) {
292 BOOST_LOG(info) <<
"Using CBR with single frame VBV size (radeonsi ignores the VBV in VBR)"sv;
293 av_dict_set(options,
"rc_mode",
"CBR", 0);
294 }
else if (rc_attr.value & VA_RC_VBR) {
295 BOOST_LOG(info) <<
"Using VBR with single frame VBV size"sv;
296 av_dict_set(options,
"rc_mode",
"VBR", 0);
297 }
else if (rc_attr.value & VA_RC_CBR) {
298 BOOST_LOG(info) <<
"Using CBR with single frame VBV size"sv;
299 av_dict_set(options,
"rc_mode",
"CBR", 0);
301 BOOST_LOG(warning) <<
"Using CQP with single frame VBV size"sv;
302 av_dict_set_int(options,
"qp", config::video.qp, 0);
304 }
else if (!(rc_attr.value & (VA_RC_CBR | VA_RC_VBR))) {
305 BOOST_LOG(warning) <<
"Using CQP rate control"sv;
306 av_dict_set_int(options,
"qp", config::video.qp, 0);
311 if (rc_attr.value & VA_RC_CBR) {
312 BOOST_LOG(info) <<
"Using CBR rate control"sv;
313 av_dict_set(options,
"rc_mode",
"CBR", 0);
314 }
else if (rc_attr.value & VA_RC_VBR) {
315 BOOST_LOG(info) <<
"Using VBR rate control"sv;
316 av_dict_set(options,
"rc_mode",
"VBR", 0);
321 int set_frame(AVFrame *frame, AVBufferRef *hw_frames_ctx_buf)
override {
322 this->hwframe.reset(frame);
325 if (!frame->buf[0]) {
326 if (av_hwframe_get_buffer(hw_frames_ctx_buf, frame, 0)) {
327 BOOST_LOG(error) <<
"Couldn't get hwframe for VAAPI"sv;
333 va::VASurfaceID surface = (std::uintptr_t) frame->data[3];
334 auto hw_frames_ctx = (AVHWFramesContext *) hw_frames_ctx_buf->data;
336 auto status = vaExportSurfaceHandle(
339 va::SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME_2,
340 va::EXPORT_SURFACE_WRITE_ONLY | va::EXPORT_SURFACE_SEPARATE_LAYERS,
344 BOOST_LOG(error) <<
"Couldn't export va surface handle: ["sv << (int) surface <<
"]: "sv << vaErrorStr(status);
350 std::array<file_t, egl::nv12_img_t::num_fds> fds;
351 for (
int x = 0; x < prime.num_objects; ++x) {
352 fds[x] = prime.objects[x].fd;
355 if (prime.num_layers != 2) {
356 BOOST_LOG(error) <<
"Invalid layer count for VA surface: expected 2, got "sv << prime.num_layers;
361 for (
int plane = 0; plane < 2; ++plane) {
362 auto &sd = sds[plane];
363 auto &layer = prime.layers[plane];
365 sd.fourcc = layer.drm_format;
368 sd.width = prime.width / (plane == 0 ? 1 : 2);
369 sd.height = prime.height / (plane == 0 ? 1 : 2);
372 sd.modifier = prime.objects[layer.object_index[0]].drm_format_modifier;
374 std::fill_n(sd.fds, 4, -1);
375 for (
int x = 0; x < layer.num_planes; ++x) {
376 sd.fds[x] = prime.objects[layer.object_index[x]].fd;
377 sd.pitches[x] = layer.pitch[x];
378 sd.offsets[x] = layer.offset[x];
382 auto nv12_opt = egl::import_target(display.get(), std::move(fds), sds[0], sds[1]);
387 auto sws_opt = egl::sws_t::make(width, height, frame->width, frame->height, hw_frames_ctx->sw_format);
392 this->sws = std::move(*sws_opt);
393 this->nv12 = std::move(*nv12_opt);
398 void apply_colorspace()
override {
399 sws.apply_colorspace(colorspace);
402 va::display_t::pointer va_display;
406 egl::display_t display;
424 sws.convert(nv12->buf);
434 if (descriptor.sequence == 0) {
437 }
else if (descriptor.sequence > sequence) {
438 sequence = descriptor.sequence;
442 auto rgb_opt = egl::import_source(display.get(), descriptor.sd);
448 rgb = std::move(*rgb_opt);
451 sws.load_vram(descriptor, offset_x, offset_y, rgb->tex[0]);
453 sws.convert(nv12->buf);
457 int init(
int in_width,
int in_height, file_t &&render_device,
int offset_x,
int offset_y) {
458 if (va_t::init(in_width, in_height, std::move(render_device))) {
464 this->offset_x = offset_x;
465 this->offset_y = offset_y;
470 std::uint64_t sequence;
473 int offset_x, offset_y;
509 } AVVAAPIDeviceContext;
511 static void __log(
void *level,
const char *msg) {
512 BOOST_LOG(*(boost::log::sources::severity_logger<int> *) level) << msg;
515 static void vaapi_hwdevice_ctx_free(AVHWDeviceContext *ctx) {
519 vaTerminate(hwctx->display);
524 int vaapi_init_avcodec_hardware_input_buffer(platf::avcodec_encode_device_t *base, AVBufferRef **hw_device_buf) {
525 auto va = (va::va_t *) base;
526 auto fd = dup(va->file.el);
531 auto fg = util::fail_guard([fd, priv]() {
536 va::display_t
display {vaGetDisplayDRM(fd)};
538 BOOST_LOG(error) <<
"Couldn't open a va display from DRM on the encoding GPU"sv;
542 va->va_display =
display.get();
544 vaSetErrorCallback(
display.get(), __log, &error);
545 vaSetErrorCallback(
display.get(), __log, &info);
548 auto status = vaInitialize(
display.get(), &major, &minor);
550 BOOST_LOG(error) <<
"Couldn't initialize va display: "sv << vaErrorStr(status);
554 BOOST_LOG(info) <<
"vaapi vendor: "sv << vaQueryVendorString(
display.get());
557 *hw_device_buf = av_hwdevice_ctx_alloc(AV_HWDEVICE_TYPE_VAAPI);
558 auto ctx = (AVHWDeviceContext *) (*hw_device_buf)->data;
562 hwctx->display =
display.release();
563 ctx->user_opaque = priv;
564 ctx->free = vaapi_hwdevice_ctx_free;
567 auto err = av_hwdevice_ctx_init(*hw_device_buf);
569 char err_str[AV_ERROR_MAX_STRING_SIZE] {0};
570 BOOST_LOG(error) <<
"Failed to create FFMpeg hardware device context: "sv << av_make_error_string(err_str, AV_ERROR_MAX_STRING_SIZE, err);
578 static bool query(display_t::pointer display, VAProfile profile) {
579 std::vector<VAEntrypoint> entrypoints;
580 entrypoints.resize(vaMaxNumEntrypoints(display));
583 auto status = vaQueryConfigEntrypoints(display, profile, entrypoints.data(), &count);
585 BOOST_LOG(error) <<
"Couldn't query entrypoints: "sv << vaErrorStr(status);
588 entrypoints.resize(count);
590 for (
auto entrypoint : entrypoints) {
591 if (entrypoint == VAEntrypointEncSlice || entrypoint == VAEntrypointEncSliceLP) {
599 bool validate(
int fd) {
600 va::display_t
display {vaGetDisplayDRM(fd)};
604 auto bytes = readlink(std::format(
"/proc/self/fd/{}", fd).c_str(),
string,
sizeof(
string));
606 std::string_view render_device {string, (std::size_t) bytes};
608 BOOST_LOG(error) <<
"Couldn't open a va display from DRM with device: "sv << render_device;
613 auto status = vaInitialize(
display.get(), &major, &minor);
615 BOOST_LOG(error) <<
"Couldn't initialize va display: "sv << vaErrorStr(status);
619 if (!query(
display.get(), VAProfileH264Main)) {
623 if (video::active_hevc_mode > 1 && !query(
display.get(), VAProfileHEVCMain)) {
627 if (video::active_hevc_mode > 2 && !query(
display.get(), VAProfileHEVCMain10)) {
635 va::display_t display {vaGetDisplayDRM(fd)};
641 vaSetErrorCallback(display.get(),
nullptr,
nullptr);
642 vaSetInfoCallback(display.get(),
nullptr,
nullptr);
645 if (vaInitialize(display.get(), &major, &minor) != VA_STATUS_SUCCESS) {
649 const auto encodes = [&](VAProfile profile) {
650 std::vector<VAEntrypoint> entrypoints(vaMaxNumEntrypoints(display.get()));
652 if (vaQueryConfigEntrypoints(display.get(), profile, entrypoints.data(), &count) != VA_STATUS_SUCCESS) {
655 entrypoints.resize(count);
656 return std::ranges::any_of(entrypoints, [](VAEntrypoint entrypoint) {
657 return entrypoint == VAEntrypointEncSlice || entrypoint == VAEntrypointEncSliceLP;
661 if (!encodes(VAProfileH264Main) && !encodes(VAProfileH264High)) {
665 if (encodes(VAProfileHEVCMain)) {
668 if (encodes(VAProfileHEVCMain10)) {
671 if (encodes(VAProfileAV1Profile0)) {
677 std::unique_ptr<platf::avcodec_encode_device_t> make_avcodec_encode_device(
int width,
int height, file_t &&card,
int offset_x,
int offset_y,
bool vram) {
679 auto egl = std::make_unique<va::va_vram_t>();
680 if (egl->init(width, height, std::move(card), offset_x, offset_y)) {
688 auto egl = std::make_unique<va::va_ram_t>();
689 if (egl->init(width, height, std::move(card))) {
697 std::unique_ptr<platf::avcodec_encode_device_t> make_avcodec_encode_device(
int width,
int height,
int offset_x,
int offset_y,
bool vram) {
700 BOOST_LOG(error) <<
"Couldn't open a GPU to encode on"sv;
704 return make_avcodec_encode_device(width, height, std::move(file), offset_x, offset_y, vram);
707 std::unique_ptr<platf::avcodec_encode_device_t> make_avcodec_encode_device(
int width,
int height,
bool vram) {
708 return make_avcodec_encode_device(width, height, 0, 0, vram);
VAEntrypoint select_va_entrypoint(VAProfile profile)
Finds a supported VA entrypoint for the given VA profile.
bool is_va_profile_supported(VAProfile profile)
Determines if a given VA profile is supported.
void init_codec_options(AVCodecContext *ctx, AVDictionary **options) override
Provides a hook for allow platform-specific code to adjust codec options.
VAProfile get_va_profile(AVCodecContext *ctx)
Determines the matching VA profile for the codec configuration.
int set_frame(AVFrame *frame, AVBufferRef *hw_frames_ctx_buf) override
Set the frame to be encoded.
Declarations for common platform specific utilities.
std::shared_ptr< display_t > display(mem_type_e hwdevice_type, const std::string &display_name, const video::config_t &config)
Get the display_t instance for the given hwdevice_type. If display_name is empty, use the first monit...
Declarations for the configuration of Sunshine.
int open_encode_render_node(bool nvenc)
Open the render node of the best GPU to encode a stream on.
void note_vaapi_encode_gpu(int fd)
Record the GPU a VAAPI encoder actually opened, from its DRM fd.
rgb_t create_blank(platf::img_t &img)
Create a black RGB texture of the specified image size.
Declarations for graphics related functions.
Declarations for logging related functions.
Miscellaneous declarations for Linux.
unsigned int driver_quirks
Declarations for utility functions.
int encode_capability(int fd)
Rank what the GPU behind fd can encode, for choosing between GPUs.