Hermes 0.7.0
Linux game streaming host
Loading...
Searching...
No Matches
pyrowave.cpp
Go to the documentation of this file.
1
5// standard includes
6#include <array>
7#include <cerrno>
8#include <cstring>
9#include <fcntl.h>
10#include <poll.h>
11#include <unistd.h>
12
13// lib includes
14#include <drm_fourcc.h>
15#include <gbm.h>
16#include <xf86drm.h>
17
18extern "C" {
19#include <libavutil/frame.h>
20#include <libavutil/pixfmt.h>
21}
22
23// local includes
24#include "graphics.h"
25#include "pyrowave.h"
26#include "pyrowave_fence.h"
27#include "src/config.h"
28#include "src/logging.h"
29
30using namespace std::literals;
31
32namespace pyrowave {
33 namespace {
34 // EGL_ANDROID_native_fence_sync. The glad loader Hermes ships was not
35 // generated with it, so the one entry point it adds is looked up by hand.
36 constexpr EGLenum sync_native_fence_android = 0x3144;
37 using dup_native_fence_fd_fn = EGLint (*)(EGLDisplay, EGLSync);
38
39 struct device_deleter_t {
40 void operator()(pyrowave_device_opaque *device) const {
41 pyrowave_device_destroy(device);
42 }
43 };
44
45 using device_ptr = std::unique_ptr<pyrowave_device_opaque, device_deleter_t>;
46
47 bool succeeded(pyrowave_result result, std::string_view operation) {
48 if (result == PYROWAVE_SUCCESS) {
49 return true;
50 }
51 BOOST_LOG(error) << "[PyroWave] "sv << operation << " failed with status "sv << static_cast<int>(result);
52 return false;
53 }
54
63 device_ptr create_device(int render_fd) {
64 std::uint32_t vendor = 0;
65 std::uint32_t product = 0;
66 drmDevicePtr drm_device = nullptr;
67 if (drmGetDevice2(render_fd, 0, &drm_device) == 0 && drm_device) {
68 if (drm_device->bustype == DRM_BUS_PCI && drm_device->deviceinfo.pci) {
69 vendor = drm_device->deviceinfo.pci->vendor_id;
70 product = drm_device->deviceinfo.pci->device_id;
71 }
72 drmFreeDevice(&drm_device);
73 }
74
75 pyrowave_device raw {};
76 if (!succeeded(pyrowave_create_device_by_compat(vendor, product, nullptr, nullptr, nullptr, &raw), "Vulkan device creation"sv)) {
77 return nullptr;
78 }
79 device_ptr device {raw};
80 if (!pyrowave_device_confirm_interop_support(device.get())) {
81 BOOST_LOG(error) << "[PyroWave] The Vulkan driver for "sv << util::hex(vendor).to_string_view() << ':'
82 << util::hex(product).to_string_view()
83 << " cannot import DMA-BUFs and sync files, so frames cannot stay on the GPU."sv;
84 return nullptr;
85 }
86 // Hermes encodes from another process than the one rendering. The async
87 // compute queue keeps the encode from waiting behind a busy game.
88 pyrowave_device_set_queue_type(device.get(), VK_QUEUE_COMPUTE_BIT);
89 return device;
90 }
91
93 struct plane_t {
94 plane_t() = default;
95 plane_t(const plane_t &) = delete;
96 plane_t &operator=(const plane_t &) = delete;
97
98 ~plane_t() {
99 reset();
100 }
101
102 void reset() {
103 if (image) {
104 pyrowave_image_destroy(image);
105 image = nullptr;
106 }
107 if (bo) {
108 gbm_bo_destroy(bo);
109 bo = nullptr;
110 }
111 }
112
113 gbm_bo *bo {};
114 pyrowave_image image {};
115 int width {};
116 int height {};
117 std::uint32_t fourcc {};
118 std::uint64_t modifier {DRM_FORMAT_MOD_INVALID};
119 int plane_count {};
120 };
121
127 bool allocate(gbm_device *gbm, plane_t &plane, int width, int height, std::uint32_t fourcc, bool linear) {
128 plane.reset();
129 plane.width = width;
130 plane.height = height;
131 plane.fourcc = fourcc;
132 plane.bo = gbm_bo_create(gbm, width, height, fourcc, GBM_BO_USE_RENDERING | (linear ? GBM_BO_USE_LINEAR : 0));
133 if (!plane.bo) {
134 return false;
135 }
136 plane.modifier = gbm_bo_get_modifier(plane.bo);
137 if (plane.modifier == DRM_FORMAT_MOD_INVALID && linear) {
138 plane.modifier = DRM_FORMAT_MOD_LINEAR;
139 }
140 plane.plane_count = gbm_bo_get_plane_count(plane.bo);
141 // An implicit layout cannot be described to Vulkan, and more than four
142 // memory planes cannot be described to EGL.
143 if (plane.modifier == DRM_FORMAT_MOD_INVALID || plane.plane_count < 1 || plane.plane_count > 4) {
144 plane.reset();
145 return false;
146 }
147 return true;
148 }
149
150 egl::surface_descriptor_t describe(const plane_t &plane, int fd) {
151 egl::surface_descriptor_t sd {};
152 sd.width = plane.width;
153 sd.height = plane.height;
154 sd.fourcc = plane.fourcc;
155 sd.modifier = plane.modifier;
156 std::fill_n(sd.fds, 4, -1);
157 for (int x = 0; x < plane.plane_count; ++x) {
158 sd.fds[x] = fd;
159 sd.pitches[x] = gbm_bo_get_stride_for_plane(plane.bo, x);
160 sd.offsets[x] = gbm_bo_get_offset(plane.bo, x);
161 }
162 return sd;
163 }
164
165 bool import_plane(pyrowave_device device, plane_t &plane, VkFormat format) {
166 std::array<VkSubresourceLayout, 4> layouts {};
167 for (int x = 0; x < plane.plane_count; ++x) {
168 layouts[x].offset = gbm_bo_get_offset(plane.bo, x);
169 layouts[x].rowPitch = gbm_bo_get_stride_for_plane(plane.bo, x);
170 }
171
172 VkImageDrmFormatModifierExplicitCreateInfoEXT modifier_info {VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_EXPLICIT_CREATE_INFO_EXT};
173 modifier_info.drmFormatModifier = plane.modifier;
174 modifier_info.drmFormatModifierPlaneCount = static_cast<std::uint32_t>(plane.plane_count);
175 modifier_info.pPlaneLayouts = layouts.data();
176
177 VkImageCreateInfo image_info {VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO};
178 image_info.pNext = &modifier_info;
179 image_info.imageType = VK_IMAGE_TYPE_2D;
180 image_info.format = format;
181 image_info.extent = {static_cast<std::uint32_t>(plane.width), static_cast<std::uint32_t>(plane.height), 1};
182 image_info.mipLevels = 1;
183 image_info.arrayLayers = 1;
184 image_info.samples = VK_SAMPLE_COUNT_1_BIT;
185 image_info.tiling = VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT;
186 image_info.usage = VK_IMAGE_USAGE_SAMPLED_BIT;
187 image_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
188 image_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
189
190 const int fd = gbm_bo_get_fd(plane.bo);
191 if (fd < 0) {
192 return false;
193 }
194 pyrowave_image_create_info create_info {};
195 create_info.device = device;
196 create_info.external_handle = static_cast<pyrowave_os_handle>(fd);
197 create_info.handle_type = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT;
198 create_info.image_create_info = &image_info;
199 // A successful import owns the descriptor. After a failure it is not
200 // known whether the driver got as far as taking it, so it is left open
201 // rather than risk closing a number another thread has since reused.
202 return pyrowave_image_create(&create_info, &plane.image) == PYROWAVE_SUCCESS;
203 }
204
205 struct av_frame_deleter_t {
206 void operator()(AVFrame *frame) const {
207 av_frame_free(&frame);
208 }
209 };
210 } // namespace
211
212 class egl_encode_device_t: public gpu_encode_device_t {
213 public:
214 ~egl_encode_device_t() override {
215 drop_fence();
216 drop_sync();
217 }
218
219 int init(int in_width, int in_height, file_t &&render_device, int offset_x, int offset_y, bool vram, std::uint32_t ram_fourcc) {
220 file = std::move(render_device);
221 width = in_width;
222 height = in_height;
223 this->offset_x = offset_x;
224 this->offset_y = offset_y;
225 this->vram = vram;
226 this->ram_fourcc = ram_fourcc;
227
228 if (!gbm::create_device) {
229 BOOST_LOG(warning) << "[PyroWave] libgbm is not loaded."sv;
230 return -1;
231 }
232 gbm.reset(gbm::create_device(file.el));
233 if (!gbm) {
234 BOOST_LOG(error) << "[PyroWave] Could not create a GBM device: "sv << std::strerror(errno);
235 return -1;
236 }
237 display = egl::make_display(gbm.get());
238 if (!display) {
239 return -1;
240 }
241 auto ctx_opt = egl::make_ctx(display.get());
242 if (!ctx_opt) {
243 return -1;
244 }
245 ctx = std::move(*ctx_opt);
246
247 const char *extensions = eglQueryString(display.get(), EGL_EXTENSIONS);
248 if (extensions && std::strstr(extensions, "EGL_ANDROID_native_fence_sync") && eglCreateSync && eglDestroySync) {
249 dup_native_fence_fd = reinterpret_cast<dup_native_fence_fd_fn>(eglGetProcAddress("eglDupNativeFenceFDANDROID"));
250 }
251 if (!dup_native_fence_fd) {
252 BOOST_LOG(info) << "[PyroWave] EGL cannot export fences; each frame is finished on the CPU before it is encoded."sv;
253 }
254
255 pyro = create_device(file.el);
256 if (!pyro) {
257 return -1;
258 }
259
260 // Sharing planes between OpenGL and Vulkan is what can fail on a given
261 // driver (GBM formats, modifiers, DMA-BUF import), and set_frame() is too
262 // late for a caller to choose another path. Find out now, on a tiny
263 // frame.
264 if (!import_targets(64, 64, false) && !import_targets(64, 64, true)) {
265 BOOST_LOG(warning) << "[PyroWave] This GPU cannot share planes between OpenGL and Vulkan."sv;
266 return -1;
267 }
268 return 0;
269 }
270
271 pyrowave_device device() const override {
272 return pyro.get();
273 }
274
275 int set_frame(AVFrame *frame, AVBufferRef * /* hw_frames_ctx */) override {
276 owned_frame.reset(frame);
277 this->frame = frame;
278 if (frame->width <= 0 || frame->height <= 0 || (frame->width & 1) || (frame->height & 1)) {
279 BOOST_LOG(error) << "[PyroWave] 4:2:0 needs even dimensions, not "sv << frame->width << 'x' << frame->height;
280 return -1;
281 }
282
283 bool linear = false;
284 if (!import_targets(frame->width, frame->height, false)) {
285 linear = true;
286 if (!import_targets(frame->width, frame->height, true)) {
287 BOOST_LOG(error) << "[PyroWave] Could not share a "sv << frame->width << 'x' << frame->height
288 << " target between OpenGL and Vulkan on this GPU."sv;
289 return -1;
290 }
291 }
292 BOOST_LOG(info) << "[PyroWave] Converting "sv << (vram ? "captured GPU buffers"sv : "frames uploaded from system memory"sv)
293 << " on the GPU into "sv << (linear ? "linear"sv : "tiled"sv) << ' ' << frame->width << 'x'
294 << frame->height << " planes (modifier "sv << util::hex(luma.modifier).to_string_view() << ')';
295
296 auto sws_opt = egl::sws_t::make(width, height, frame->width, frame->height, AV_PIX_FMT_NV12);
297 if (!sws_opt) {
298 return -1;
299 }
300 sws = std::move(*sws_opt);
301 return 0;
302 }
303
304 void apply_colorspace() override {
305 sws.apply_colorspace(colorspace);
306 }
307
308 int convert(platf::img_t &img) override {
309 if (!vram) {
310 // A capture into system memory: one texture upload, then the same
311 // conversion as for a DMA-BUF.
312 if (sws.load_ram(img, ram_fourcc)) {
313 return -1;
314 }
315 sws.convert(nv12->buf);
316 drop_fence();
317 fence_fd = export_fence();
318 converted = true;
319 return 0;
320 }
321
322 auto &descriptor = (egl::img_descriptor_t &) img;
323
324 if (descriptor.sequence == 0) {
325 // The blank frame encoded before the first capture arrives.
326 rgb = egl::create_blank(img);
327 } else if (descriptor.sequence > sequence) {
328 sequence = descriptor.sequence;
329 rgb = egl::rgb_t {};
330 auto rgb_opt = egl::import_source(display.get(), descriptor.sd);
331 if (!rgb_opt) {
332 return -1;
333 }
334 rgb = std::move(*rgb_opt);
335 }
336
337 sws.load_vram(descriptor, offset_x, offset_y, rgb->tex[0]);
338 sws.convert(nv12->buf);
339
340 drop_fence();
341 fence_fd = export_fence();
342 converted = true;
343 return 0;
344 }
345
346 bool planes(pyrowave_gpu_buffers &out, const pyrowave_gpu_sync_operation *&acquire, const pyrowave_gpu_sync_operation *&release) override {
347 if (!converted) {
348 return false;
349 }
350
351 drop_sync();
352 acquire_op.sync = {};
353 if (fence_fd >= 0) {
354 pyrowave_sync_object_create_info sync_info {};
355 sync_info.device = pyro.get();
356 sync_info.external_handle = static_cast<pyrowave_os_handle>(fence_fd);
357 sync_info.handle_type = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT;
358 sync_info.semaphore_type = VK_SEMAPHORE_TYPE_BINARY;
359 sync_info.import_flags = VK_SEMAPHORE_IMPORT_TEMPORARY_BIT;
360 if (pyrowave_sync_object_create(&sync_info, &sync) == PYROWAVE_SUCCESS) {
361 fence_fd = -1; // owned by the sync object now
362 acquire_op.sync.semaphore = pyrowave_sync_object_get_semaphore(sync);
363 } else {
364 // Wait here instead: slower, but the frame is still complete. The
365 // bound keeps a hung GPU from holding the encode thread forever.
366 sync = nullptr;
367 const bool ready = wait_for_conversion_fence(fence_fd, 1000ms);
368 drop_fence();
369 if (!ready) {
370 converted = false;
371 BOOST_LOG(warning) << "[PyroWave] Conversion fence timed out or failed; dropping the frame."sv;
372 return false;
373 }
374 }
375 }
376
377 out = buffers;
378 acquire = &acquire_op;
379 release = &release_op;
380 return true;
381 }
382
383 void encoded() override {
384 // The encode that waited on the semaphore has completed by now, so it
385 // can be destroyed; destroying it any earlier would be invalid Vulkan.
386 drop_sync();
387 }
388
389 private:
394 int export_fence() {
395 if (dup_native_fence_fd) {
396 const EGLAttrib attribs[] {EGL_NONE};
397 EGLSync fence = eglCreateSync(display.get(), sync_native_fence_android, attribs);
398 if (fence != EGL_NO_SYNC) {
399 // The fence only gets a file descriptor once it has been flushed.
400 gl::ctx.Flush();
401 const int fd = dup_native_fence_fd(display.get(), fence);
402 eglDestroySync(display.get(), fence);
403 if (fd >= 0) {
404 return fd;
405 }
406 }
407 }
408 gl::ctx.Finish();
409 return -1;
410 }
411
412 bool import_targets(int out_width, int out_height, bool linear) {
413 nv12 = egl::nv12_t {};
414 auto *native = reinterpret_cast<gbm_device *>(gbm.get());
415 if (!allocate(native, luma, out_width, out_height, DRM_FORMAT_R8, linear) || !allocate(native, chroma, out_width / 2, out_height / 2, DRM_FORMAT_GR88, linear)) {
416 return false;
417 }
418
419 std::array<file_t, egl::nv12_img_t::num_fds> fds;
420 fds[0] = gbm_bo_get_fd(luma.bo);
421 fds[1] = gbm_bo_get_fd(chroma.bo);
422 if (fds[0].el < 0 || fds[1].el < 0) {
423 return false;
424 }
425 const auto luma_sd = describe(luma, fds[0].el);
426 const auto chroma_sd = describe(chroma, fds[1].el);
427 auto nv12_opt = egl::import_target(display.get(), std::move(fds), luma_sd, chroma_sd);
428 if (!nv12_opt) {
429 return false;
430 }
431
432 // GR88 keeps Cb in the low byte, which Vulkan names R8G8.
433 if (!import_plane(pyro.get(), luma, VK_FORMAT_R8_UNORM) || !import_plane(pyro.get(), chroma, VK_FORMAT_R8G8_UNORM)) {
434 BOOST_LOG(info) << "[PyroWave] Vulkan could not import the "sv << (linear ? "linear" : "driver-chosen")
435 << " layout (modifier "sv << util::hex(luma.modifier).to_string_view() << ')';
436 return false;
437 }
438
439 // Cb and Cr are read from one interleaved image through swizzles.
440 if (!succeeded(pyrowave_image_get_image_view(luma.image, VK_IMAGE_ASPECT_PLANE_0_BIT, VK_IMAGE_USAGE_SAMPLED_BIT, &buffers.planes[0]), "luma view"sv) || !succeeded(pyrowave_image_get_image_view(chroma.image, VK_IMAGE_ASPECT_PLANE_1_BIT, VK_IMAGE_USAGE_SAMPLED_BIT, &buffers.planes[1]), "Cb view"sv) || !succeeded(pyrowave_image_get_image_view(chroma.image, VK_IMAGE_ASPECT_PLANE_2_BIT, VK_IMAGE_USAGE_SAMPLED_BIT, &buffers.planes[2]), "Cr view"sv)) {
441 return false;
442 }
443
444 // The planes change hands between OpenGL and Vulkan every frame.
445 references[0] = {luma.image, VK_QUEUE_FAMILY_EXTERNAL};
446 references[1] = {chroma.image, VK_QUEUE_FAMILY_EXTERNAL};
447 acquire_op = {references.data(), references.size(), {}};
448 release_op = {references.data(), references.size(), {}};
449
450 nv12 = std::move(*nv12_opt);
451 return true;
452 }
453
454 void drop_fence() {
455 if (fence_fd >= 0) {
456 ::close(fence_fd);
457 fence_fd = -1;
458 }
459 }
460
461 void drop_sync() {
462 if (sync) {
463 pyrowave_sync_object_destroy(sync);
464 sync = nullptr;
465 }
466 }
467
468 // Declaration order is destruction order in reverse: the Vulkan device
469 // outlives its images, the GBM device its buffers, and the EGL context
470 // every OpenGL object.
471 file_t file;
472 gbm::gbm_t gbm;
473 egl::display_t display;
474 egl::ctx_t ctx;
475
476 device_ptr pyro;
477 plane_t luma;
478 plane_t chroma;
479 pyrowave_gpu_buffers buffers {};
480 std::array<pyrowave_gpu_external_reference, 2> references {};
481 pyrowave_gpu_sync_operation acquire_op {};
482 pyrowave_gpu_sync_operation release_op {};
483 pyrowave_sync_object sync {};
484 int fence_fd {-1};
485 bool converted {false};
486
487 std::unique_ptr<AVFrame, av_frame_deleter_t> owned_frame;
488 egl::sws_t sws;
489 egl::nv12_t nv12;
490 egl::rgb_t rgb;
491 std::uint64_t sequence {};
492
493 dup_native_fence_fd_fn dup_native_fence_fd {};
494 bool vram {true};
495 std::uint32_t ram_fourcc {};
496 int width {};
497 int height {};
498 int offset_x {};
499 int offset_y {};
500 };
501
502 namespace {
503 file_t open_adapter() {
504 const auto *render_device = config::video.adapter_name.empty() ? "/dev/dri/renderD128" : config::video.adapter_name.c_str();
505 file_t file = ::open(render_device, O_RDWR | O_CLOEXEC);
506 if (file.el < 0) {
507 BOOST_LOG(error) << "[PyroWave] Could not open "sv << render_device << ": "sv << std::strerror(errno);
508 }
509 return file;
510 }
511 } // namespace
512
513 std::unique_ptr<gpu_encode_device_t> make_gpu_encode_device(int width, int height, file_t &&render_device, int offset_x, int offset_y) {
514 auto device = std::make_unique<egl_encode_device_t>();
515 if (device->init(width, height, std::move(render_device), offset_x, offset_y, true, 0)) {
516 return nullptr;
517 }
518 return device;
519 }
520
521 std::unique_ptr<gpu_encode_device_t> make_gpu_encode_device(int width, int height, int offset_x, int offset_y) {
522 file_t file = open_adapter();
523 if (file.el < 0) {
524 return nullptr;
525 }
526 return make_gpu_encode_device(width, height, std::move(file), offset_x, offset_y);
527 }
528
529 std::unique_ptr<platf::avcodec_encode_device_t> make_ram_encode_device(int width, int height, file_t &&render_device, std::uint32_t fourcc) {
530 if (render_device.el >= 0) {
531 auto device = std::make_unique<egl_encode_device_t>();
532 if (!device->init(width, height, std::move(render_device), 0, 0, false, fourcc)) {
533 return device;
534 }
535 }
536 BOOST_LOG(warning) << "[PyroWave] Frames will be converted on the CPU, which takes several milliseconds per frame."sv;
537 return std::make_unique<platf::avcodec_encode_device_t>();
538 }
539
540 std::unique_ptr<platf::avcodec_encode_device_t> make_ram_encode_device(int width, int height, std::uint32_t fourcc) {
541 return make_ram_encode_device(width, height, open_adapter(), fourcc);
542 }
543} // namespace pyrowave
Declarations for the configuration of Sunshine.
@ drm_device
–drm-device, the shorter downstream patch reported in Hermes#57.
rgb_t create_blank(platf::img_t &img)
Create a black RGB texture of the specified image size.
Definition graphics.cpp:621
Declarations for graphics related functions.
Declarations for logging related functions.
std::string_view describe(virtual_display_source_e source)
Definition process.cpp:126
GPU conversion for the experimental PyroWave codec.