HeadlessOpenGLDriver.cpp 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. #include "HeadlessOpenGLDriver.h"
  2. #include "VideoFactories.h"
  3. #include "WallpaperEngine/Logging/Log.h"
  4. #include "WallpaperEngine/Render/Drivers/Output/GLFWWindowOutput.h"
  5. #include <EGL/eglext.h>
  6. #include <algorithm>
  7. #include <cstdio>
  8. #include <cstdlib>
  9. #include <cstring>
  10. #include <filesystem>
  11. #include <fstream>
  12. #include <sstream>
  13. #include <string>
  14. #include <vector>
  15. using namespace WallpaperEngine::Render::Drivers;
  16. namespace {
  17. EGLDisplay openDisplay () {
  18. const auto queryDevices = reinterpret_cast<PFNEGLQUERYDEVICESEXTPROC> (eglGetProcAddress ("eglQueryDevicesEXT"));
  19. const auto queryDeviceString
  20. = reinterpret_cast<PFNEGLQUERYDEVICESTRINGEXTPROC> (eglGetProcAddress ("eglQueryDeviceStringEXT"));
  21. const auto getPlatformDisplay
  22. = reinterpret_cast<PFNEGLGETPLATFORMDISPLAYEXTPROC> (eglGetProcAddress ("eglGetPlatformDisplayEXT"));
  23. if (queryDevices == nullptr || queryDeviceString == nullptr || getPlatformDisplay == nullptr) {
  24. sLog.exception ("EGL device enumeration is not available, cannot render headless");
  25. }
  26. EGLint count = 0;
  27. queryDevices (0, nullptr, &count);
  28. std::vector<EGLDeviceEXT> devices (count);
  29. queryDevices (count, devices.data (), &count);
  30. const char* wanted = std::getenv ("LWE_HEADLESS_DEVICE");
  31. std::vector<std::pair<EGLDeviceEXT, std::string>> candidates;
  32. for (const auto device : devices) {
  33. // devices without a render node are software renderers (llvmpipe), the whole point is to avoid those
  34. const char* node = queryDeviceString (device, EGL_DRM_RENDER_NODE_FILE_EXT);
  35. if (node != nullptr && (wanted == nullptr || std::strcmp (node, wanted) == 0)) {
  36. candidates.emplace_back (device, node);
  37. }
  38. }
  39. // with an iGPU and a dedicated card, EGL often lists the iGPU first; the card driving the boot
  40. // display is the better guess
  41. std::ranges::stable_partition (candidates, [] (const auto& candidate) {
  42. const auto name = std::filesystem::path (candidate.second).filename ();
  43. std::ifstream bootVga ("/sys/class/drm" / name / "device/boot_vga");
  44. char value = '0';
  45. bootVga >> value;
  46. return value == '1';
  47. });
  48. for (const auto& [device, node] : candidates) {
  49. const EGLDisplay display = getPlatformDisplay (EGL_PLATFORM_DEVICE_EXT, device, nullptr);
  50. if (display != EGL_NO_DISPLAY && eglInitialize (display, nullptr, nullptr)) {
  51. sLog.out ("Headless rendering on ", node);
  52. return display;
  53. }
  54. }
  55. sLog.exception (
  56. "No usable GPU found for headless rendering", wanted ? " (LWE_HEADLESS_DEVICE=" : "", wanted ? wanted : "",
  57. wanted ? ")" : ""
  58. );
  59. return EGL_NO_DISPLAY;
  60. }
  61. } // namespace
  62. HeadlessOpenGLDriver::FixedMouse::FixedMouse (const HeadlessOpenGLDriver& driver) : m_driver (driver) {
  63. const char* cursor = std::getenv ("LWE_HEADLESS_CURSOR");
  64. if (cursor != nullptr && std::sscanf (cursor, "%lf,%lf", &m_fraction.x, &m_fraction.y) != 2) {
  65. m_fraction = glm::dvec2 (0.5);
  66. }
  67. const char* path = std::getenv ("LWE_HEADLESS_CURSOR_PATH");
  68. std::istringstream steps (path != nullptr ? path : "");
  69. std::string text;
  70. while (std::getline (steps, text, ';')) {
  71. Step step {};
  72. char button = 0;
  73. const int fields
  74. = std::sscanf (text.c_str (), "%lf:%lf,%lf,%c", &step.time, &step.fraction.x, &step.fraction.y, &button);
  75. if (fields >= 3) {
  76. step.down = fields == 4 && button == 'd';
  77. m_path.push_back (step);
  78. }
  79. }
  80. }
  81. void HeadlessOpenGLDriver::FixedMouse::update () {
  82. const double elapsed
  83. = std::chrono::duration<double> (std::chrono::steady_clock::now () - m_driver.m_started).count ();
  84. for (const auto& step : m_path) {
  85. if (step.time > elapsed) {
  86. break;
  87. }
  88. m_fraction = step.fraction;
  89. m_down = step.down;
  90. }
  91. }
  92. HeadlessOpenGLDriver::HeadlessOpenGLDriver (ApplicationContext& context, WallpaperApplication& app) :
  93. VideoDriver (app, m_mouseInput), m_mouseInput (*this) {
  94. this->m_display = openDisplay ();
  95. const EGLint configAttributes[] = { EGL_SURFACE_TYPE,
  96. EGL_PBUFFER_BIT,
  97. EGL_RENDERABLE_TYPE,
  98. EGL_OPENGL_BIT,
  99. EGL_RED_SIZE,
  100. 8,
  101. EGL_GREEN_SIZE,
  102. 8,
  103. EGL_BLUE_SIZE,
  104. 8,
  105. EGL_ALPHA_SIZE,
  106. 8,
  107. EGL_DEPTH_SIZE,
  108. 24,
  109. EGL_STENCIL_SIZE,
  110. 8,
  111. EGL_NONE };
  112. EGLint configs = 0;
  113. if (!eglChooseConfig (this->m_display, configAttributes, &this->m_config, 1, &configs) || configs == 0) {
  114. sLog.exception ("No pbuffer capable EGL config for headless rendering");
  115. }
  116. eglBindAPI (EGL_OPENGL_API);
  117. const EGLint contextAttributes[] = { EGL_CONTEXT_MAJOR_VERSION,
  118. 3,
  119. EGL_CONTEXT_MINOR_VERSION,
  120. 3,
  121. EGL_CONTEXT_OPENGL_PROFILE_MASK,
  122. EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT,
  123. EGL_CONTEXT_OPENGL_DEBUG,
  124. EGL_TRUE,
  125. EGL_NONE };
  126. this->m_eglContext = eglCreateContext (this->m_display, this->m_config, EGL_NO_CONTEXT, contextAttributes);
  127. if (this->m_eglContext == EGL_NO_CONTEXT) {
  128. sLog.exception ("Cannot create headless OpenGL context: ", eglGetError ());
  129. }
  130. if (context.settings.render.mode == ApplicationContext::EXPLICIT_WINDOW) {
  131. this->m_size = { context.settings.render.window.geometry.z, context.settings.render.window.geometry.w };
  132. }
  133. this->createSurface ();
  134. glewExperimental = GL_TRUE;
  135. // GLEW built with GLX support fails its GLX part without an X display, the GL functions are loaded by then
  136. if (const GLenum result = glewInit (); result != GLEW_OK && result != GLEW_ERROR_NO_GLX_DISPLAY) {
  137. sLog.error ("Failed to initialize GLEW: ", glewGetErrorString (result));
  138. }
  139. this->m_output = new Output::GLFWWindowOutput (context, *this);
  140. }
  141. HeadlessOpenGLDriver::~HeadlessOpenGLDriver () {
  142. eglMakeCurrent (this->m_display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
  143. eglDestroySurface (this->m_display, this->m_surface);
  144. eglDestroyContext (this->m_display, this->m_eglContext);
  145. eglTerminate (this->m_display);
  146. }
  147. void HeadlessOpenGLDriver::createSurface () {
  148. const EGLint attributes[] = { EGL_WIDTH, this->m_size.x, EGL_HEIGHT, this->m_size.y, EGL_NONE };
  149. const EGLSurface surface = eglCreatePbufferSurface (this->m_display, this->m_config, attributes);
  150. if (surface == EGL_NO_SURFACE) {
  151. sLog.exception ("Cannot create a ", this->m_size.x, "x", this->m_size.y, " pbuffer: ", eglGetError ());
  152. }
  153. eglMakeCurrent (this->m_display, surface, surface, this->m_eglContext);
  154. if (this->m_surface != EGL_NO_SURFACE) {
  155. eglDestroySurface (this->m_display, this->m_surface);
  156. }
  157. this->m_surface = surface;
  158. }
  159. Output::Output& HeadlessOpenGLDriver::getOutput () { return *this->m_output; }
  160. float HeadlessOpenGLDriver::getRenderTime () const {
  161. return std::chrono::duration<float> (std::chrono::steady_clock::now () - this->m_started).count ();
  162. }
  163. bool HeadlessOpenGLDriver::closeRequested () { return false; }
  164. void HeadlessOpenGLDriver::resizeWindow (glm::ivec2 size) {
  165. if (size == this->m_size || size.x <= 0 || size.y <= 0) {
  166. return;
  167. }
  168. this->m_size = size;
  169. this->createSurface ();
  170. }
  171. void HeadlessOpenGLDriver::resizeWindow (glm::ivec4 sizeandpos) {
  172. this->resizeWindow (glm::ivec2 (sizeandpos.z, sizeandpos.w));
  173. }
  174. void HeadlessOpenGLDriver::showWindow () { }
  175. void HeadlessOpenGLDriver::hideWindow () { }
  176. glm::ivec2 HeadlessOpenGLDriver::getFramebufferSize () const { return this->m_size; }
  177. uint32_t HeadlessOpenGLDriver::getFrameCounter () const { return this->m_frameCounter; }
  178. void HeadlessOpenGLDriver::dispatchEventQueue () {
  179. glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  180. for (const auto& [screen, viewport] : this->m_output->getViewports ()) {
  181. this->getApp ().update (viewport);
  182. }
  183. this->m_output->updateRender ();
  184. // there's no swap to throttle on, so keep at most one frame queued on the GPU instead of letting
  185. // --fps 1000 pile up work faster than it gets done
  186. if (this->m_lastFrame != nullptr) {
  187. glClientWaitSync (this->m_lastFrame, GL_SYNC_FLUSH_COMMANDS_BIT, GL_TIMEOUT_IGNORED);
  188. glDeleteSync (this->m_lastFrame);
  189. }
  190. this->m_lastFrame = glFenceSync (GL_SYNC_GPU_COMMANDS_COMPLETE, 0);
  191. glFlush ();
  192. this->m_frameCounter++;
  193. }
  194. void* HeadlessOpenGLDriver::getProcAddress (const char* name) const {
  195. return reinterpret_cast<void*> (eglGetProcAddress (name));
  196. }
  197. __attribute__ ((constructor)) void registerHeadlessOpenGLDriver () {
  198. const auto create
  199. = [] (ApplicationContext& context, WallpaperApplication& application) -> std::unique_ptr<VideoDriver> {
  200. return std::make_unique<HeadlessOpenGLDriver> (context, application);
  201. };
  202. sVideoFactories.registerDriver (ApplicationContext::EXPLICIT_WINDOW, "headless", create);
  203. sVideoFactories.registerDriver (ApplicationContext::NORMAL_WINDOW, "headless", create);
  204. }