Hermes 0.7.0
Linux game streaming host
Loading...
Searching...
No Matches
graphics.cpp
Go to the documentation of this file.
1
5// standard includes
6#include <fcntl.h>
7
8// local includes
9#include "graphics.h"
10#include "src/file_handler.h"
11#include "src/logging.h"
12#include "src/video.h"
13
14extern "C" {
15#include <libavutil/pixdesc.h>
16}
17
18// I want to have as little build dependencies as possible
19// There aren't that many DRM_FORMAT I need to use, so define them here
20//
21// They aren't likely to change any time soon.
22#define fourcc_code(a, b, c, d) ((std::uint32_t) (a) | ((std::uint32_t) (b) << 8) | ((std::uint32_t) (c) << 16) | ((std::uint32_t) (d) << 24))
23#define fourcc_mod_code(vendor, val) ((((uint64_t) vendor) << 56) | ((val) & 0x00ffffffffffffffULL))
24#define DRM_FORMAT_MOD_INVALID fourcc_mod_code(0, ((1ULL << 56) - 1))
25
26#if !defined(HERMES_SHADERS_DIR) // for testing this needs to be defined in cmake as we don't do an install
27 #define HERMES_SHADERS_DIR HERMES_ASSETS_DIR "/shaders/opengl"
28#endif
29
30using namespace std::literals;
31
32namespace gl {
33 GladGLContext ctx;
34
35 void drain_errors(const std::string_view &prefix) {
36 GLenum err;
37 while ((err = ctx.GetError()) != GL_NO_ERROR) {
38 BOOST_LOG(error) << "GL: "sv << prefix << ": ["sv << util::hex(err).to_string_view() << ']';
39 }
40 }
41
42 tex_t::~tex_t() {
43 if (size() != 0) {
44 ctx.DeleteTextures(size(), begin());
45 }
46 }
47
48 tex_t tex_t::make(std::size_t count) {
49 tex_t textures {count};
50
51 ctx.GenTextures(textures.size(), textures.begin());
52
53 float color[] = {0.0f, 0.0f, 0.0f, 1.0f};
54
55 for (auto tex : textures) {
56 gl::ctx.BindTexture(GL_TEXTURE_2D, tex);
57 gl::ctx.TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); // x
58 gl::ctx.TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); // y
59 gl::ctx.TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
60 gl::ctx.TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
61 gl::ctx.TexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, color);
62 }
63
64 return textures;
65 }
66
67 frame_buf_t::~frame_buf_t() {
68 if (begin()) {
69 ctx.DeleteFramebuffers(size(), begin());
70 }
71 }
72
73 frame_buf_t frame_buf_t::make(std::size_t count) {
74 frame_buf_t frame_buf {count};
75
76 ctx.GenFramebuffers(frame_buf.size(), frame_buf.begin());
77
78 return frame_buf;
79 }
80
81 void frame_buf_t::copy(int id, int texture, int offset_x, int offset_y, int width, int height) {
82 gl::ctx.BindFramebuffer(GL_FRAMEBUFFER, (*this)[id]);
83 gl::ctx.ReadBuffer(GL_COLOR_ATTACHMENT0 + id);
84 gl::ctx.BindTexture(GL_TEXTURE_2D, texture);
85 gl::ctx.CopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, offset_x, offset_y, width, height);
86 }
87
88 std::string shader_t::err_str() {
89 int length;
90 ctx.GetShaderiv(handle(), GL_INFO_LOG_LENGTH, &length);
91
92 std::string string;
93 string.resize(length);
94
95 ctx.GetShaderInfoLog(handle(), length, &length, string.data());
96
97 string.resize(length - 1);
98
99 return string;
100 }
101
102 util::Either<shader_t, std::string> shader_t::compile(const std::string_view &source, GLenum type) {
103 shader_t shader;
104
105 auto data = source.data();
106 GLint length = source.length();
107
108 shader._shader.el = ctx.CreateShader(type);
109 ctx.ShaderSource(shader.handle(), 1, &data, &length);
110 ctx.CompileShader(shader.handle());
111
112 int status = 0;
113 ctx.GetShaderiv(shader.handle(), GL_COMPILE_STATUS, &status);
114
115 if (!status) {
116 return shader.err_str();
117 }
118
119 return shader;
120 }
121
122 GLuint shader_t::handle() const {
123 return _shader.el;
124 }
125
126 buffer_t buffer_t::make(util::buffer_t<GLint> &&offsets, const char *block, const std::string_view &data) {
127 buffer_t buffer;
128 buffer._block = block;
129 buffer._size = data.size();
130 buffer._offsets = std::move(offsets);
131
132 ctx.GenBuffers(1, &buffer._buffer.el);
133 ctx.BindBuffer(GL_UNIFORM_BUFFER, buffer.handle());
134 ctx.BufferData(GL_UNIFORM_BUFFER, data.size(), (const std::uint8_t *) data.data(), GL_DYNAMIC_DRAW);
135
136 return buffer;
137 }
138
139 GLuint buffer_t::handle() const {
140 return _buffer.el;
141 }
142
143 const char *buffer_t::block() const {
144 return _block;
145 }
146
147 void buffer_t::update(const std::string_view &view, std::size_t offset) {
148 ctx.BindBuffer(GL_UNIFORM_BUFFER, handle());
149 ctx.BufferSubData(GL_UNIFORM_BUFFER, offset, view.size(), (const void *) view.data());
150 }
151
152 void buffer_t::update(std::string_view *members, std::size_t count, std::size_t offset) {
153 util::buffer_t<std::uint8_t> buffer {_size};
154
155 for (int x = 0; x < count; ++x) {
156 auto val = members[x];
157
158 std::copy_n((const std::uint8_t *) val.data(), val.size(), &buffer[_offsets[x]]);
159 }
160
161 update(util::view(buffer.begin(), buffer.end()), offset);
162 }
163
164 std::string program_t::err_str() {
165 int length;
166 ctx.GetProgramiv(handle(), GL_INFO_LOG_LENGTH, &length);
167
168 std::string string;
169 string.resize(length);
170
171 ctx.GetShaderInfoLog(handle(), length, &length, string.data());
172
173 string.resize(length - 1);
174
175 return string;
176 }
177
178 util::Either<program_t, std::string> program_t::link(const shader_t &vert, const shader_t &frag) {
179 program_t program;
180
181 program._program.el = ctx.CreateProgram();
182
183 ctx.AttachShader(program.handle(), vert.handle());
184 ctx.AttachShader(program.handle(), frag.handle());
185
186 // p_handle stores a copy of the program handle, since program will be moved before
187 // the fail guard function is called.
188 auto fg = util::fail_guard([p_handle = program.handle(), &vert, &frag]() {
189 ctx.DetachShader(p_handle, vert.handle());
190 ctx.DetachShader(p_handle, frag.handle());
191 });
192
193 ctx.LinkProgram(program.handle());
194
195 int status = 0;
196 ctx.GetProgramiv(program.handle(), GL_LINK_STATUS, &status);
197
198 if (!status) {
199 return program.err_str();
200 }
201
202 return program;
203 }
204
205 void program_t::bind(const buffer_t &buffer) {
206 ctx.UseProgram(handle());
207 auto i = ctx.GetUniformBlockIndex(handle(), buffer.block());
208
209 ctx.BindBufferBase(GL_UNIFORM_BUFFER, i, buffer.handle());
210 }
211
212 std::optional<buffer_t> program_t::uniform(const char *block, std::pair<const char *, std::string_view> *members, std::size_t count) {
213 auto i = ctx.GetUniformBlockIndex(handle(), block);
214 if (i == GL_INVALID_INDEX) {
215 BOOST_LOG(error) << "Couldn't find index of ["sv << block << ']';
216 return std::nullopt;
217 }
218
219 int size;
220 ctx.GetActiveUniformBlockiv(handle(), i, GL_UNIFORM_BLOCK_DATA_SIZE, &size);
221
222 bool error_flag = false;
223
224 util::buffer_t<GLint> offsets {count};
225 auto indices = (std::uint32_t *) alloca(count * sizeof(std::uint32_t));
226 auto names = (const char **) alloca(count * sizeof(const char *));
227 auto names_p = names;
228
229 std::for_each_n(members, count, [names_p](auto &member) mutable {
230 *names_p++ = std::get<0>(member);
231 });
232
233 std::fill_n(indices, count, GL_INVALID_INDEX);
234 ctx.GetUniformIndices(handle(), count, names, indices);
235
236 for (int x = 0; x < count; ++x) {
237 if (indices[x] == GL_INVALID_INDEX) {
238 error_flag = true;
239
240 BOOST_LOG(error) << "Couldn't find ["sv << block << '.' << members[x].first << ']';
241 }
242 }
243
244 if (error_flag) {
245 return std::nullopt;
246 }
247
248 ctx.GetActiveUniformsiv(handle(), count, indices, GL_UNIFORM_OFFSET, offsets.begin());
249 util::buffer_t<std::uint8_t> buffer {(std::size_t) size};
250
251 for (int x = 0; x < count; ++x) {
252 auto val = std::get<1>(members[x]);
253
254 std::copy_n((const std::uint8_t *) val.data(), val.size(), &buffer[offsets[x]]);
255 }
256
257 return buffer_t::make(std::move(offsets), block, std::string_view {(char *) buffer.begin(), buffer.size()});
258 }
259
260 GLuint program_t::handle() const {
261 return _program.el;
262 }
263
264} // namespace gl
265
266namespace gbm {
267 device_destroy_fn device_destroy;
268 create_device_fn create_device;
269
270 int init() {
271 static void *handle {nullptr};
272 static bool funcs_loaded = false;
273
274 if (funcs_loaded) {
275 return 0;
276 }
277
278 if (!handle) {
279 handle = dyn::handle({"libgbm.so.1", "libgbm.so"});
280 if (!handle) {
281 return -1;
282 }
283 }
284
285 std::vector<std::tuple<GLADapiproc *, const char *>> funcs {
286 {(GLADapiproc *) &device_destroy, "gbm_device_destroy"},
287 {(GLADapiproc *) &create_device, "gbm_create_device"},
288 };
289
290 if (dyn::load(handle, funcs)) {
291 return -1;
292 }
293
294 funcs_loaded = true;
295 return 0;
296 }
297} // namespace gbm
298
299namespace egl {
300 constexpr auto EGL_LINUX_DMA_BUF_EXT = 0x3270;
301 constexpr auto EGL_LINUX_DRM_FOURCC_EXT = 0x3271;
302 constexpr auto EGL_DMA_BUF_PLANE0_FD_EXT = 0x3272;
303 constexpr auto EGL_DMA_BUF_PLANE0_OFFSET_EXT = 0x3273;
304 constexpr auto EGL_DMA_BUF_PLANE0_PITCH_EXT = 0x3274;
305 constexpr auto EGL_DMA_BUF_PLANE1_FD_EXT = 0x3275;
306 constexpr auto EGL_DMA_BUF_PLANE1_OFFSET_EXT = 0x3276;
307 constexpr auto EGL_DMA_BUF_PLANE1_PITCH_EXT = 0x3277;
308 constexpr auto EGL_DMA_BUF_PLANE2_FD_EXT = 0x3278;
309 constexpr auto EGL_DMA_BUF_PLANE2_OFFSET_EXT = 0x3279;
310 constexpr auto EGL_DMA_BUF_PLANE2_PITCH_EXT = 0x327A;
311 constexpr auto EGL_DMA_BUF_PLANE3_FD_EXT = 0x3440;
312 constexpr auto EGL_DMA_BUF_PLANE3_OFFSET_EXT = 0x3441;
313 constexpr auto EGL_DMA_BUF_PLANE3_PITCH_EXT = 0x3442;
314 constexpr auto EGL_DMA_BUF_PLANE0_MODIFIER_LO_EXT = 0x3443;
315 constexpr auto EGL_DMA_BUF_PLANE0_MODIFIER_HI_EXT = 0x3444;
316 constexpr auto EGL_DMA_BUF_PLANE1_MODIFIER_LO_EXT = 0x3445;
317 constexpr auto EGL_DMA_BUF_PLANE1_MODIFIER_HI_EXT = 0x3446;
318 constexpr auto EGL_DMA_BUF_PLANE2_MODIFIER_LO_EXT = 0x3447;
319 constexpr auto EGL_DMA_BUF_PLANE2_MODIFIER_HI_EXT = 0x3448;
320 constexpr auto EGL_DMA_BUF_PLANE3_MODIFIER_LO_EXT = 0x3449;
321 constexpr auto EGL_DMA_BUF_PLANE3_MODIFIER_HI_EXT = 0x344A;
322
323 bool fail() {
324 return eglGetError() != EGL_SUCCESS;
325 }
326
330 display_t make_display(std::variant<gbm::gbm_t::pointer, wl_display *, _XDisplay *> native_display) {
331 constexpr auto EGL_PLATFORM_GBM_MESA = 0x31D7;
332 constexpr auto EGL_PLATFORM_WAYLAND_KHR = 0x31D8;
333 constexpr auto EGL_PLATFORM_X11_KHR = 0x31D5;
334
335 int egl_platform;
336 void *native_display_p;
337
338 switch (native_display.index()) {
339 case 0:
340 egl_platform = EGL_PLATFORM_GBM_MESA;
341 native_display_p = std::get<0>(native_display);
342 break;
343 case 1:
344 egl_platform = EGL_PLATFORM_WAYLAND_KHR;
345 native_display_p = std::get<1>(native_display);
346 break;
347 case 2:
348 egl_platform = EGL_PLATFORM_X11_KHR;
349 native_display_p = std::get<2>(native_display);
350 break;
351 default:
352 BOOST_LOG(error) << "egl::make_display(): Index ["sv << native_display.index() << "] not implemented"sv;
353 return nullptr;
354 }
355
356 // Platform init loads EGL after its capture-source checks, but Hermes can
357 // reach this through the virtual-display bootstrap even when those checks
358 // failed (e.g. KMS capture without CAP_SYS_ADMIN). Load lazily instead of
359 // calling a NULL glad pointer.
360 if (!eglGetPlatformDisplay) {
361 if (!gladLoaderLoadEGL(EGL_NO_DISPLAY) || !eglGetPlatformDisplay) {
362 BOOST_LOG(error) << "Couldn't load EGL library"sv;
363 return nullptr;
364 }
365 }
366
367 // native_display.left() equals native_display.right()
368 display_t display = eglGetPlatformDisplay(egl_platform, native_display_p, nullptr);
369
370 if (fail()) {
371 BOOST_LOG(error) << "Couldn't open EGL display: ["sv << util::hex(eglGetError()).to_string_view() << ']';
372 return nullptr;
373 }
374
375 int major, minor;
376 if (!eglInitialize(display.get(), &major, &minor)) {
377 BOOST_LOG(error) << "Couldn't initialize EGL display: ["sv << util::hex(eglGetError()).to_string_view() << ']';
378 return nullptr;
379 }
380
381 const char *extension_st = eglQueryString(display.get(), EGL_EXTENSIONS);
382 const char *version = eglQueryString(display.get(), EGL_VERSION);
383 const char *vendor = eglQueryString(display.get(), EGL_VENDOR);
384 const char *apis = eglQueryString(display.get(), EGL_CLIENT_APIS);
385
386 BOOST_LOG(debug) << "EGL: ["sv << vendor << "]: version ["sv << version << ']';
387 BOOST_LOG(debug) << "API's supported: ["sv << apis << ']';
388
389 const char *extensions[] {
390 "EGL_KHR_create_context",
391 "EGL_KHR_surfaceless_context",
392 "EGL_EXT_image_dma_buf_import",
393 "EGL_EXT_image_dma_buf_import_modifiers",
394 };
395
396 for (auto ext : extensions) {
397 if (!std::strstr(extension_st, ext)) {
398 BOOST_LOG(error) << "Missing extension: ["sv << ext << ']';
399 return nullptr;
400 }
401 }
402
403 return display;
404 }
405
406 std::optional<ctx_t> make_ctx(display_t::pointer display) {
407 constexpr int conf_attr[] {
408 EGL_RENDERABLE_TYPE,
409 EGL_OPENGL_BIT,
410 EGL_NONE
411 };
412
413 int count;
414 EGLConfig conf;
415 if (!eglChooseConfig(display, conf_attr, &conf, 1, &count)) {
416 BOOST_LOG(error) << "Couldn't set config attributes: ["sv << util::hex(eglGetError()).to_string_view() << ']';
417 return std::nullopt;
418 }
419
420 if (!eglBindAPI(EGL_OPENGL_API)) {
421 BOOST_LOG(error) << "Couldn't bind API: ["sv << util::hex(eglGetError()).to_string_view() << ']';
422 return std::nullopt;
423 }
424
425 constexpr int attr[] {
426 EGL_CONTEXT_CLIENT_VERSION,
427 3,
428 EGL_NONE
429 };
430
431 ctx_t ctx {display, eglCreateContext(display, conf, EGL_NO_CONTEXT, attr)};
432 if (fail()) {
433 BOOST_LOG(error) << "Couldn't create EGL context: ["sv << util::hex(eglGetError()).to_string_view() << ']';
434 return std::nullopt;
435 }
436
437 TUPLE_EL_REF(ctx_p, 1, ctx.el);
438 if (!eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, ctx_p)) {
439 BOOST_LOG(error) << "Couldn't make current display"sv;
440 return std::nullopt;
441 }
442
443 if (!gladLoadGLContext(&gl::ctx, eglGetProcAddress)) {
444 BOOST_LOG(error) << "Couldn't load OpenGL library"sv;
445 return std::nullopt;
446 }
447
448 BOOST_LOG(debug) << "GL: vendor: "sv << gl::ctx.GetString(GL_VENDOR);
449 BOOST_LOG(debug) << "GL: renderer: "sv << gl::ctx.GetString(GL_RENDERER);
450 BOOST_LOG(debug) << "GL: version: "sv << gl::ctx.GetString(GL_VERSION);
451 BOOST_LOG(debug) << "GL: shader: "sv << gl::ctx.GetString(GL_SHADING_LANGUAGE_VERSION);
452
453 gl::ctx.PixelStorei(GL_UNPACK_ALIGNMENT, 1);
454
455 return ctx;
456 }
457
459 EGLAttrib fd;
460 EGLAttrib offset;
461 EGLAttrib pitch;
462 EGLAttrib lo;
463 EGLAttrib hi;
464 };
465
466 inline plane_attr_t get_plane(std::uint32_t plane_indice) {
467 switch (plane_indice) {
468 case 0:
469 return {
470 EGL_DMA_BUF_PLANE0_FD_EXT,
471 EGL_DMA_BUF_PLANE0_OFFSET_EXT,
472 EGL_DMA_BUF_PLANE0_PITCH_EXT,
473 EGL_DMA_BUF_PLANE0_MODIFIER_LO_EXT,
474 EGL_DMA_BUF_PLANE0_MODIFIER_HI_EXT,
475 };
476 case 1:
477 return {
478 EGL_DMA_BUF_PLANE1_FD_EXT,
479 EGL_DMA_BUF_PLANE1_OFFSET_EXT,
480 EGL_DMA_BUF_PLANE1_PITCH_EXT,
481 EGL_DMA_BUF_PLANE1_MODIFIER_LO_EXT,
482 EGL_DMA_BUF_PLANE1_MODIFIER_HI_EXT,
483 };
484 case 2:
485 return {
486 EGL_DMA_BUF_PLANE2_FD_EXT,
487 EGL_DMA_BUF_PLANE2_OFFSET_EXT,
488 EGL_DMA_BUF_PLANE2_PITCH_EXT,
489 EGL_DMA_BUF_PLANE2_MODIFIER_LO_EXT,
490 EGL_DMA_BUF_PLANE2_MODIFIER_HI_EXT,
491 };
492 case 3:
493 return {
494 EGL_DMA_BUF_PLANE3_FD_EXT,
495 EGL_DMA_BUF_PLANE3_OFFSET_EXT,
496 EGL_DMA_BUF_PLANE3_PITCH_EXT,
497 EGL_DMA_BUF_PLANE3_MODIFIER_LO_EXT,
498 EGL_DMA_BUF_PLANE3_MODIFIER_HI_EXT,
499 };
500 }
501
502 // Avoid warning
503 return {};
504 }
505
511 std::vector<EGLAttrib> surface_descriptor_to_egl_attribs(const surface_descriptor_t &surface) {
512 std::vector<EGLAttrib> attribs;
513
514 attribs.emplace_back(EGL_WIDTH);
515 attribs.emplace_back(surface.width);
516 attribs.emplace_back(EGL_HEIGHT);
517 attribs.emplace_back(surface.height);
518 attribs.emplace_back(EGL_LINUX_DRM_FOURCC_EXT);
519 attribs.emplace_back(surface.fourcc);
520
521 for (auto x = 0; x < 4; ++x) {
522 auto fd = surface.fds[x];
523 if (fd < 0) {
524 continue;
525 }
526
527 auto plane_attr = get_plane(x);
528
529 attribs.emplace_back(plane_attr.fd);
530 attribs.emplace_back(fd);
531 attribs.emplace_back(plane_attr.offset);
532 attribs.emplace_back(surface.offsets[x]);
533 attribs.emplace_back(plane_attr.pitch);
534 attribs.emplace_back(surface.pitches[x]);
535
536 // No need to check for EGL_EXT_image_dma_buf_import_modifiers here:
537 // make_display() refuses to return a display without it, and every
538 // import_source() caller gets its display from there. The standalone
539 // hermes-egl-import-check tool does guard this, because it builds its
540 // own display and cannot make the same assumption - the difference is
541 // deliberate, not an oversight here.
542 if (surface.modifier != DRM_FORMAT_MOD_INVALID) {
543 attribs.emplace_back(plane_attr.lo);
544 attribs.emplace_back(surface.modifier & 0xFFFFFFFF);
545 attribs.emplace_back(plane_attr.hi);
546 attribs.emplace_back(surface.modifier >> 32);
547 }
548 }
549
550 attribs.emplace_back(EGL_NONE);
551 return attribs;
552 }
553
562 bool bind_egl_image_texture_2d(EGLImage image) {
563 // Drain stale errors so the check below sees only this bind.
564 while (gl::ctx.GetError() != GL_NO_ERROR) {}
565
566 gl::ctx.EGLImageTargetTexture2DOES(GL_TEXTURE_2D, image);
567 if (gl::ctx.GetError() == GL_NO_ERROR) {
568 return true;
569 }
570
571 using tex_storage_fn = void(GLAPIENTRY *)(GLenum, void *, const GLint *);
572 static auto tex_storage = (tex_storage_fn) eglGetProcAddress("glEGLImageTargetTexStorageEXT");
573 if (!tex_storage) {
574 BOOST_LOG(error) << "EGLImage bind failed and glEGLImageTargetTexStorageEXT is unavailable"sv;
575 return false;
576 }
577
578 tex_storage(GL_TEXTURE_2D, image, nullptr);
579 if (gl::ctx.GetError() != GL_NO_ERROR) {
580 BOOST_LOG(error) << "EGLImage bind failed through both OES and TexStorageEXT paths"sv;
581 return false;
582 }
583
584 BOOST_LOG(debug) << "EGLImage bound via glEGLImageTargetTexStorageEXT fallback"sv;
585 return true;
586 }
587
588 std::optional<rgb_t> import_source(display_t::pointer egl_display, const surface_descriptor_t &xrgb) {
589 auto attribs = surface_descriptor_to_egl_attribs(xrgb);
590
591 rgb_t rgb {
592 egl_display,
593 eglCreateImage(egl_display, EGL_NO_CONTEXT, EGL_LINUX_DMA_BUF_EXT, nullptr, attribs.data()),
594 gl::tex_t::make(1)
595 };
596
597 if (!rgb->xrgb8) {
598 BOOST_LOG(error) << "Couldn't import RGB Image: "sv << util::hex(eglGetError()).to_string_view();
599
600 return std::nullopt;
601 }
602
603 gl::ctx.BindTexture(GL_TEXTURE_2D, rgb->tex[0]);
604 if (!bind_egl_image_texture_2d(rgb->xrgb8)) {
605 gl::ctx.BindTexture(GL_TEXTURE_2D, 0);
606 return std::nullopt;
607 }
608
609 gl::ctx.BindTexture(GL_TEXTURE_2D, 0);
610
611 gl_drain_errors;
612
613 return rgb;
614 }
615
622 rgb_t rgb {
623 EGL_NO_DISPLAY,
624 EGL_NO_IMAGE,
625 gl::tex_t::make(1)
626 };
627
628 gl::ctx.BindTexture(GL_TEXTURE_2D, rgb->tex[0]);
629 gl::ctx.TexStorage2D(GL_TEXTURE_2D, 1, GL_RGBA8, img.width, img.height);
630 gl::ctx.BindTexture(GL_TEXTURE_2D, 0);
631
632 auto framebuf = gl::frame_buf_t::make(1);
633 framebuf.bind(&rgb->tex[0], &rgb->tex[0] + 1);
634
635 GLenum attachment = GL_COLOR_ATTACHMENT0;
636 gl::ctx.DrawBuffers(1, &attachment);
637 const GLuint rgb_black[] = {0, 0, 0, 0};
638 gl::ctx.ClearBufferuiv(GL_COLOR, 0, rgb_black);
639
640 gl_drain_errors;
641
642 return rgb;
643 }
644
645 std::optional<nv12_t> import_target(display_t::pointer egl_display, std::array<file_t, nv12_img_t::num_fds> &&fds, const surface_descriptor_t &y, const surface_descriptor_t &uv) {
646 auto y_attribs = surface_descriptor_to_egl_attribs(y);
647 auto uv_attribs = surface_descriptor_to_egl_attribs(uv);
648
649 nv12_t nv12 {
650 egl_display,
651 eglCreateImage(egl_display, EGL_NO_CONTEXT, EGL_LINUX_DMA_BUF_EXT, nullptr, y_attribs.data()),
652 eglCreateImage(egl_display, EGL_NO_CONTEXT, EGL_LINUX_DMA_BUF_EXT, nullptr, uv_attribs.data()),
653 gl::tex_t::make(2),
654 gl::frame_buf_t::make(2),
655 std::move(fds)
656 };
657
658 if (!nv12->r8 || !nv12->bg88) {
659 BOOST_LOG(error) << "Couldn't import YUV target: "sv << util::hex(eglGetError()).to_string_view();
660
661 return std::nullopt;
662 }
663
664 gl::ctx.BindTexture(GL_TEXTURE_2D, nv12->tex[0]);
666 return std::nullopt;
667 }
668
669 gl::ctx.BindTexture(GL_TEXTURE_2D, nv12->tex[1]);
670 if (!bind_egl_image_texture_2d(nv12->bg88)) {
671 return std::nullopt;
672 }
673
674 nv12->buf.bind(std::begin(nv12->tex), std::end(nv12->tex));
675
676 GLenum attachments[] {
677 GL_COLOR_ATTACHMENT0,
678 GL_COLOR_ATTACHMENT1
679 };
680
681 for (int x = 0; x < sizeof(attachments) / sizeof(decltype(attachments[0])); ++x) {
682 gl::ctx.BindFramebuffer(GL_FRAMEBUFFER, nv12->buf[x]);
683 gl::ctx.DrawBuffers(1, &attachments[x]);
684
685 const float y_black[] = {0.0f, 0.0f, 0.0f, 0.0f};
686 const float uv_black[] = {0.5f, 0.5f, 0.5f, 0.5f};
687 gl::ctx.ClearBufferfv(GL_COLOR, 0, x == 0 ? y_black : uv_black);
688 }
689
690 gl::ctx.BindFramebuffer(GL_FRAMEBUFFER, 0);
691
692 gl_drain_errors;
693
694 return nv12;
695 }
696
704 std::optional<nv12_t> create_target(int width, int height, AVPixelFormat format) {
705 nv12_t nv12 {
706 EGL_NO_DISPLAY,
707 EGL_NO_IMAGE,
708 EGL_NO_IMAGE,
709 gl::tex_t::make(2),
710 gl::frame_buf_t::make(2),
711 };
712
713 GLint y_format;
714 GLint uv_format;
715
716 // Determine the size of each plane element
717 auto fmt_desc = av_pix_fmt_desc_get(format);
718 if (fmt_desc->comp[0].depth <= 8) {
719 y_format = GL_R8;
720 uv_format = GL_RG8;
721 } else if (fmt_desc->comp[0].depth <= 16) {
722 y_format = GL_R16;
723 uv_format = GL_RG16;
724 } else {
725 BOOST_LOG(error) << "Unsupported target pixel format: "sv << format;
726 return std::nullopt;
727 }
728
729 gl::ctx.BindTexture(GL_TEXTURE_2D, nv12->tex[0]);
730 gl::ctx.TexStorage2D(GL_TEXTURE_2D, 1, y_format, width, height);
731
732 gl::ctx.BindTexture(GL_TEXTURE_2D, nv12->tex[1]);
733 gl::ctx.TexStorage2D(GL_TEXTURE_2D, 1, uv_format, width >> fmt_desc->log2_chroma_w, height >> fmt_desc->log2_chroma_h);
734
735 nv12->buf.bind(std::begin(nv12->tex), std::end(nv12->tex));
736
737 GLenum attachments[] {
738 GL_COLOR_ATTACHMENT0,
739 GL_COLOR_ATTACHMENT1
740 };
741
742 for (int x = 0; x < sizeof(attachments) / sizeof(decltype(attachments[0])); ++x) {
743 gl::ctx.BindFramebuffer(GL_FRAMEBUFFER, nv12->buf[x]);
744 gl::ctx.DrawBuffers(1, &attachments[x]);
745
746 const float y_black[] = {0.0f, 0.0f, 0.0f, 0.0f};
747 const float uv_black[] = {0.5f, 0.5f, 0.5f, 0.5f};
748 gl::ctx.ClearBufferfv(GL_COLOR, 0, x == 0 ? y_black : uv_black);
749 }
750
751 gl::ctx.BindFramebuffer(GL_FRAMEBUFFER, 0);
752
753 gl_drain_errors;
754
755 return nv12;
756 }
757
758 // The shaders round in code-value space before packing into UNORM textures.
759 // P010 stores each 10-bit code in bits 15:6, not across all 16 bits.
760 static video::color_t gl_color_matrix(const video::sunshine_colorspace_t &colorspace) {
761 auto matrix = *video::new_color_vectors_from_colorspace(colorspace);
762 const float scale = colorspace.bit_depth == 10 ? 64.0f / 65535.0f : 1.0f / 255.0f;
763 const float maximum = colorspace.bit_depth == 10 ? 1023.0f : 255.0f;
764 matrix.range_y[0] = matrix.range_uv[0] = scale;
765 matrix.range_y[1] = matrix.range_uv[1] = maximum;
766 return matrix;
767 }
768
769 void sws_t::apply_colorspace(const video::sunshine_colorspace_t &colorspace) {
770 auto matrix = gl_color_matrix(colorspace);
771 auto color_p = &matrix;
772 black_y = (colorspace.full_range ? 0.0f : (colorspace.bit_depth == 10 ? 64.0f : 16.0f)) * matrix.range_y[0];
773 black_uv = (colorspace.bit_depth == 10 ? 512.0f : 128.0f) * matrix.range_uv[0];
774
775 std::string_view members[] {
776 util::view(color_p->color_vec_y),
777 util::view(color_p->color_vec_u),
778 util::view(color_p->color_vec_v),
779 util::view(color_p->range_y),
780 util::view(color_p->range_uv),
781 };
782
783 color_matrix.update(members, sizeof(members) / sizeof(decltype(members[0])));
784
785 program[0].bind(color_matrix);
786 program[1].bind(color_matrix);
787 }
788
789 std::optional<sws_t> sws_t::make(int in_width, int in_height, int out_width, int out_height, gl::tex_t &&tex) {
790 sws_t sws;
791
792 sws.serial = std::numeric_limits<std::uint64_t>::max();
793
794 // Ensure aspect ratio is maintained
795 auto scalar = std::fminf(out_width / (float) in_width, out_height / (float) in_height);
796 auto out_width_f = in_width * scalar;
797 auto out_height_f = in_height * scalar;
798
799 // result is always positive
800 auto offsetX_f = (out_width - out_width_f) / 2;
801 auto offsetY_f = (out_height - out_height_f) / 2;
802
803 sws.out_width = out_width_f;
804 sws.out_height = out_height_f;
805
806 sws.in_width = in_width;
807 sws.in_height = in_height;
808
809 sws.offsetX = offsetX_f;
810 sws.offsetY = offsetY_f;
811
812 auto width_i = 1.0f / sws.out_width;
813
814 {
815 const char *sources[] {
816 HERMES_SHADERS_DIR "/ConvertUV.frag",
817 HERMES_SHADERS_DIR "/ConvertUV.vert",
818 HERMES_SHADERS_DIR "/ConvertY.frag",
819 HERMES_SHADERS_DIR "/Scene.vert",
820 HERMES_SHADERS_DIR "/Scene.frag",
821 };
822
823 GLenum shader_type[2] {
824 GL_FRAGMENT_SHADER,
825 GL_VERTEX_SHADER,
826 };
827
828 constexpr auto count = sizeof(sources) / sizeof(const char *);
829
830 util::Either<gl::shader_t, std::string> compiled_sources[count];
831
832 bool error_flag = false;
833 for (int x = 0; x < count; ++x) {
834 auto &compiled_source = compiled_sources[x];
835
836 compiled_source = gl::shader_t::compile(file_handler::read_file(sources[x]), shader_type[x % 2]);
837 gl_drain_errors;
838
839 if (compiled_source.has_right()) {
840 BOOST_LOG(error) << sources[x] << ": "sv << compiled_source.right();
841 error_flag = true;
842 }
843 }
844
845 if (error_flag) {
846 return std::nullopt;
847 }
848
849 auto program = gl::program_t::link(compiled_sources[3].left(), compiled_sources[4].left());
850 if (program.has_right()) {
851 BOOST_LOG(error) << "GL linker: "sv << program.right();
852 return std::nullopt;
853 }
854
855 // Cursor - shader
856 sws.program[2] = std::move(program.left());
857
858 program = gl::program_t::link(compiled_sources[1].left(), compiled_sources[0].left());
859 if (program.has_right()) {
860 BOOST_LOG(error) << "GL linker: "sv << program.right();
861 return std::nullopt;
862 }
863
864 // UV - shader
865 sws.program[1] = std::move(program.left());
866
867 program = gl::program_t::link(compiled_sources[3].left(), compiled_sources[2].left());
868 if (program.has_right()) {
869 BOOST_LOG(error) << "GL linker: "sv << program.right();
870 return std::nullopt;
871 }
872
873 // Y - shader
874 sws.program[0] = std::move(program.left());
875 }
876
877 auto loc_width_i = gl::ctx.GetUniformLocation(sws.program[1].handle(), "width_i");
878 if (loc_width_i < 0) {
879 BOOST_LOG(error) << "Couldn't find uniform [width_i]"sv;
880 return std::nullopt;
881 }
882
883 gl::ctx.UseProgram(sws.program[1].handle());
884 gl::ctx.Uniform1fv(loc_width_i, 1, &width_i);
885
886 auto matrix = gl_color_matrix({video::colorspace_e::rec601, false, 8});
887 auto color_p = &matrix;
888 std::pair<const char *, std::string_view> members[] {
889 std::make_pair("color_vec_y", util::view(color_p->color_vec_y)),
890 std::make_pair("color_vec_u", util::view(color_p->color_vec_u)),
891 std::make_pair("color_vec_v", util::view(color_p->color_vec_v)),
892 std::make_pair("range_y", util::view(color_p->range_y)),
893 std::make_pair("range_uv", util::view(color_p->range_uv)),
894 };
895
896 auto color_matrix = sws.program[0].uniform("ColorMatrix", members, sizeof(members) / sizeof(decltype(members[0])));
897 if (!color_matrix) {
898 return std::nullopt;
899 }
900
901 sws.color_matrix = std::move(*color_matrix);
902
903 sws.tex = std::move(tex);
904
905 sws.cursor_framebuffer = gl::frame_buf_t::make(1);
906 sws.cursor_framebuffer.bind(&sws.tex[0], &sws.tex[1]);
907
908 sws.program[0].bind(sws.color_matrix);
909 sws.program[1].bind(sws.color_matrix);
910
911 gl::ctx.BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
912 // Dithering must not fill the unused low bits of P010 surfaces.
913 gl::ctx.Disable(GL_DITHER);
914
915 gl_drain_errors;
916
917 return sws;
918 }
919
920 int sws_t::blank(gl::frame_buf_t &fb, int offsetX, int offsetY, int width, int height) {
921 auto f = [&]() {
922 std::swap(offsetX, this->offsetX);
923 std::swap(offsetY, this->offsetY);
924 std::swap(width, this->out_width);
925 std::swap(height, this->out_height);
926 };
927
928 f();
929 auto fg = util::fail_guard(f);
930
931 return convert(fb);
932 }
933
934 std::optional<sws_t> sws_t::make(int in_width, int in_height, int out_width, int out_height, AVPixelFormat format) {
935 GLint gl_format;
936
937 // Decide the bit depth format of the backing texture based the target frame format
938 auto fmt_desc = av_pix_fmt_desc_get(format);
939 switch (fmt_desc->comp[0].depth) {
940 case 8:
941 gl_format = GL_RGBA8;
942 break;
943
944 case 10:
945 gl_format = GL_RGB10_A2;
946 break;
947
948 case 12:
949 gl_format = GL_RGBA12;
950 break;
951
952 case 16:
953 gl_format = GL_RGBA16;
954 break;
955
956 default:
957 BOOST_LOG(error) << "Unsupported pixel format for EGL frame: "sv << (int) format;
958 return std::nullopt;
959 }
960
961 auto tex = gl::tex_t::make(2);
962 gl::ctx.BindTexture(GL_TEXTURE_2D, tex[0]);
963 gl::ctx.TexStorage2D(GL_TEXTURE_2D, 1, gl_format, in_width, in_height);
964
965 return make(in_width, in_height, out_width, out_height, std::move(tex));
966 }
967
968 int sws_t::load_ram(platf::img_t &img, std::uint32_t fourcc) {
969 GLenum format = GL_BGRA;
970 GLenum type = GL_UNSIGNED_BYTE;
971 switch (fourcc) {
972 case 0: // Existing RAM capture callers supply BGRA8.
973 case fourcc_code('X', 'R', '2', '4'):
974 case fourcc_code('A', 'R', '2', '4'):
975 break;
976 case fourcc_code('X', 'R', '3', '0'):
977 case fourcc_code('A', 'R', '3', '0'):
978 type = GL_UNSIGNED_INT_2_10_10_10_REV;
979 break;
980 case fourcc_code('X', 'B', '3', '0'):
981 case fourcc_code('A', 'B', '3', '0'):
982 format = GL_RGBA;
983 type = GL_UNSIGNED_INT_2_10_10_10_REV;
984 break;
985 default:
986 BOOST_LOG(error) << "Unsupported RGB upload fourcc: " << fourcc;
987 return -1;
988 }
989 if (!img.data || img.width != in_width || img.height != in_height ||
990 img.pixel_pitch != 4 || img.row_pitch < static_cast<int64_t>(img.width) * 4 ||
991 img.row_pitch % 4) {
992 BOOST_LOG(error) << "Invalid RGB upload dimensions or stride";
993 return -1;
994 }
995 loaded_texture = tex[0];
996 GLint previous_alignment;
997 gl::ctx.GetIntegerv(GL_UNPACK_ALIGNMENT, &previous_alignment);
998 gl::ctx.PixelStorei(GL_UNPACK_ALIGNMENT, 4);
999 GLint previous_row_length;
1000 gl::ctx.GetIntegerv(GL_UNPACK_ROW_LENGTH, &previous_row_length);
1001 gl::ctx.PixelStorei(GL_UNPACK_ROW_LENGTH, img.row_pitch / 4);
1002 gl::ctx.BindTexture(GL_TEXTURE_2D, loaded_texture);
1003 gl::ctx.TexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, img.width, img.height, format, type, img.data);
1004 gl::ctx.PixelStorei(GL_UNPACK_ROW_LENGTH, previous_row_length);
1005 gl::ctx.PixelStorei(GL_UNPACK_ALIGNMENT, previous_alignment);
1006 return gl::ctx.GetError() == GL_NO_ERROR ? 0 : -1;
1007 }
1008
1009 void sws_t::load_vram(img_descriptor_t &img, int offset_x, int offset_y, int texture) {
1010 // When only a sub-part of the image must be encoded...
1011 const bool copy = offset_x || offset_y || img.sd.width != in_width || img.sd.height != in_height;
1012 if (copy) {
1013 auto framebuf = gl::frame_buf_t::make(1);
1014 framebuf.bind(&texture, &texture + 1);
1015
1016 loaded_texture = tex[0];
1017 framebuf.copy(0, loaded_texture, offset_x, offset_y, in_width, in_height);
1018 } else {
1019 loaded_texture = texture;
1020 }
1021
1022 if (img.data) {
1023 GLenum attachment = GL_COLOR_ATTACHMENT0;
1024
1025 gl::ctx.BindFramebuffer(GL_FRAMEBUFFER, cursor_framebuffer[0]);
1026 gl::ctx.UseProgram(program[2].handle());
1027
1028 // When a copy has already been made...
1029 if (!copy) {
1030 gl::ctx.BindTexture(GL_TEXTURE_2D, texture);
1031 gl::ctx.DrawBuffers(1, &attachment);
1032
1033 gl::ctx.Viewport(0, 0, in_width, in_height);
1034 gl::ctx.DrawArrays(GL_TRIANGLES, 0, 3);
1035
1036 loaded_texture = tex[0];
1037 }
1038
1039 gl::ctx.BindTexture(GL_TEXTURE_2D, tex[1]);
1040 if (serial != img.serial) {
1041 serial = img.serial;
1042
1043 gl::ctx.TexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, img.src_w, img.src_h, 0, GL_BGRA, GL_UNSIGNED_BYTE, img.data);
1044 }
1045
1046 gl::ctx.BlendFunc(img.cursor_premultiplied ? GL_ONE : GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1047 gl::ctx.Enable(GL_BLEND);
1048
1049 gl::ctx.DrawBuffers(1, &attachment);
1050
1051#ifndef NDEBUG
1052 auto status = gl::ctx.CheckFramebufferStatus(GL_FRAMEBUFFER);
1053 if (status != GL_FRAMEBUFFER_COMPLETE) {
1054 BOOST_LOG(error) << "Pass Cursor: CheckFramebufferStatus() --> [0x"sv << util::hex(status).to_string_view() << ']';
1055 return;
1056 }
1057#endif
1058
1059 gl::ctx.Viewport(img.x, img.y, img.width, img.height);
1060 gl::ctx.DrawArrays(GL_TRIANGLES, 0, 3);
1061
1062 gl::ctx.Disable(GL_BLEND);
1063 gl::ctx.BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1064
1065 gl::ctx.BindTexture(GL_TEXTURE_2D, 0);
1066 gl::ctx.BindFramebuffer(GL_FRAMEBUFFER, 0);
1067 }
1068 }
1069
1070 int sws_t::convert(gl::frame_buf_t &fb) {
1071 gl::ctx.BindTexture(GL_TEXTURE_2D, loaded_texture);
1072
1073 GLenum attachments[] {
1074 GL_COLOR_ATTACHMENT0,
1075 GL_COLOR_ATTACHMENT1
1076 };
1077
1078 for (int x = 0; x < sizeof(attachments) / sizeof(decltype(attachments[0])); ++x) {
1079 gl::ctx.BindFramebuffer(GL_FRAMEBUFFER, fb[x]);
1080 gl::ctx.DrawBuffers(1, &attachments[x]);
1081
1082#ifndef NDEBUG
1083 auto status = gl::ctx.CheckFramebufferStatus(GL_FRAMEBUFFER);
1084 if (status != GL_FRAMEBUFFER_COMPLETE) {
1085 BOOST_LOG(error) << "Pass "sv << x << ": CheckFramebufferStatus() --> [0x"sv << util::hex(status).to_string_view() << ']';
1086 return -1;
1087 }
1088#endif
1089
1090 // Clear the entire target, including letterboxing, with encoded black.
1091 const float black[] = {x == 0 ? black_y : black_uv, black_uv, 0.0f, 0.0f};
1092 gl::ctx.ClearBufferfv(GL_COLOR, 0, black);
1093 gl::ctx.UseProgram(program[x].handle());
1094 gl::ctx.Viewport(offsetX / (x + 1), offsetY / (x + 1), out_width / (x + 1), out_height / (x + 1));
1095 gl::ctx.DrawArrays(GL_TRIANGLES, 0, 3);
1096 }
1097
1098 gl::ctx.BindTexture(GL_TEXTURE_2D, 0);
1099
1100 gl::ctx.Flush();
1101
1102 return 0;
1103 }
1104} // namespace egl
1105
1106void free_frame(AVFrame *frame) {
1107 av_frame_free(&frame);
1108}
void copy(int id, int texture, int offset_x, int offset_y, int width, int height)
Definition graphics.cpp:81
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
Declarations for file handling functions.
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
bool bind_egl_image_texture_2d(EGLImage image)
Bind an EGLImage to the currently bound GL_TEXTURE_2D.
Definition graphics.cpp:562
std::vector< EGLAttrib > surface_descriptor_to_egl_attribs(const surface_descriptor_t &surface)
Get EGL attributes for eglCreateImage() to import the provided surface.
Definition graphics.cpp:511
Declarations for graphics related functions.
Declarations for logging related functions.
int version()
Print the version to stdout, then exit.
std::string read_file(const char *path)
Read a file to string.
Declarations for video.
const color_t * new_color_vectors_from_colorspace(const sunshine_colorspace_t &colorspace)
New version of color_vectors_from_colorspace() function that better adheres to the standards....