Hermes 0.7.0
Linux game streaming host
Loading...
Searching...
No Matches
cuda.cpp
Go to the documentation of this file.
1
5// standard includes
6#include <bitset>
7#include <dlfcn.h>
8#include <fcntl.h>
9#include <filesystem>
10#include <mutex>
11#include <thread>
12
13// lib includes
14#include <ffnvcodec/dynlink_loader.h>
15#include <NvFBC.h>
16
17extern "C" {
18#include <libavcodec/avcodec.h>
19#include <libavutil/hwcontext_cuda.h>
20#include <libavutil/imgutils.h>
21}
22
23// local includes
24#include "cuda.h"
25#include "graphics.h"
26#include "misc.h"
27#include "src/logging.h"
28#include "src/utility.h"
29#include "src/video.h"
30#include "wayland.h"
31
32#define HERMES_STRINGVIEW_HELPER(x) x##sv
33#define HERMES_STRINGVIEW(x) HERMES_STRINGVIEW_HELPER(x)
34
35#define CU_CHECK(x, y) \
36 if (check((x), HERMES_STRINGVIEW(y ": "))) \
37 return -1
38
39#define CU_CHECK_IGNORE(x, y) \
40 check((x), HERMES_STRINGVIEW(y ": "))
41
42namespace fs = std::filesystem;
43
44using namespace std::literals;
45
46namespace cuda {
47 constexpr auto cudaDevAttrMaxThreadsPerBlock = (CUdevice_attribute) 1;
48 constexpr auto cudaDevAttrMaxThreadsPerMultiProcessor = (CUdevice_attribute) 39;
49
50 void pass_error(const std::string_view &sv, const char *name, const char *description) {
51 BOOST_LOG(error) << sv << name << ':' << description;
52 }
53
54 void cff(CudaFunctions *cf) {
55 cuda_free_functions(&cf);
56 }
57
58 using cdf_t = util::safe_ptr<CudaFunctions, cff>;
59
60 static cdf_t cdf;
61
62 inline static int check(CUresult result, const std::string_view &sv) {
63 if (result != CUDA_SUCCESS) {
64 const char *name;
65 const char *description;
66
67 cdf->cuGetErrorName(result, &name);
68 cdf->cuGetErrorString(result, &description);
69
70 BOOST_LOG(error) << sv << name << ':' << description;
71 return -1;
72 }
73
74 return 0;
75 }
76
77 void freeStream(CUstream stream) {
78 CU_CHECK_IGNORE(cdf->cuStreamDestroy(stream), "Couldn't destroy cuda stream");
79 }
80
81 void unregisterResource(CUgraphicsResource resource) {
82 CU_CHECK_IGNORE(cdf->cuGraphicsUnregisterResource(resource), "Couldn't unregister resource");
83 }
84
85 using registered_resource_t = util::safe_ptr<CUgraphicsResource_st, unregisterResource>;
86
87 class img_t: public platf::img_t {
88 public:
89 tex_t tex;
90 };
91
92 int init() {
93 auto status = cuda_load_functions(&cdf, nullptr);
94 if (status) {
95 BOOST_LOG(error) << "Couldn't load cuda: "sv << status;
96
97 return -1;
98 }
99
100 CU_CHECK(cdf->cuInit(0), "Couldn't initialize cuda");
101
102 return 0;
103 }
104
105 // Not in the ffnvcodec headers.
106 constexpr unsigned int cuMemHostAllocPortable = 0x01;
107
114 CUresult (*alloc)(void **ptr, std::size_t size, unsigned int flags);
115 CUresult (*free)(void *ptr);
116 };
117
118 const host_memory_functions_t *host_memory_functions() {
119 static const host_memory_functions_t functions = [] {
120 host_memory_functions_t loaded {};
121 loaded.alloc = reinterpret_cast<decltype(loaded.alloc)>(dlsym(cdf->lib, "cuMemHostAlloc"));
122 loaded.free = reinterpret_cast<decltype(loaded.free)>(dlsym(cdf->lib, "cuMemFreeHost"));
123 return loaded;
124 }();
125 return functions.alloc && functions.free ? &functions : nullptr;
126 }
127
128 // FFmpeg's hwcontext_cuda opens device 0's primary context (Hermes passes no
129 // device) with these flags, and refuses an active one that has others.
130 constexpr unsigned int ffmpegPrimaryContextFlags = CU_CTX_SCHED_BLOCKING_SYNC;
131
132 void *alloc_host(std::size_t size) {
133 {
134 static std::mutex init_mutex;
135 std::lock_guard lock {init_mutex};
136 if (!cdf && init()) {
137 return nullptr;
138 }
139 }
140 const auto *host_memory = host_memory_functions();
141 if (!host_memory) {
142 return nullptr;
143 }
144
145 CUdevice device;
146 if (CU_CHECK_IGNORE(cdf->cuDeviceGet(&device, 0), "Couldn't get the CUDA device for page-locked frames")) {
147 return nullptr;
148 }
149
150 unsigned int flags = 0;
151 int active = 0;
152 if (CU_CHECK_IGNORE(cdf->cuDevicePrimaryCtxGetState(device, &flags, &active), "Couldn't query the primary CUDA context")) {
153 return nullptr;
154 }
155 // Activating the context with the driver's default flags first would make
156 // FFmpeg reject it for the whole session.
157 if (!active && flags != ffmpegPrimaryContextFlags &&
158 CU_CHECK_IGNORE(cdf->cuDevicePrimaryCtxSetFlags(device, ffmpegPrimaryContextFlags), "Couldn't set the primary CUDA context flags")) {
159 return nullptr;
160 }
161
162 CUcontext context;
163 if (CU_CHECK_IGNORE(cdf->cuDevicePrimaryCtxRetain(&context, device), "Couldn't retain the primary CUDA context")) {
164 return nullptr;
165 }
166
167 void *ptr = nullptr;
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")) {
170 ptr = nullptr;
171 }
172 CUcontext popped;
173 CU_CHECK_IGNORE(cdf->cuCtxPopCurrent(&popped), "Couldn't restore the CUDA context");
174 }
175
176 // A live allocation keeps its retain on the context; see free_host().
177 if (!ptr) {
178 CU_CHECK_IGNORE(cdf->cuDevicePrimaryCtxRelease(device), "Couldn't release the primary CUDA context");
179 }
180 return ptr;
181 }
182
183 void free_host(void *ptr) {
184 const auto *host_memory = ptr && cdf ? host_memory_functions() : nullptr;
185 if (!host_memory) {
186 return;
187 }
188
189 CUdevice device;
190 if (CU_CHECK_IGNORE(cdf->cuDeviceGet(&device, 0), "Couldn't get the CUDA device to free a page-locked frame")) {
191 return;
192 }
193 CUcontext context;
194 if (CU_CHECK_IGNORE(cdf->cuDevicePrimaryCtxRetain(&context, device), "Couldn't retain the primary CUDA context")) {
195 return;
196 }
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");
199 CUcontext popped;
200 CU_CHECK_IGNORE(cdf->cuCtxPopCurrent(&popped), "Couldn't restore the CUDA context");
201 }
202 // This call's retain, then the one alloc_host() kept for the allocation.
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");
205 }
206
208 public:
209 int init(int in_width, int in_height) {
210 if (!cdf) {
211 BOOST_LOG(warning) << "cuda not initialized"sv;
212 return -1;
213 }
214
215 data = (void *) 0x1;
216
217 width = in_width;
218 height = in_height;
219
220 return 0;
221 }
222
223 int set_frame(AVFrame *frame, AVBufferRef *hw_frames_ctx) override {
224 this->hwframe.reset(frame);
225 this->frame = frame;
226
227 auto hwframe_ctx = (AVHWFramesContext *) hw_frames_ctx->data;
228 int output_bits;
229 if (hwframe_ctx->sw_format == AV_PIX_FMT_NV12) {
230 output_bits = 8;
231 } else if (hwframe_ctx->sw_format == AV_PIX_FMT_P010) {
232 output_bits = 10;
233 } else {
234 BOOST_LOG(error) << "cuda::cuda_t supports only AV_PIX_FMT_NV12 and AV_PIX_FMT_P010"sv;
235 return -1;
236 }
237
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;
241 return -1;
242 }
243 }
244
245 auto cuda_ctx = (AVCUDADeviceContext *) hwframe_ctx->device_ctx->hwctx;
246
247 stream = make_stream();
248 if (!stream) {
249 return -1;
250 }
251
252 cuda_ctx->stream = stream.get();
253
254 auto sws_opt = sws_t::make(width, height, frame->width, frame->height, width * 4, layout, output_bits);
255 if (!sws_opt) {
256 return -1;
257 }
258
259 sws = std::move(*sws_opt);
260
261 linear_interpolation = width != frame->width || height != frame->height;
262 sws.linear = linear_interpolation;
263
264 return 0;
265 }
266
267 void apply_colorspace() override {
268 sws.apply_colorspace(colorspace);
269
270 auto tex = tex_t::make(height, width * 4, layout);
271 if (!tex) {
272 return;
273 }
274
275 // The default green color is ugly.
276 // Update the background color
277 platf::img_t img;
278 img.width = width;
279 img.height = height;
280 img.pixel_pitch = 4;
281 img.row_pitch = img.width * img.pixel_pitch;
282
283 std::vector<std::uint8_t> image_data;
284 image_data.resize(img.row_pitch * img.height);
285
286 img.data = image_data.data();
287
288 if (sws.load_ram(img, tex->array)) {
289 return;
290 }
291
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});
293 }
294
295 cudaTextureObject_t tex_obj(const tex_t &tex) const {
296 return linear_interpolation ? tex.texture.linear : tex.texture.point;
297 }
298
299 stream_t stream;
300 frame_t hwframe;
301
302 int width, height;
303
304 // When height and width don't change, it's not necessary to use linear interpolation
305 bool linear_interpolation;
306
309
310 sws_t sws;
311 };
312
313 class cuda_ram_t: public cuda_t {
314 public:
315 int convert(platf::img_t &img) override {
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());
317 }
318
319 int set_frame(AVFrame *frame, AVBufferRef *hw_frames_ctx) override {
320 if (cuda_t::set_frame(frame, hw_frames_ctx)) {
321 return -1;
322 }
323
324 auto tex_opt = tex_t::make(height, width * 4, layout);
325 if (!tex_opt) {
326 return -1;
327 }
328
329 tex = std::move(*tex_opt);
330
331 return 0;
332 }
333
334 tex_t tex;
335 };
336
337 class cuda_vram_t: public cuda_t {
338 public:
339 int convert(platf::img_t &img) override {
340 return sws.convert(frame->data[0], frame->data[1], frame->linesize[0], frame->linesize[1], tex_obj(((img_t *) &img)->tex), stream.get());
341 }
342 };
343
349 file_t open_drm_fd_for_cuda_device(int index) {
350 CUdevice device;
351 CU_CHECK(cdf->cuDeviceGet(&device, index), "Couldn't get CUDA device");
352
353 // There's no way to directly go from CUDA to a DRM device, so we'll
354 // use sysfs to look up the DRM device name from the PCI ID.
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();
358
359 // Linux uses lowercase hexadecimal while CUDA uses uppercase
360 std::transform(pci_bus_id.begin(), pci_bus_id.end(), pci_bus_id.begin(), [](char c) {
361 return std::tolower(c);
362 });
363
364 // Look for the name of the primary node in sysfs
365 try {
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) {
373 continue;
374 }
375
376 BOOST_LOG(debug) << "Found DRM primary node: "sv << filestring;
377
378 fs::path dri_path {"/dev/dri"sv};
379 auto device_path = dri_path / file;
380 return platf::open_drm_node(device_path.c_str(), O_RDWR);
381 }
382 } catch (const std::filesystem::filesystem_error &err) {
383 BOOST_LOG(error) << "Failed to read sysfs: "sv << err.what();
384 }
385
386 BOOST_LOG(error) << "Unable to find DRM device with PCI bus ID: "sv << pci_bus_id.data();
387 return -1;
388 }
389
391 public:
400 int init(int in_width, int in_height, int offset_x, int offset_y) {
401 // This must be non-zero to tell the video core that it's a hardware encoding device.
402 data = (void *) 0x1;
403
404 // TODO: Support more than one CUDA device
405 file = std::move(open_drm_fd_for_cuda_device(0));
406 if (file.el < 0) {
407 char string[1024];
408 BOOST_LOG(error) << "Couldn't open DRM FD for CUDA device: "sv << strerror_r(errno, string, sizeof(string));
409 return -1;
410 }
411
412 gbm.reset(gbm::create_device(file.el));
413 if (!gbm) {
414 BOOST_LOG(error) << "Couldn't create GBM device: ["sv << util::hex(eglGetError()).to_string_view() << ']';
415 return -1;
416 }
417
418 display = egl::make_display(gbm.get());
419 if (!display) {
420 return -1;
421 }
422
423 auto ctx_opt = egl::make_ctx(display.get());
424 if (!ctx_opt) {
425 return -1;
426 }
427
428 ctx = std::move(*ctx_opt);
429
430 width = in_width;
431 height = in_height;
432
433 sequence = 0;
434
435 this->offset_x = offset_x;
436 this->offset_y = offset_y;
437
438 return 0;
439 }
440
447 int set_frame(AVFrame *frame, AVBufferRef *hw_frames_ctx_buf) override {
448 this->hwframe.reset(frame);
449 this->frame = frame;
450
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;
454 return -1;
455 }
456 }
457
458 auto hw_frames_ctx = (AVHWFramesContext *) hw_frames_ctx_buf->data;
459 sw_format = hw_frames_ctx->sw_format;
460
461 auto nv12_opt = egl::create_target(frame->width, frame->height, sw_format);
462 if (!nv12_opt) {
463 return -1;
464 }
465
466 auto sws_opt = egl::sws_t::make(width, height, frame->width, frame->height, sw_format);
467 if (!sws_opt) {
468 return -1;
469 }
470
471 this->sws = std::move(*sws_opt);
472 this->nv12 = std::move(*nv12_opt);
473
474 auto cuda_ctx = (AVCUDADeviceContext *) hw_frames_ctx->device_ctx->hwctx;
475
476 stream = make_stream();
477 if (!stream) {
478 return -1;
479 }
480
481 cuda_ctx->stream = stream.get();
482
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");
485
486 return 0;
487 }
488
494 int convert(platf::img_t &img) override {
495 auto &descriptor = (egl::img_descriptor_t &) img;
496
497 if (descriptor.sequence == 0) {
498 // For dummy images, use a blank RGB texture instead of importing a DMA-BUF
499 rgb = egl::create_blank(img);
500 } else if (descriptor.sequence > sequence) {
501 sequence = descriptor.sequence;
502
503 rgb = egl::rgb_t {};
504
505 auto rgb_opt = egl::import_source(display.get(), descriptor.sd);
506
507 if (!rgb_opt) {
508 return -1;
509 }
510
511 rgb = std::move(*rgb_opt);
512 }
513
514 // Perform the color conversion and scaling in GL
515 sws.load_vram(descriptor, offset_x, offset_y, rgb->tex[0]);
516 if (sws.convert(nv12->buf)) {
517 return -1;
518 }
519
520 auto fmt_desc = av_pix_fmt_desc_get(sw_format);
521
522 // Map the GL textures to read for CUDA
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");
525
526 auto unmap = util::fail_guard([&]() {
527 CU_CHECK_IGNORE(cdf->cuGraphicsUnmapResources(2, resources, stream.get()), "Couldn't unmap GL textures from CUDA");
528 });
529
530 // Copy from the GL textures to the target CUDA frame
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");
535
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);
541
542 CU_CHECK(cdf->cuMemcpy2DAsync(&cpy, stream.get()), "Couldn't copy texture to CUDA frame");
543 }
544
545 // Unmap the textures to allow modification from GL again.
546 const auto result = cdf->cuGraphicsUnmapResources(2, resources, stream.get());
547 unmap.disable();
548 CU_CHECK(result, "Couldn't unmap GL textures from CUDA");
549 return 0;
550 }
551
555 void apply_colorspace() override {
556 sws.apply_colorspace(colorspace);
557 }
558
559 file_t file;
560 gbm::gbm_t gbm;
561 egl::display_t display;
562 egl::ctx_t ctx;
563
564 // This must be destroyed before display_t
565 stream_t stream;
566 frame_t hwframe;
567
568 egl::sws_t sws;
569 egl::nv12_t nv12;
570 AVPixelFormat sw_format;
571
572 int width, height;
573
574 std::uint64_t sequence;
575 egl::rgb_t rgb;
576
577 registered_resource_t y_res;
578 registered_resource_t uv_res;
579
580 int offset_x, offset_y;
581 };
582
583 std::unique_ptr<platf::avcodec_encode_device_t> make_avcodec_encode_device(int width, int height, bool vram, pixel::layout_e layout) {
584 if (init()) {
585 return nullptr;
586 }
587
588 std::unique_ptr<cuda_t> cuda;
589
590 if (vram) {
591 cuda = std::make_unique<cuda_vram_t>();
592 } else {
593 cuda = std::make_unique<cuda_ram_t>();
594 cuda->layout = layout;
595 }
596
597 if (cuda->init(width, height)) {
598 return nullptr;
599 }
600
601 return cuda;
602 }
603
612 std::unique_ptr<platf::avcodec_encode_device_t> make_avcodec_gl_encode_device(int width, int height, int offset_x, int offset_y) {
613 if (init()) {
614 return nullptr;
615 }
616
617 auto cuda = std::make_unique<gl_cuda_vram_t>();
618
619 if (cuda->init(width, height, offset_x, offset_y)) {
620 return nullptr;
621 }
622
623 return cuda;
624 }
625
626 namespace nvfbc {
627 static PNVFBCCREATEINSTANCE createInstance {};
628 static NVFBC_API_FUNCTION_LIST func {NVFBC_VERSION};
629
630 static constexpr inline NVFBC_BOOL nv_bool(bool b) {
631 return b ? NVFBC_TRUE : NVFBC_FALSE;
632 }
633
634 static void *handle {nullptr};
635
636 int init() {
637 static bool funcs_loaded = false;
638
639 if (funcs_loaded) {
640 return 0;
641 }
642
643 if (!handle) {
644 handle = dyn::handle({"libnvidia-fbc.so.1", "libnvidia-fbc.so"});
645 if (!handle) {
646 return -1;
647 }
648 }
649
650 std::vector<std::tuple<dyn::apiproc *, const char *>> funcs {
651 {(dyn::apiproc *) &createInstance, "NvFBCCreateInstance"},
652 };
653
654 if (dyn::load(handle, funcs)) {
655 dlclose(handle);
656 handle = nullptr;
657
658 return -1;
659 }
660
661 auto status = cuda::nvfbc::createInstance(&cuda::nvfbc::func);
662 if (status) {
663 BOOST_LOG(error) << "Unable to create NvFBC instance"sv;
664
665 dlclose(handle);
666 handle = nullptr;
667 return -1;
668 }
669
670 funcs_loaded = true;
671 return 0;
672 }
673
674 class ctx_t {
675 public:
676 ctx_t(NVFBC_SESSION_HANDLE handle) {
677 NVFBC_BIND_CONTEXT_PARAMS params {NVFBC_BIND_CONTEXT_PARAMS_VER};
678
679 if (func.nvFBCBindContext(handle, &params)) {
680 BOOST_LOG(error) << "Couldn't bind NvFBC context to current thread: " << func.nvFBCGetLastErrorStr(handle);
681 }
682
683 this->handle = handle;
684 }
685
686 ~ctx_t() {
687 NVFBC_RELEASE_CONTEXT_PARAMS params {NVFBC_RELEASE_CONTEXT_PARAMS_VER};
688 if (func.nvFBCReleaseContext(handle, &params)) {
689 BOOST_LOG(error) << "Couldn't release NvFBC context from current thread: " << func.nvFBCGetLastErrorStr(handle);
690 }
691 }
692
693 NVFBC_SESSION_HANDLE handle;
694 };
695
696 class handle_t {
697 enum flag_e {
698 SESSION_HANDLE,
699 SESSION_CAPTURE,
700 MAX_FLAGS,
701 };
702
703 public:
704 handle_t() = default;
705
706 handle_t(handle_t &&other):
707 handle_flags {other.handle_flags},
708 handle {other.handle} {
709 other.handle_flags.reset();
710 }
711
712 handle_t &operator=(handle_t &&other) {
713 std::swap(handle_flags, other.handle_flags);
714 std::swap(handle, other.handle);
715
716 return *this;
717 }
718
719 static std::optional<handle_t> make() {
720 NVFBC_CREATE_HANDLE_PARAMS params {NVFBC_CREATE_HANDLE_PARAMS_VER};
721
722 // Set privateData to allow NvFBC on consumer NVIDIA GPUs.
723 // Based on https://github.com/keylase/nvidia-patch/blob/3193b4b1cea91527bf09ea9b8db5aade6a3f3c0a/win/nvfbcwrp/nvfbcwrp_main.cpp#L23-L25 .
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);
727
728 handle_t handle;
729 auto status = func.nvFBCCreateHandle(&handle.handle, &params);
730 if (status) {
731 BOOST_LOG(error) << "Failed to create session: "sv << handle.last_error();
732
733 return std::nullopt;
734 }
735
736 handle.handle_flags[SESSION_HANDLE] = true;
737
738 return handle;
739 }
740
741 const char *last_error() {
742 return func.nvFBCGetLastErrorStr(handle);
743 }
744
745 std::optional<NVFBC_GET_STATUS_PARAMS> status() {
746 NVFBC_GET_STATUS_PARAMS params {NVFBC_GET_STATUS_PARAMS_VER};
747
748 auto status = func.nvFBCGetStatus(handle, &params);
749 if (status) {
750 BOOST_LOG(error) << "Failed to get NvFBC status: "sv << last_error();
751
752 return std::nullopt;
753 }
754
755 return params;
756 }
757
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();
761 return -1;
762 }
763
764 handle_flags[SESSION_CAPTURE] = true;
765
766 NVFBC_TOCUDA_SETUP_PARAMS setup_params {
767 NVFBC_TOCUDA_SETUP_PARAMS_VER,
768 NVFBC_BUFFER_FORMAT_BGRA,
769 };
770
771 if (func.nvFBCToCudaSetUp(handle, &setup_params)) {
772 BOOST_LOG(error) << "Failed to setup cuda interop with nvFBC: "sv << last_error();
773 return -1;
774 }
775 return 0;
776 }
777
778 int stop() {
779 if (!handle_flags[SESSION_CAPTURE]) {
780 return 0;
781 }
782
783 NVFBC_DESTROY_CAPTURE_SESSION_PARAMS params {NVFBC_DESTROY_CAPTURE_SESSION_PARAMS_VER};
784
785 if (func.nvFBCDestroyCaptureSession(handle, &params)) {
786 BOOST_LOG(error) << "Couldn't destroy capture session: "sv << last_error();
787
788 return -1;
789 }
790
791 handle_flags[SESSION_CAPTURE] = false;
792
793 return 0;
794 }
795
796 int reset() {
797 if (!handle_flags[SESSION_HANDLE]) {
798 return 0;
799 }
800
801 stop();
802
803 NVFBC_DESTROY_HANDLE_PARAMS params {NVFBC_DESTROY_HANDLE_PARAMS_VER};
804
805 ctx_t ctx {handle};
806 if (func.nvFBCDestroyHandle(handle, &params)) {
807 BOOST_LOG(error) << "Couldn't destroy session handle: "sv << func.nvFBCGetLastErrorStr(handle);
808 }
809
810 handle_flags[SESSION_HANDLE] = false;
811
812 return 0;
813 }
814
815 ~handle_t() {
816 reset();
817 }
818
819 std::bitset<MAX_FLAGS> handle_flags;
820
821 NVFBC_SESSION_HANDLE handle;
822 };
823
824 class display_t: public platf::display_t {
825 public:
826 int init(const std::string_view &display_name, const ::video::config_t &config) {
827 auto handle = handle_t::make();
828 if (!handle) {
829 return -1;
830 }
831
832 ctx_t ctx {handle->handle};
833
834 auto status_params = handle->status();
835 if (!status_params) {
836 return -1;
837 }
838
839 int streamedMonitor = -1;
840 if (!display_name.empty()) {
841 if (status_params->bXRandRAvailable) {
842 auto monitor_nr = util::from_view(display_name);
843
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;
846 } else {
847 streamedMonitor = monitor_nr;
848 }
849 } else {
850 BOOST_LOG(warning) << "XrandR not available, streaming entire virtual desktop"sv;
851 }
852 }
853
854 delay = std::chrono::nanoseconds {1s} / config.framerate;
855
856 capture_params = NVFBC_CREATE_CAPTURE_SESSION_PARAMS {NVFBC_CREATE_CAPTURE_SESSION_PARAMS_VER};
857
858 capture_params.eCaptureType = NVFBC_CAPTURE_SHARED_CUDA;
859 capture_params.bDisableAutoModesetRecovery = nv_bool(true);
860
861 capture_params.dwSamplingRateMs = 1000 /* ms */ / config.framerate;
862
863 if (streamedMonitor != -1) {
864 auto &output = status_params->outputs[streamedMonitor];
865
866 width = output.trackedBox.w;
867 height = output.trackedBox.h;
868 offset_x = output.trackedBox.x;
869 offset_y = output.trackedBox.y;
870
871 capture_params.eTrackingType = NVFBC_TRACKING_OUTPUT;
872 capture_params.dwOutputId = output.dwId;
873 } else {
874 capture_params.eTrackingType = NVFBC_TRACKING_SCREEN;
875
876 width = status_params->screenSize.w;
877 height = status_params->screenSize.h;
878 }
879
880 env_width = status_params->screenSize.w;
881 env_height = status_params->screenSize.h;
882
883 this->handle = std::move(*handle);
884 return 0;
885 }
886
887 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 {
888 auto next_frame = std::chrono::steady_clock::now();
889
890 {
891 // We must create at least one texture on this thread before calling NvFBCToCudaSetUp()
892 // Otherwise it fails with "Unable to register an OpenGL buffer to a CUDA resource (result: 201)" message
893 std::shared_ptr<platf::img_t> img_dummy;
894 pull_free_image_cb(img_dummy);
895 }
896
897 // Force display_t::capture to initialize handle_t::capture
898 cursor_visible = !*cursor;
899
900 ctx_t ctx {handle.handle};
901 auto fg = util::fail_guard([&]() {
902 handle.reset();
903 });
904
905 sleep_overshoot_logger.reset();
906
907 while (true) {
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();
913 }
914
915 next_frame += delay;
916 if (next_frame < now) { // some major slowdown happened; we couldn't keep up
917 next_frame = now + delay;
918 }
919
920 std::shared_ptr<platf::img_t> img_out;
921 auto status = snapshot(pull_free_image_cb, img_out, 150ms, *cursor);
922 switch (status) {
926 return status;
928 if (!push_captured_image_cb(std::move(img_out), false)) {
930 }
931 break;
933 if (!push_captured_image_cb(std::move(img_out), true)) {
935 }
936 break;
937 default:
938 BOOST_LOG(error) << "Unrecognized capture status ["sv << (int) status << ']';
939 return status;
940 }
941 }
942
944 }
945
946 // Reinitialize the capture session.
947 platf::capture_e reinit(bool cursor) {
948 if (handle.stop()) {
950 }
951
952 cursor_visible = cursor;
953 if (cursor) {
954 capture_params.bPushModel = nv_bool(false);
955 capture_params.bWithCursor = nv_bool(true);
956 capture_params.bAllowDirectCapture = nv_bool(false);
957 } else {
958 capture_params.bPushModel = nv_bool(true);
959 capture_params.bWithCursor = nv_bool(false);
960 capture_params.bAllowDirectCapture = nv_bool(true);
961 }
962
963 if (handle.capture(capture_params)) {
964 return platf::capture_e::error;
965 }
966
967 // If trying to capture directly, test if it actually does.
968 if (capture_params.bAllowDirectCapture) {
969 CUdeviceptr device_ptr;
970 NVFBC_FRAME_GRAB_INFO info;
971
972 NVFBC_TOCUDA_GRAB_FRAME_PARAMS grab {
973 NVFBC_TOCUDA_GRAB_FRAME_PARAMS_VER,
974 NVFBC_TOCUDA_GRAB_FLAGS_NOWAIT,
975 &device_ptr,
976 &info,
977 0,
978 };
979
980 // Direct Capture may fail the first few times, even if it's possible
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;
985 }
986
987 BOOST_LOG(error) << "Couldn't capture nvFramebuffer: "sv << handle.last_error();
988
989 return platf::capture_e::error;
990 }
991
992 if (info.bDirectCapture) {
993 break;
994 }
995
996 BOOST_LOG(debug) << "Direct capture failed attempt ["sv << x << ']';
997 }
998
999 if (!info.bDirectCapture) {
1000 BOOST_LOG(debug) << "Direct capture failed, trying the extra copy method"sv;
1001 // Direct capture failed
1002 capture_params.bPushModel = nv_bool(false);
1003 capture_params.bWithCursor = nv_bool(false);
1004 capture_params.bAllowDirectCapture = nv_bool(false);
1005
1006 if (handle.stop() || handle.capture(capture_params)) {
1007 return platf::capture_e::error;
1008 }
1009 }
1010 }
1011
1012 return platf::capture_e::ok;
1013 }
1014
1015 platf::capture_e snapshot(const pull_free_image_cb_t &pull_free_image_cb, std::shared_ptr<platf::img_t> &img_out, std::chrono::milliseconds timeout, bool cursor) {
1016 if (cursor != cursor_visible) {
1017 auto status = reinit(cursor);
1018 if (status != platf::capture_e::ok) {
1019 return status;
1020 }
1021 }
1022
1023 CUdeviceptr device_ptr;
1024 NVFBC_FRAME_GRAB_INFO info;
1025
1026 NVFBC_TOCUDA_GRAB_FRAME_PARAMS grab {
1027 NVFBC_TOCUDA_GRAB_FRAME_PARAMS_VER,
1028 NVFBC_TOCUDA_GRAB_FLAGS_NOWAIT,
1029 &device_ptr,
1030 &info,
1031 (std::uint32_t) timeout.count(),
1032 };
1033
1034 if (auto status = func.nvFBCToCudaGrabFrame(handle.handle, &grab)) {
1035 if (status == NVFBC_ERR_MUST_RECREATE) {
1036 return platf::capture_e::reinit;
1037 }
1038
1039 BOOST_LOG(error) << "Couldn't capture nvFramebuffer: "sv << handle.last_error();
1040 return platf::capture_e::error;
1041 }
1042
1043 if (!pull_free_image_cb(img_out)) {
1044 return platf::capture_e::interrupted;
1045 }
1046 auto img = (img_t *) img_out.get();
1047
1048 if (img->tex.copy((std::uint8_t *) device_ptr, img->height, img->row_pitch)) {
1049 return platf::capture_e::error;
1050 }
1051
1052 return platf::capture_e::ok;
1053 }
1054
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);
1057 }
1058
1059 std::shared_ptr<platf::img_t> alloc_img() override {
1060 auto img = std::make_shared<cuda::img_t>();
1061
1062 img->data = nullptr;
1063 img->width = width;
1064 img->height = height;
1065 img->pixel_pitch = 4;
1066 img->row_pitch = img->width * img->pixel_pitch;
1067
1068 auto tex_opt = tex_t::make(height, width * img->pixel_pitch);
1069 if (!tex_opt) {
1070 return nullptr;
1071 }
1072
1073 img->tex = std::move(*tex_opt);
1074
1075 return img;
1076 };
1077
1078 int dummy_img(platf::img_t *) override {
1079 return 0;
1080 }
1081
1082 std::chrono::nanoseconds delay;
1083
1084 bool cursor_visible;
1085 handle_t handle;
1086
1087 NVFBC_CREATE_CAPTURE_SESSION_PARAMS capture_params;
1088 };
1089 } // namespace nvfbc
1090} // namespace cuda
1091
1092namespace platf {
1093 std::shared_ptr<display_t> nvfbc_display(mem_type_e hwdevice_type, const std::string &display_name, const video::config_t &config) {
1094 if (hwdevice_type != mem_type_e::cuda) {
1095 BOOST_LOG(error) << "Could not initialize nvfbc display with the given hw device type"sv;
1096 return nullptr;
1097 }
1098
1099 auto display = std::make_shared<cuda::nvfbc::display_t>();
1100
1101 if (display->init(display_name, config)) {
1102 return nullptr;
1103 }
1104
1105 return display;
1106 }
1107
1108 std::vector<std::string> nvfbc_display_names() {
1109 if (cuda::init() || cuda::nvfbc::init()) {
1110 return {};
1111 }
1112
1113 std::vector<std::string> display_names;
1114
1115 auto handle = cuda::nvfbc::handle_t::make();
1116 if (!handle) {
1117 return {};
1118 }
1119
1120 auto status_params = handle->status();
1121 if (!status_params) {
1122 return {};
1123 }
1124
1125 if (!status_params->bIsCapturePossible) {
1126 BOOST_LOG(error) << "NVidia driver doesn't support NvFBC screencasting"sv;
1127 }
1128
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);
1132
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));
1141 }
1142
1143 return display_names;
1144 }
1145} // namespace platf
int set_frame(AVFrame *frame, AVBufferRef *hw_frames_ctx) override
Set the frame to be encoded.
Definition cuda.cpp:319
pixel::layout_e layout
Channel layout of the frames this device converts.
Definition cuda.cpp:308
int set_frame(AVFrame *frame, AVBufferRef *hw_frames_ctx) override
Set the frame to be encoded.
Definition cuda.cpp:223
int init(int in_width, int in_height, int offset_x, int offset_y)
Initialize the GL->CUDA encoding device.
Definition cuda.cpp:400
int convert(platf::img_t &img) override
Convert the captured image into the target CUDA frame.
Definition cuda.cpp:494
void apply_colorspace() override
Configures shader parameters for the specified colorspace.
Definition cuda.cpp:555
int set_frame(AVFrame *frame, AVBufferRef *hw_frames_ctx_buf) override
Initialize color conversion into target CUDA frame.
Definition cuda.cpp:447
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.
Definition cuda.cpp:887
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,...
Definition common.h:452
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...
Definition common.h:461
mem_type_e
Definition common.h:211
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...
Definition misc.cpp:1658
capture_e
Definition common.h:435
@ ok
Success.
Definition common.h:436
@ timeout
Timeout.
Definition common.h:438
@ reinit
Need to reinitialize.
Definition common.h:437
@ error
Error.
Definition common.h:440
@ interrupted
Capture was interrupted.
Definition common.h:439
file_t open_drm_fd_for_cuda_device(int index)
Opens the DRM device associated with the CUDA device index.
Definition cuda.cpp:349
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.
Definition cuda.cpp:612
Definitions for CUDA implementation.
layout_e
How the 32-bit little-endian words of a CPU-copied frame hold their channels.
Definition cuda_pixel.h:21
@ bgra8
DRM XRGB8888 / ARGB8888: bytes B, G, R, X.
Definition cuda_pixel.h:22
rgb_t create_blank(platf::img_t &img)
Create a black RGB texture of the specified image size.
Definition graphics.cpp:621
std::optional< nv12_t > create_target(int width, int height, AVPixelFormat format)
Create biplanar YUV textures to render into.
Definition graphics.cpp:704
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.
Definition misc.cpp:138
Miscellaneous declarations for Linux.
Declarations for utility functions.
Declarations for video.
Declarations for Wayland capture.