RenderContext.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. #include <iostream>
  2. #include <GL/glew.h>
  3. #include "CWallpaper.h"
  4. #include "ImageDecoder.h"
  5. #include "RenderContext.h"
  6. #include "SplitLayout.h"
  7. #include "WallpaperEngine/Data/Model/Project.h"
  8. #include "WallpaperEngine/Logging/Log.h"
  9. #include "WallpaperEngine/VideoPlayback/MPV/GLPlayer.h"
  10. #include <chrono>
  11. #include <cstdlib>
  12. #include <unordered_map>
  13. namespace {
  14. using Clock = std::chrono::steady_clock;
  15. double millisSince (const Clock::time_point start) {
  16. return std::chrono::duration<double, std::milli> (Clock::now () - start).count ();
  17. }
  18. // LWE_FRAME_STATS=1 logs per-output frame timings every 2 s, with a glFinish per step (costs throughput)
  19. struct FrameStats {
  20. Clock::time_point windowStart = Clock::now ();
  21. Clock::time_point lastFrame {};
  22. int frames = 0;
  23. double maxInterval = 0.0;
  24. double scene = 0.0, sceneMax = 0.0;
  25. double video = 0.0, videoMax = 0.0;
  26. double swap = 0.0, swapMax = 0.0;
  27. };
  28. bool frameStatsEnabled () {
  29. static const bool enabled = std::getenv ("LWE_FRAME_STATS") != nullptr;
  30. return enabled;
  31. }
  32. std::unordered_map<std::string, FrameStats> s_frameStats;
  33. }
  34. namespace WallpaperEngine::Render {
  35. RenderContext::RenderContext (
  36. Drivers::VideoDriver& driver, WallpaperApplication& app, Media::MediaSource& mediaSource
  37. ) :
  38. m_driver (driver), m_app (app), m_mediaSource (mediaSource),
  39. m_textureCache (std::make_unique<TextureCache> (*this)) {
  40. GLint maxTextureSize = 0;
  41. glGetIntegerv (GL_MAX_TEXTURE_SIZE, &maxTextureSize);
  42. setMaxImageSide (maxTextureSize);
  43. }
  44. void RenderContext::render (Drivers::Output::OutputViewport* viewport) {
  45. if (frameStatsEnabled ()) {
  46. this->renderWithStats (viewport);
  47. return;
  48. }
  49. viewport->makeCurrent ();
  50. this->m_textureCache->repaintConditionalTextures ();
  51. #if !NDEBUG
  52. const std::string str = "Rendering to output " + viewport->name;
  53. glPushDebugGroup (GL_DEBUG_SOURCE_APPLICATION, 0, -1, str.c_str ());
  54. #endif /* DEBUG */
  55. this->drawWallpapers (*viewport);
  56. #if !NDEBUG
  57. glPopDebugGroup ();
  58. #endif /* DEBUG */
  59. viewport->swapOutput ();
  60. }
  61. void RenderContext::renderWithStats (Drivers::Output::OutputViewport* viewport) {
  62. auto& stats = s_frameStats[viewport->name];
  63. const auto frameStart = Clock::now ();
  64. if (stats.lastFrame != Clock::time_point {}) {
  65. stats.maxInterval = std::max (
  66. stats.maxInterval, std::chrono::duration<double, std::milli> (frameStart - stats.lastFrame).count ()
  67. );
  68. }
  69. stats.lastFrame = frameStart;
  70. viewport->makeCurrent ();
  71. this->m_textureCache->repaintConditionalTextures ();
  72. glFinish ();
  73. VideoPlayback::MPV::GLPlayer::s_statsMillis = 0.0;
  74. const auto sceneStart = Clock::now ();
  75. this->drawWallpapers (*viewport);
  76. glFinish ();
  77. const double video = VideoPlayback::MPV::GLPlayer::s_statsMillis;
  78. const double scene = millisSince (sceneStart) - video;
  79. const auto swapStart = Clock::now ();
  80. viewport->swapOutput ();
  81. const double swap = millisSince (swapStart);
  82. stats.frames++;
  83. stats.scene += scene;
  84. stats.sceneMax = std::max (stats.sceneMax, scene);
  85. stats.video += video;
  86. stats.videoMax = std::max (stats.videoMax, video);
  87. stats.swap += swap;
  88. stats.swapMax = std::max (stats.swapMax, swap);
  89. const double window = millisSince (stats.windowStart);
  90. if (window < 2000.0) {
  91. return;
  92. }
  93. const double n = stats.frames;
  94. sLog.out (
  95. "FRAME-STATS ", viewport->name, ": ", n * 1000.0 / window, " fps, worst gap ", stats.maxInterval,
  96. "ms | scene avg ", stats.scene / n, " max ", stats.sceneMax, " | video avg ", stats.video / n, " max ",
  97. stats.videoMax, " | swap avg ", stats.swap / n, " max ", stats.swapMax, " (ms)"
  98. );
  99. stats = FrameStats { .lastFrame = stats.lastFrame };
  100. }
  101. void RenderContext::drawWallpapers (Drivers::Output::OutputViewport& viewport) {
  102. if (const auto* split = this->m_app.getContext ().findSplitScreen (viewport.name); split != nullptr) {
  103. this->drawSplitScreen (viewport, *split);
  104. return;
  105. }
  106. const auto ref = this->m_wallpapers.find (viewport.name);
  107. if (ref == this->m_wallpapers.end ()) {
  108. return;
  109. }
  110. ref->second->setOutputHDR (viewport.isHDR (), viewport.getHDRLuminance ());
  111. viewport.setWantsPointerButtons (ref->second->wantsPointerButtons ());
  112. ref->second->render (
  113. viewport.viewport, this->getOutput ().renderVFlip (), viewport.globalPosition, viewport.logicalSize
  114. );
  115. this->drawHeldFrame (viewport.name, viewport.viewport, *ref->second);
  116. }
  117. void RenderContext::drawSplitScreen (
  118. Drivers::Output::OutputViewport& viewport, const Application::ApplicationContext::SplitScreen& split
  119. ) {
  120. const glm::ivec4 output = viewport.viewport;
  121. const bool vflip = this->getOutput ().renderVFlip ();
  122. std::vector<CWallpaper*> wallpapers;
  123. std::vector<float> aspects;
  124. for (const auto& slot : split.slots) {
  125. const auto it = this->m_wallpapers.find (slot);
  126. auto* wallpaper = it != this->m_wallpapers.end () ? it->second.get () : nullptr;
  127. wallpapers.push_back (wallpaper);
  128. aspects.push_back (wallpaper != nullptr ? wallpaper->getAspectRatio () : 0.0f);
  129. }
  130. const auto rects = splitSlotRects ({ output.z, output.w }, aspects, split.layout, vflip);
  131. // bars around centered slots and failed slots
  132. glBindFramebuffer (GL_FRAMEBUFFER, this->m_app.getDestinationFramebuffer ());
  133. glEnable (GL_SCISSOR_TEST);
  134. glScissor (output.x, output.y, output.z, output.w);
  135. glClearColor (0.0f, 0.0f, 0.0f, 1.0f);
  136. glClear (GL_COLOR_BUFFER_BIT);
  137. glDisable (GL_SCISSOR_TEST);
  138. bool wantsPointerButtons = false;
  139. for (std::size_t i = 0; i < split.slots.size (); i++) {
  140. const glm::ivec4 rect { output.x + rects[i].x, output.y + rects[i].y, rects[i].z, rects[i].w };
  141. this->m_slotRects.insert_or_assign (split.slots[i], rect);
  142. if (wallpapers[i] == nullptr || rect.z <= 0 || rect.w <= 0) {
  143. continue;
  144. }
  145. wallpapers[i]->setOutputHDR (viewport.isHDR (), viewport.getHDRLuminance ());
  146. wallpapers[i]->setPointerRegion (rect);
  147. wantsPointerButtons = wantsPointerButtons || wallpapers[i]->wantsPointerButtons ();
  148. wallpapers[i]->render (rect, vflip, viewport.globalPosition, viewport.logicalSize);
  149. this->drawHeldFrame (split.slots[i], rect, *wallpapers[i]);
  150. }
  151. viewport.setWantsPointerButtons (wantsPointerButtons);
  152. }
  153. std::optional<RenderContext::DrawTarget> RenderContext::findDrawTarget (const std::string& display) const {
  154. const auto& viewports = this->getOutput ().getViewports ();
  155. if (const auto* split = this->m_app.getContext ().findSplitScreen (display); split != nullptr) {
  156. const auto viewport = viewports.find (split->screen);
  157. const auto rect = this->m_slotRects.find (display);
  158. if (viewport == viewports.end () || rect == this->m_slotRects.end ()) {
  159. return std::nullopt;
  160. }
  161. return DrawTarget { .viewport = viewport->second, .rect = rect->second };
  162. }
  163. const auto viewport = viewports.find (display);
  164. if (viewport == viewports.end ()) {
  165. return std::nullopt;
  166. }
  167. return DrawTarget { .viewport = viewport->second, .rect = viewport->second->viewport };
  168. }
  169. void RenderContext::setWallpaper (
  170. const std::string& display, std::shared_ptr<CWallpaper> wallpaper, const bool holdPrevious
  171. ) {
  172. if (holdPrevious) {
  173. this->holdFrame (display);
  174. } else {
  175. this->releaseHeldFrame (display);
  176. }
  177. wallpaper->setDestinationFramebuffer (this->m_app.getDestinationFramebuffer ());
  178. this->m_wallpapers.insert_or_assign (display, wallpaper);
  179. this->pruneTextures ();
  180. }
  181. void RenderContext::holdFrame (const std::string& display) {
  182. const auto current = this->m_wallpapers.find (display);
  183. const auto target = this->findDrawTarget (display);
  184. if (current == this->m_wallpapers.end () || !target.has_value ()) {
  185. this->releaseHeldFrame (display);
  186. return;
  187. }
  188. // keep the older frame when switching again before content arrived
  189. if (this->m_heldFrames.contains (display) && !current->second->hasContent ()) {
  190. return;
  191. }
  192. this->releaseHeldFrame (display);
  193. const glm::ivec4 rect = target->rect;
  194. if (rect.z <= 0 || rect.w <= 0) {
  195. return;
  196. }
  197. target->viewport->makeCurrent ();
  198. HeldFrame held { .viewport = rect };
  199. if (!allocateHeldFrame (held)) {
  200. sLog.error ("Cannot keep the previous wallpaper on ", display, " while the new one loads");
  201. glBindFramebuffer (GL_FRAMEBUFFER, this->m_app.getDestinationFramebuffer ());
  202. return;
  203. }
  204. glClearColor (0.0f, 0.0f, 0.0f, 1.0f);
  205. glClear (GL_COLOR_BUFFER_BIT);
  206. current->second->setDestinationFramebuffer (held.framebuffer);
  207. current->second->present (
  208. { 0, 0, rect.z, rect.w }, target->viewport->globalPosition, target->viewport->logicalSize
  209. );
  210. current->second->setDestinationFramebuffer (this->m_app.getDestinationFramebuffer ());
  211. glBindFramebuffer (GL_FRAMEBUFFER, this->m_app.getDestinationFramebuffer ());
  212. this->m_heldFrames.insert_or_assign (display, held);
  213. }
  214. void RenderContext::releaseHeldFrame (const std::string& display) {
  215. const auto held = this->m_heldFrames.find (display);
  216. if (held == this->m_heldFrames.end ()) {
  217. return;
  218. }
  219. glDeleteFramebuffers (1, &held->second.framebuffer);
  220. glDeleteTextures (1, &held->second.texture);
  221. this->m_heldFrames.erase (held);
  222. }
  223. void RenderContext::drawHeldFrame (const std::string& display, const glm::ivec4& rect, const CWallpaper& wallpaper) {
  224. auto held = this->m_heldFrames.find (display);
  225. if (held == this->m_heldFrames.end ()) {
  226. return;
  227. }
  228. if (wallpaper.hasContent ()) {
  229. this->releaseHeldFrame (display);
  230. return;
  231. }
  232. // the old frame is stretched over the new slot rect, via a copy since multisampled outputs only take 1:1 blits
  233. if (held->second.viewport.z != rect.z || held->second.viewport.w != rect.w) {
  234. HeldFrame resized { .viewport = rect };
  235. if (rect.z <= 0 || rect.w <= 0 || !allocateHeldFrame (resized)) {
  236. this->releaseHeldFrame (display);
  237. glBindFramebuffer (GL_FRAMEBUFFER, this->m_app.getDestinationFramebuffer ());
  238. return;
  239. }
  240. glBindFramebuffer (GL_READ_FRAMEBUFFER, held->second.framebuffer);
  241. glBindFramebuffer (GL_DRAW_FRAMEBUFFER, resized.framebuffer);
  242. glBlitFramebuffer (
  243. 0, 0, held->second.viewport.z, held->second.viewport.w, 0, 0, rect.z, rect.w, GL_COLOR_BUFFER_BIT, GL_LINEAR
  244. );
  245. this->releaseHeldFrame (display);
  246. held = this->m_heldFrames.insert_or_assign (display, resized).first;
  247. }
  248. glBindFramebuffer (GL_READ_FRAMEBUFFER, held->second.framebuffer);
  249. glBindFramebuffer (GL_DRAW_FRAMEBUFFER, this->m_app.getDestinationFramebuffer ());
  250. glBlitFramebuffer (
  251. 0, 0, rect.z, rect.w, rect.x, rect.y, rect.x + rect.z, rect.y + rect.w, GL_COLOR_BUFFER_BIT, GL_NEAREST
  252. );
  253. glBindFramebuffer (GL_FRAMEBUFFER, this->m_app.getDestinationFramebuffer ());
  254. }
  255. bool RenderContext::allocateHeldFrame (HeldFrame& held) {
  256. glGenTextures (1, &held.texture);
  257. glBindTexture (GL_TEXTURE_2D, held.texture);
  258. glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA16F, held.viewport.z, held.viewport.w, 0, GL_RGBA, GL_HALF_FLOAT, nullptr);
  259. glBindTexture (GL_TEXTURE_2D, 0);
  260. glGenFramebuffers (1, &held.framebuffer);
  261. glBindFramebuffer (GL_FRAMEBUFFER, held.framebuffer);
  262. glFramebufferTexture2D (GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, held.texture, 0);
  263. if (glCheckFramebufferStatus (GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE) {
  264. return true;
  265. }
  266. glDeleteFramebuffers (1, &held.framebuffer);
  267. glDeleteTextures (1, &held.texture);
  268. return false;
  269. }
  270. void RenderContext::pruneTextures () const { this->m_textureCache->prune (); }
  271. void RenderContext::setPause (const bool newState) const {
  272. for (const auto& wallpaper : this->m_wallpapers | std::views::values) {
  273. wallpaper->setPause (newState);
  274. }
  275. }
  276. Input::InputContext& RenderContext::getInputContext () const { return this->m_driver.getInputContext (); }
  277. const WallpaperApplication& RenderContext::getApp () const { return this->m_app; }
  278. const Drivers::VideoDriver& RenderContext::getDriver () const { return this->m_driver; }
  279. const Drivers::Output::Output& RenderContext::getOutput () const { return this->m_driver.getOutput (); }
  280. std::shared_ptr<const TextureProvider>
  281. RenderContext::resolveTexture (const std::string& name, const Data::Model::Project& project) const {
  282. return this->m_textureCache->resolve (name, project);
  283. }
  284. std::shared_ptr<const TextureProvider>
  285. RenderContext::findLoadedTexture (const std::string& name, const Data::Model::Project& project) const {
  286. return this->m_textureCache->findLoaded (name, project);
  287. }
  288. const std::map<std::string, std::shared_ptr<CWallpaper>>& RenderContext::getWallpapers () const {
  289. return this->m_wallpapers;
  290. }
  291. Media::MediaSource& RenderContext::getMediaSource () const { return this->m_mediaSource; }
  292. std::optional<glm::ivec4> RenderContext::getSlotRect (const std::string& slot) const {
  293. const auto rect = this->m_slotRects.find (slot);
  294. return rect != this->m_slotRects.end () ? std::optional (rect->second) : std::nullopt;
  295. }
  296. } // namespace WallpaperEngine::Render