14#include <ffnvcodec/dynlink_loader.h>
18#include <libavcodec/avcodec.h>
19#include <libavutil/hwcontext_cuda.h>
20#include <libavutil/imgutils.h>
32#define HERMES_STRINGVIEW_HELPER(x) x##sv
33#define HERMES_STRINGVIEW(x) HERMES_STRINGVIEW_HELPER(x)
35#define CU_CHECK(x, y) \
36 if (check((x), HERMES_STRINGVIEW(y ": "))) \
39#define CU_CHECK_IGNORE(x, y) \
40 check((x), HERMES_STRINGVIEW(y ": "))
42namespace fs = std::filesystem;
44using namespace std::literals;
47 constexpr auto cudaDevAttrMaxThreadsPerBlock = (CUdevice_attribute) 1;
48 constexpr auto cudaDevAttrMaxThreadsPerMultiProcessor = (CUdevice_attribute) 39;
50 void pass_error(
const std::string_view &sv,
const char *name,
const char *description) {
51 BOOST_LOG(error) << sv << name <<
':' << description;
54 void cff(CudaFunctions *cf) {
55 cuda_free_functions(&cf);
58 using cdf_t = util::safe_ptr<CudaFunctions, cff>;
62 inline static int check(CUresult result,
const std::string_view &sv) {
63 if (result != CUDA_SUCCESS) {
65 const char *description;
67 cdf->cuGetErrorName(result, &name);
68 cdf->cuGetErrorString(result, &description);
70 BOOST_LOG(error) << sv << name <<
':' << description;
77 void freeStream(CUstream stream) {
78 CU_CHECK_IGNORE(cdf->cuStreamDestroy(stream),
"Couldn't destroy cuda stream");
81 void unregisterResource(CUgraphicsResource resource) {
82 CU_CHECK_IGNORE(cdf->cuGraphicsUnregisterResource(resource),
"Couldn't unregister resource");
85 using registered_resource_t = util::safe_ptr<CUgraphicsResource_st, unregisterResource>;
93 auto status = cuda_load_functions(&cdf,
nullptr);
95 BOOST_LOG(error) <<
"Couldn't load cuda: "sv << status;
100 CU_CHECK(cdf->cuInit(0),
"Couldn't initialize cuda");
106 constexpr unsigned int cuMemHostAllocPortable = 0x01;
114 CUresult (*alloc)(
void **ptr, std::size_t size,
unsigned int flags);
115 CUresult (*free)(
void *ptr);
121 loaded.alloc =
reinterpret_cast<decltype(loaded.alloc)
>(dlsym(cdf->lib,
"cuMemHostAlloc"));
122 loaded.free =
reinterpret_cast<decltype(loaded.free)
>(dlsym(cdf->lib,
"cuMemFreeHost"));
125 return functions.alloc && functions.free ? &functions :
nullptr;
130 constexpr unsigned int ffmpegPrimaryContextFlags = CU_CTX_SCHED_BLOCKING_SYNC;
132 void *alloc_host(std::size_t size) {
134 static std::mutex init_mutex;
135 std::lock_guard lock {init_mutex};
136 if (!cdf && init()) {
140 const auto *host_memory = host_memory_functions();
146 if (CU_CHECK_IGNORE(cdf->cuDeviceGet(&device, 0),
"Couldn't get the CUDA device for page-locked frames")) {
150 unsigned int flags = 0;
152 if (CU_CHECK_IGNORE(cdf->cuDevicePrimaryCtxGetState(device, &flags, &active),
"Couldn't query the primary CUDA context")) {
157 if (!active && flags != ffmpegPrimaryContextFlags &&
158 CU_CHECK_IGNORE(cdf->cuDevicePrimaryCtxSetFlags(device, ffmpegPrimaryContextFlags),
"Couldn't set the primary CUDA context flags")) {
163 if (CU_CHECK_IGNORE(cdf->cuDevicePrimaryCtxRetain(&context, device),
"Couldn't retain the primary CUDA context")) {
168 if (!CU_CHECK_IGNORE(cdf->cuCtxPushCurrent(context),
"Couldn't make the primary CUDA context current")) {
169 if (CU_CHECK_IGNORE(host_memory->alloc(&ptr, size, cuMemHostAllocPortable),
"Couldn't allocate a page-locked frame")) {
173 CU_CHECK_IGNORE(cdf->cuCtxPopCurrent(&popped),
"Couldn't restore the CUDA context");
178 CU_CHECK_IGNORE(cdf->cuDevicePrimaryCtxRelease(device),
"Couldn't release the primary CUDA context");
183 void free_host(
void *ptr) {
184 const auto *host_memory = ptr && cdf ? host_memory_functions() : nullptr;
190 if (CU_CHECK_IGNORE(cdf->cuDeviceGet(&device, 0),
"Couldn't get the CUDA device to free a page-locked frame")) {
194 if (CU_CHECK_IGNORE(cdf->cuDevicePrimaryCtxRetain(&context, device),
"Couldn't retain the primary CUDA context")) {
197 if (!CU_CHECK_IGNORE(cdf->cuCtxPushCurrent(context),
"Couldn't make the primary CUDA context current")) {
198 CU_CHECK_IGNORE(host_memory->free(ptr),
"Couldn't free a page-locked frame");
200 CU_CHECK_IGNORE(cdf->cuCtxPopCurrent(&popped),
"Couldn't restore the CUDA context");
203 CU_CHECK_IGNORE(cdf->cuDevicePrimaryCtxRelease(device),
"Couldn't release the primary CUDA context");
204 CU_CHECK_IGNORE(cdf->cuDevicePrimaryCtxRelease(device),
"Couldn't release the primary CUDA context");
209 int init(
int in_width,
int in_height) {
211 BOOST_LOG(warning) <<
"cuda not initialized"sv;
223 int set_frame(AVFrame *frame, AVBufferRef *hw_frames_ctx)
override {
224 this->hwframe.reset(frame);
227 auto hwframe_ctx = (AVHWFramesContext *) hw_frames_ctx->data;
229 if (hwframe_ctx->sw_format == AV_PIX_FMT_NV12) {
231 }
else if (hwframe_ctx->sw_format == AV_PIX_FMT_P010) {
234 BOOST_LOG(error) <<
"cuda::cuda_t supports only AV_PIX_FMT_NV12 and AV_PIX_FMT_P010"sv;
238 if (!frame->buf[0]) {
239 if (av_hwframe_get_buffer(hw_frames_ctx, frame, 0)) {
240 BOOST_LOG(error) <<
"Couldn't get hwframe for NVENC"sv;
245 auto cuda_ctx = (AVCUDADeviceContext *) hwframe_ctx->device_ctx->hwctx;
247 stream = make_stream();
252 cuda_ctx->stream = stream.get();
254 auto sws_opt = sws_t::make(width, height, frame->width, frame->height, width * 4,
layout, output_bits);
259 sws = std::move(*sws_opt);
261 linear_interpolation = width != frame->width || height != frame->height;
262 sws.linear = linear_interpolation;
267 void apply_colorspace()
override {
268 sws.apply_colorspace(colorspace);
270 auto tex = tex_t::make(height, width * 4,
layout);
281 img.row_pitch = img.width * img.pixel_pitch;
283 std::vector<std::uint8_t> image_data;
284 image_data.resize(img.row_pitch * img.height);
286 img.data = image_data.data();
288 if (sws.load_ram(img, tex->array)) {
292 sws.convert(frame->data[0], frame->data[1], frame->linesize[0], frame->linesize[1], tex->texture.linear, stream.get(), {frame->width, frame->height, 0, 0});
295 cudaTextureObject_t tex_obj(
const tex_t &tex)
const {
296 return linear_interpolation ? tex.texture.linear : tex.texture.point;
305 bool linear_interpolation;
316 return sws.load_ram(img, tex.array) || sws.convert(frame->data[0], frame->data[1], frame->linesize[0], frame->linesize[1], tex_obj(tex), stream.get());
319 int set_frame(AVFrame *frame, AVBufferRef *hw_frames_ctx)
override {
324 auto tex_opt = tex_t::make(height, width * 4,
layout);
329 tex = std::move(*tex_opt);
340 return sws.convert(frame->data[0], frame->data[1], frame->linesize[0], frame->linesize[1], tex_obj(((
img_t *) &img)->tex), stream.get());
351 CU_CHECK(cdf->cuDeviceGet(&device, index),
"Couldn't get CUDA device");
355 std::array<char, 13> pci_bus_id;
356 CU_CHECK(cdf->cuDeviceGetPCIBusId(pci_bus_id.data(), pci_bus_id.size(), device),
"Couldn't get CUDA device PCI bus ID");
357 BOOST_LOG(debug) <<
"Found CUDA device with PCI bus ID: "sv << pci_bus_id.data();
360 std::transform(pci_bus_id.begin(), pci_bus_id.end(), pci_bus_id.begin(), [](
char c) {
361 return std::tolower(c);
366 char sysfs_path[PATH_MAX];
367 std::snprintf(sysfs_path,
sizeof(sysfs_path),
"/sys/bus/pci/devices/%s/drm", pci_bus_id.data());
368 fs::path sysfs_dir {sysfs_path};
369 for (
auto &entry : fs::directory_iterator {sysfs_dir}) {
370 auto file = entry.path().filename();
371 auto filestring = file.generic_string();
372 if (std::string_view {filestring}.substr(0, 4) !=
"card"sv) {
376 BOOST_LOG(debug) <<
"Found DRM primary node: "sv << filestring;
378 fs::path dri_path {
"/dev/dri"sv};
379 auto device_path = dri_path / file;
382 }
catch (
const std::filesystem::filesystem_error &err) {
383 BOOST_LOG(error) <<
"Failed to read sysfs: "sv << err.what();
386 BOOST_LOG(error) <<
"Unable to find DRM device with PCI bus ID: "sv << pci_bus_id.data();
400 int init(
int in_width,
int in_height,
int offset_x,
int offset_y) {
408 BOOST_LOG(error) <<
"Couldn't open DRM FD for CUDA device: "sv << strerror_r(errno,
string,
sizeof(
string));
412 gbm.reset(gbm::create_device(file.el));
414 BOOST_LOG(error) <<
"Couldn't create GBM device: ["sv << util::hex(eglGetError()).to_string_view() <<
']';
418 display = egl::make_display(gbm.get());
423 auto ctx_opt = egl::make_ctx(display.get());
428 ctx = std::move(*ctx_opt);
435 this->offset_x = offset_x;
436 this->offset_y = offset_y;
447 int set_frame(AVFrame *frame, AVBufferRef *hw_frames_ctx_buf)
override {
448 this->hwframe.reset(frame);
451 if (!frame->buf[0]) {
452 if (av_hwframe_get_buffer(hw_frames_ctx_buf, frame, 0)) {
453 BOOST_LOG(error) <<
"Couldn't get hwframe for VAAPI"sv;
458 auto hw_frames_ctx = (AVHWFramesContext *) hw_frames_ctx_buf->data;
459 sw_format = hw_frames_ctx->sw_format;
466 auto sws_opt = egl::sws_t::make(width, height, frame->width, frame->height, sw_format);
471 this->sws = std::move(*sws_opt);
472 this->nv12 = std::move(*nv12_opt);
474 auto cuda_ctx = (AVCUDADeviceContext *) hw_frames_ctx->device_ctx->hwctx;
476 stream = make_stream();
481 cuda_ctx->stream = stream.get();
483 CU_CHECK(cdf->cuGraphicsGLRegisterImage(&y_res, nv12->tex[0], GL_TEXTURE_2D, CU_GRAPHICS_REGISTER_FLAGS_READ_ONLY),
"Couldn't register Y plane texture");
484 CU_CHECK(cdf->cuGraphicsGLRegisterImage(&uv_res, nv12->tex[1], GL_TEXTURE_2D, CU_GRAPHICS_REGISTER_FLAGS_READ_ONLY),
"Couldn't register UV plane texture");
497 if (descriptor.sequence == 0) {
500 }
else if (descriptor.sequence > sequence) {
501 sequence = descriptor.sequence;
505 auto rgb_opt = egl::import_source(display.get(), descriptor.sd);
511 rgb = std::move(*rgb_opt);
515 sws.load_vram(descriptor, offset_x, offset_y, rgb->tex[0]);
516 if (sws.convert(nv12->buf)) {
520 auto fmt_desc = av_pix_fmt_desc_get(sw_format);
523 CUgraphicsResource resources[2] = {y_res.get(), uv_res.get()};
524 CU_CHECK(cdf->cuGraphicsMapResources(2, resources, stream.get()),
"Couldn't map GL textures in CUDA");
526 auto unmap = util::fail_guard([&]() {
527 CU_CHECK_IGNORE(cdf->cuGraphicsUnmapResources(2, resources, stream.get()),
"Couldn't unmap GL textures from CUDA");
531 for (
int i = 0; i < 2; i++) {
532 CUDA_MEMCPY2D cpy = {};
533 cpy.srcMemoryType = CU_MEMORYTYPE_ARRAY;
534 CU_CHECK(cdf->cuGraphicsSubResourceGetMappedArray(&cpy.srcArray, resources[i], 0, 0),
"Couldn't get mapped plane array");
536 cpy.dstMemoryType = CU_MEMORYTYPE_DEVICE;
537 cpy.dstDevice = (CUdeviceptr) frame->data[i];
538 cpy.dstPitch = frame->linesize[i];
539 cpy.WidthInBytes = (frame->width * fmt_desc->comp[i].step) >> (i ? fmt_desc->log2_chroma_w : 0);
540 cpy.Height = frame->height >> (i ? fmt_desc->log2_chroma_h : 0);
542 CU_CHECK(cdf->cuMemcpy2DAsync(&cpy, stream.get()),
"Couldn't copy texture to CUDA frame");
546 const auto result = cdf->cuGraphicsUnmapResources(2, resources, stream.get());
548 CU_CHECK(result,
"Couldn't unmap GL textures from CUDA");
556 sws.apply_colorspace(colorspace);
561 egl::display_t display;
570 AVPixelFormat sw_format;
574 std::uint64_t sequence;
577 registered_resource_t y_res;
578 registered_resource_t uv_res;
580 int offset_x, offset_y;
583 std::unique_ptr<platf::avcodec_encode_device_t> make_avcodec_encode_device(
int width,
int height,
bool vram, pixel::layout_e layout) {
588 std::unique_ptr<cuda_t>
cuda;
591 cuda = std::make_unique<cuda_vram_t>();
593 cuda = std::make_unique<cuda_ram_t>();
594 cuda->layout = layout;
597 if (
cuda->init(width, height)) {
617 auto cuda = std::make_unique<gl_cuda_vram_t>();
619 if (cuda->init(width, height, offset_x, offset_y)) {
627 static PNVFBCCREATEINSTANCE createInstance {};
628 static NVFBC_API_FUNCTION_LIST func {NVFBC_VERSION};
630 static constexpr inline NVFBC_BOOL nv_bool(
bool b) {
631 return b ? NVFBC_TRUE : NVFBC_FALSE;
634 static void *handle {
nullptr};
637 static bool funcs_loaded =
false;
644 handle = dyn::handle({
"libnvidia-fbc.so.1",
"libnvidia-fbc.so"});
650 std::vector<std::tuple<dyn::apiproc *, const char *>> funcs {
651 {(dyn::apiproc *) &createInstance,
"NvFBCCreateInstance"},
654 if (dyn::load(handle, funcs)) {
661 auto status = cuda::nvfbc::createInstance(&cuda::nvfbc::func);
663 BOOST_LOG(error) <<
"Unable to create NvFBC instance"sv;
676 ctx_t(NVFBC_SESSION_HANDLE handle) {
677 NVFBC_BIND_CONTEXT_PARAMS params {NVFBC_BIND_CONTEXT_PARAMS_VER};
679 if (func.nvFBCBindContext(handle, ¶ms)) {
680 BOOST_LOG(error) <<
"Couldn't bind NvFBC context to current thread: " << func.nvFBCGetLastErrorStr(handle);
683 this->handle = handle;
687 NVFBC_RELEASE_CONTEXT_PARAMS params {NVFBC_RELEASE_CONTEXT_PARAMS_VER};
688 if (func.nvFBCReleaseContext(handle, ¶ms)) {
689 BOOST_LOG(error) <<
"Couldn't release NvFBC context from current thread: " << func.nvFBCGetLastErrorStr(handle);
693 NVFBC_SESSION_HANDLE handle;
704 handle_t() =
default;
706 handle_t(handle_t &&other):
707 handle_flags {other.handle_flags},
708 handle {other.handle} {
709 other.handle_flags.reset();
712 handle_t &operator=(handle_t &&other) {
713 std::swap(handle_flags, other.handle_flags);
714 std::swap(handle, other.handle);
719 static std::optional<handle_t> make() {
720 NVFBC_CREATE_HANDLE_PARAMS params {NVFBC_CREATE_HANDLE_PARAMS_VER};
724 const unsigned int MAGIC_PRIVATE_DATA[4] = {0xAEF57AC5, 0x401D1A39, 0x1B856BBE, 0x9ED0CEBA};
725 params.privateData = MAGIC_PRIVATE_DATA;
726 params.privateDataSize =
sizeof(MAGIC_PRIVATE_DATA);
729 auto status = func.nvFBCCreateHandle(&handle.handle, ¶ms);
731 BOOST_LOG(error) <<
"Failed to create session: "sv << handle.last_error();
736 handle.handle_flags[SESSION_HANDLE] =
true;
741 const char *last_error() {
742 return func.nvFBCGetLastErrorStr(handle);
745 std::optional<NVFBC_GET_STATUS_PARAMS> status() {
746 NVFBC_GET_STATUS_PARAMS params {NVFBC_GET_STATUS_PARAMS_VER};
748 auto status = func.nvFBCGetStatus(handle, ¶ms);
750 BOOST_LOG(error) <<
"Failed to get NvFBC status: "sv << last_error();
758 int capture(NVFBC_CREATE_CAPTURE_SESSION_PARAMS &capture_params) {
759 if (func.nvFBCCreateCaptureSession(handle, &capture_params)) {
760 BOOST_LOG(error) <<
"Failed to start capture session: "sv << last_error();
764 handle_flags[SESSION_CAPTURE] =
true;
766 NVFBC_TOCUDA_SETUP_PARAMS setup_params {
767 NVFBC_TOCUDA_SETUP_PARAMS_VER,
768 NVFBC_BUFFER_FORMAT_BGRA,
771 if (func.nvFBCToCudaSetUp(handle, &setup_params)) {
772 BOOST_LOG(error) <<
"Failed to setup cuda interop with nvFBC: "sv << last_error();
779 if (!handle_flags[SESSION_CAPTURE]) {
783 NVFBC_DESTROY_CAPTURE_SESSION_PARAMS params {NVFBC_DESTROY_CAPTURE_SESSION_PARAMS_VER};
785 if (func.nvFBCDestroyCaptureSession(handle, ¶ms)) {
786 BOOST_LOG(error) <<
"Couldn't destroy capture session: "sv << last_error();
791 handle_flags[SESSION_CAPTURE] =
false;
797 if (!handle_flags[SESSION_HANDLE]) {
803 NVFBC_DESTROY_HANDLE_PARAMS params {NVFBC_DESTROY_HANDLE_PARAMS_VER};
806 if (func.nvFBCDestroyHandle(handle, ¶ms)) {
807 BOOST_LOG(error) <<
"Couldn't destroy session handle: "sv << func.nvFBCGetLastErrorStr(handle);
810 handle_flags[SESSION_HANDLE] =
false;
819 std::bitset<MAX_FLAGS> handle_flags;
821 NVFBC_SESSION_HANDLE handle;
826 int init(
const std::string_view &display_name, const ::video::config_t &config) {
827 auto handle = handle_t::make();
832 ctx_t ctx {handle->handle};
834 auto status_params = handle->status();
835 if (!status_params) {
839 int streamedMonitor = -1;
840 if (!display_name.empty()) {
841 if (status_params->bXRandRAvailable) {
842 auto monitor_nr = util::from_view(display_name);
844 if (monitor_nr < 0 || monitor_nr >= status_params->dwOutputNum) {
845 BOOST_LOG(warning) <<
"Can't stream monitor ["sv << monitor_nr <<
"], it needs to be between [0] and ["sv << status_params->dwOutputNum - 1 <<
"], defaulting to virtual desktop"sv;
847 streamedMonitor = monitor_nr;
850 BOOST_LOG(warning) <<
"XrandR not available, streaming entire virtual desktop"sv;
854 delay = std::chrono::nanoseconds {1s} / config.framerate;
856 capture_params = NVFBC_CREATE_CAPTURE_SESSION_PARAMS {NVFBC_CREATE_CAPTURE_SESSION_PARAMS_VER};
858 capture_params.eCaptureType = NVFBC_CAPTURE_SHARED_CUDA;
859 capture_params.bDisableAutoModesetRecovery = nv_bool(
true);
861 capture_params.dwSamplingRateMs = 1000 / config.framerate;
863 if (streamedMonitor != -1) {
864 auto &output = status_params->outputs[streamedMonitor];
866 width = output.trackedBox.w;
867 height = output.trackedBox.h;
868 offset_x = output.trackedBox.x;
869 offset_y = output.trackedBox.y;
871 capture_params.eTrackingType = NVFBC_TRACKING_OUTPUT;
872 capture_params.dwOutputId = output.dwId;
874 capture_params.eTrackingType = NVFBC_TRACKING_SCREEN;
876 width = status_params->screenSize.w;
877 height = status_params->screenSize.h;
880 env_width = status_params->screenSize.w;
881 env_height = status_params->screenSize.h;
883 this->handle = std::move(*handle);
888 auto next_frame = std::chrono::steady_clock::now();
893 std::shared_ptr<platf::img_t> img_dummy;
894 pull_free_image_cb(img_dummy);
898 cursor_visible = !*cursor;
900 ctx_t ctx {handle.handle};
901 auto fg = util::fail_guard([&]() {
905 sleep_overshoot_logger.reset();
908 auto now = std::chrono::steady_clock::now();
909 if (next_frame > now) {
910 std::this_thread::sleep_for(next_frame - now);
911 sleep_overshoot_logger.first_point(next_frame);
912 sleep_overshoot_logger.second_point_now_and_log();
916 if (next_frame < now) {
917 next_frame = now + delay;
920 std::shared_ptr<platf::img_t> img_out;
921 auto status = snapshot(pull_free_image_cb, img_out, 150ms, *cursor);
928 if (!push_captured_image_cb(std::move(img_out),
false)) {
933 if (!push_captured_image_cb(std::move(img_out),
true)) {
938 BOOST_LOG(error) <<
"Unrecognized capture status ["sv << (int) status <<
']';
952 cursor_visible = cursor;
954 capture_params.bPushModel = nv_bool(
false);
955 capture_params.bWithCursor = nv_bool(
true);
956 capture_params.bAllowDirectCapture = nv_bool(
false);
958 capture_params.bPushModel = nv_bool(
true);
959 capture_params.bWithCursor = nv_bool(
false);
960 capture_params.bAllowDirectCapture = nv_bool(
true);
963 if (handle.capture(capture_params)) {
964 return platf::capture_e::error;
968 if (capture_params.bAllowDirectCapture) {
969 CUdeviceptr device_ptr;
970 NVFBC_FRAME_GRAB_INFO info;
972 NVFBC_TOCUDA_GRAB_FRAME_PARAMS grab {
973 NVFBC_TOCUDA_GRAB_FRAME_PARAMS_VER,
974 NVFBC_TOCUDA_GRAB_FLAGS_NOWAIT,
981 for (
int x = 0; x < 3; ++x) {
982 if (
auto status = func.nvFBCToCudaGrabFrame(handle.handle, &grab)) {
983 if (status == NVFBC_ERR_MUST_RECREATE) {
984 return platf::capture_e::reinit;
987 BOOST_LOG(error) <<
"Couldn't capture nvFramebuffer: "sv << handle.last_error();
989 return platf::capture_e::error;
992 if (info.bDirectCapture) {
996 BOOST_LOG(debug) <<
"Direct capture failed attempt ["sv << x <<
']';
999 if (!info.bDirectCapture) {
1000 BOOST_LOG(debug) <<
"Direct capture failed, trying the extra copy method"sv;
1002 capture_params.bPushModel = nv_bool(
false);
1003 capture_params.bWithCursor = nv_bool(
false);
1004 capture_params.bAllowDirectCapture = nv_bool(
false);
1006 if (handle.stop() || handle.capture(capture_params)) {
1007 return platf::capture_e::error;
1012 return platf::capture_e::ok;
1016 if (cursor != cursor_visible) {
1017 auto status = reinit(cursor);
1018 if (status != platf::capture_e::ok) {
1023 CUdeviceptr device_ptr;
1024 NVFBC_FRAME_GRAB_INFO info;
1026 NVFBC_TOCUDA_GRAB_FRAME_PARAMS grab {
1027 NVFBC_TOCUDA_GRAB_FRAME_PARAMS_VER,
1028 NVFBC_TOCUDA_GRAB_FLAGS_NOWAIT,
1031 (std::uint32_t)
timeout.count(),
1034 if (
auto status = func.nvFBCToCudaGrabFrame(handle.handle, &grab)) {
1035 if (status == NVFBC_ERR_MUST_RECREATE) {
1036 return platf::capture_e::reinit;
1039 BOOST_LOG(error) <<
"Couldn't capture nvFramebuffer: "sv << handle.last_error();
1040 return platf::capture_e::error;
1043 if (!pull_free_image_cb(img_out)) {
1044 return platf::capture_e::interrupted;
1046 auto img = (img_t *) img_out.get();
1048 if (img->tex.copy((std::uint8_t *) device_ptr, img->height, img->row_pitch)) {
1049 return platf::capture_e::error;
1052 return platf::capture_e::ok;
1055 std::unique_ptr<platf::avcodec_encode_device_t> make_avcodec_encode_device(platf::pix_fmt_e pix_fmt)
override {
1056 return ::cuda::make_avcodec_encode_device(width, height,
true);
1059 std::shared_ptr<platf::img_t> alloc_img()
override {
1060 auto img = std::make_shared<cuda::img_t>();
1062 img->data =
nullptr;
1064 img->height = height;
1065 img->pixel_pitch = 4;
1066 img->row_pitch = img->width * img->pixel_pitch;
1068 auto tex_opt = tex_t::make(height, width * img->pixel_pitch);
1073 img->tex = std::move(*tex_opt);
1078 int dummy_img(platf::img_t *)
override {
1082 std::chrono::nanoseconds delay;
1084 bool cursor_visible;
1087 NVFBC_CREATE_CAPTURE_SESSION_PARAMS capture_params;
1093 std::shared_ptr<display_t> nvfbc_display(
mem_type_e hwdevice_type,
const std::string &display_name,
const video::config_t &config) {
1095 BOOST_LOG(
error) <<
"Could not initialize nvfbc display with the given hw device type"sv;
1099 auto display = std::make_shared<cuda::nvfbc::display_t>();
1101 if (
display->init(display_name, config)) {
1108 std::vector<std::string> nvfbc_display_names() {
1109 if (cuda::init() || cuda::nvfbc::init()) {
1113 std::vector<std::string> display_names;
1115 auto handle = cuda::nvfbc::handle_t::make();
1120 auto status_params = handle->status();
1121 if (!status_params) {
1125 if (!status_params->bIsCapturePossible) {
1126 BOOST_LOG(
error) <<
"NVidia driver doesn't support NvFBC screencasting"sv;
1129 BOOST_LOG(info) <<
"Found ["sv << status_params->dwOutputNum <<
"] outputs"sv;
1130 BOOST_LOG(info) <<
"Virtual Desktop: "sv << status_params->screenSize.w <<
'x' << status_params->screenSize.h;
1131 BOOST_LOG(info) <<
"XrandR: "sv << (status_params->bXRandRAvailable ?
"available"sv :
"unavailable"sv);
1133 for (
auto x = 0; x < status_params->dwOutputNum; ++x) {
1134 auto &output = status_params->outputs[x];
1135 BOOST_LOG(info) <<
"-- Output --"sv;
1136 BOOST_LOG(debug) <<
" ID: "sv << output.dwId;
1137 BOOST_LOG(debug) <<
" Name: "sv << output.name;
1138 BOOST_LOG(info) <<
" Resolution: "sv << output.trackedBox.w <<
'x' << output.trackedBox.h;
1139 BOOST_LOG(info) <<
" Offset: "sv << output.trackedBox.x <<
'x' << output.trackedBox.y;
1140 display_names.emplace_back(std::to_string(x));
1143 return display_names;
int set_frame(AVFrame *frame, AVBufferRef *hw_frames_ctx) override
Set the frame to be encoded.
pixel::layout_e layout
Channel layout of the frames this device converts.
int set_frame(AVFrame *frame, AVBufferRef *hw_frames_ctx) override
Set the frame to be encoded.
int init(int in_width, int in_height, int offset_x, int offset_y)
Initialize the GL->CUDA encoding device.
int convert(platf::img_t &img) override
Convert the captured image into the target CUDA frame.
void apply_colorspace() override
Configures shader parameters for the specified colorspace.
int set_frame(AVFrame *frame, AVBufferRef *hw_frames_ctx_buf) override
Initialize color conversion into target CUDA frame.
platf::capture_e capture(const push_captured_image_cb_t &push_captured_image_cb, const pull_free_image_cb_t &pull_free_image_cb, bool *cursor) override
Capture a frame.
std::function< bool(std::shared_ptr< img_t > &&img, bool frame_captured)> push_captured_image_cb_t
Callback for when a new image is ready. When display has a new image ready or a timeout occurs,...
std::function< bool(std::shared_ptr< img_t > &img_out)> pull_free_image_cb_t
Get free image from pool. Calls must be synchronized. Blocks until there is free image in the pool or...
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...
@ reinit
Need to reinitialize.
@ interrupted
Capture was interrupted.
file_t open_drm_fd_for_cuda_device(int index)
Opens the DRM device associated with the CUDA device index.
std::unique_ptr< platf::avcodec_encode_device_t > make_avcodec_gl_encode_device(int width, int height, int offset_x, int offset_y)
Create a GL->CUDA encoding device for consuming captured dmabufs.
Definitions for CUDA implementation.
layout_e
How the 32-bit little-endian words of a CPU-copied frame hold their channels.
@ bgra8
DRM XRGB8888 / ARGB8888: bytes B, G, R, X.
rgb_t create_blank(platf::img_t &img)
Create a black RGB texture of the specified image size.
std::optional< nv12_t > create_target(int width, int height, AVPixelFormat format)
Create biplanar YUV textures to render into.
Declarations for graphics related functions.
Declarations for logging related functions.
int open_drm_node(const char *path, int flags)
Open a DRM device node without becoming its DRM master.
Miscellaneous declarations for Linux.
Declarations for utility functions.
Declarations for Wayland capture.