CWeb.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769
  1. // This code is a modification of the original projects that can be found at
  2. // https://github.com/if1live/cef-gl-example
  3. // https://github.com/andmcgregor/cefgui
  4. #include "CWeb.h"
  5. #include "WallpaperEngine/Application/WallpaperApplication.h"
  6. #include "WallpaperEngine/Audio/Drivers/PulseProcessVolume.h"
  7. #include "WallpaperEngine/Debugging/Profiling.h"
  8. #include "WallpaperEngine/Logging/Log.h"
  9. #include "WallpaperEngine/Data/Model/Project.h"
  10. #include "WallpaperEngine/Data/Model/Wallpaper.h"
  11. #include "WallpaperEngine/Media/ThumbnailPalette.h"
  12. #include "WallpaperEngine/Render/RenderContext.h"
  13. #include "WallpaperEngine/WebBrowser/CEF/TestHookPolicy.h"
  14. #include "WebDmabufImport.h"
  15. #include "WallpaperEngine/Data/Utils/FloatCompare.h"
  16. #include <atomic>
  17. #include <chrono>
  18. #include <cmath>
  19. #include <csignal>
  20. #include <cstdlib>
  21. #include <cstring>
  22. #include <fcntl.h>
  23. #include <string_view>
  24. #include <sys/prctl.h>
  25. #include <sys/socket.h>
  26. #include <sys/syscall.h>
  27. #include <sys/wait.h>
  28. #include <thread>
  29. #include <unistd.h>
  30. using namespace WallpaperEngine::Render;
  31. using namespace WallpaperEngine::Render::Wallpapers;
  32. using namespace WallpaperEngine::WebBrowser::IPC;
  33. namespace {
  34. // closes every fd but stdio so CEF doesn't inherit our Wayland/EGL/X11/audio connections; raw syscalls only, other
  35. // threads may hold malloc locks
  36. void closeInheritedFds (const unsigned int first = 3) {
  37. #if defined(SYS_close_range)
  38. syscall (SYS_close_range, first, ~0u, 0u);
  39. #endif
  40. }
  41. // the descriptor the dmabuf socket has in the host, below it everything but stdio is closed
  42. constexpr int HOST_SOCKET_FD = 3;
  43. // a page paints its background long before its content, so a flat color doesn't count. Samples a grid
  44. bool frameHasContent (const uint8_t* pixels, uint32_t width, uint32_t height) {
  45. constexpr uint32_t columns = 48;
  46. constexpr uint32_t rows = 27;
  47. constexpr int tolerance = 2;
  48. const uint8_t* first = pixels;
  49. for (uint32_t row = 0; row < rows; row++) {
  50. const uint32_t y = (height - 1) * row / (rows - 1);
  51. for (uint32_t column = 0; column < columns; column++) {
  52. const uint32_t x = (width - 1) * column / (columns - 1);
  53. const uint8_t* pixel = pixels + (static_cast<size_t> (y) * width + x) * 4;
  54. for (int channel = 0; channel < 4; channel++) {
  55. if (std::abs (pixel[channel] - first[channel]) > tolerance) {
  56. return true;
  57. }
  58. }
  59. }
  60. }
  61. return false;
  62. }
  63. // after a reinstall /proc/self/exe reads "<path> (deleted)" and CEF aborts resolving its zygote through it; the new
  64. // binary at the original path is fine
  65. std::string hostExecutable () {
  66. constexpr std::string_view deletedSuffix = " (deleted)";
  67. std::error_code error;
  68. const std::string target = std::filesystem::read_symlink ("/proc/self/exe", error).string ();
  69. if (error || !target.ends_with (deletedSuffix)) {
  70. return "/proc/self/exe";
  71. }
  72. std::string original = target.substr (0, target.size () - deletedSuffix.size ());
  73. if (access (original.c_str (), X_OK) != 0) {
  74. sLog.error ("CWeb: engine executable ", original, " was removed, the web host will likely fail to start");
  75. return "/proc/self/exe";
  76. }
  77. sLog.out ("CWeb: engine executable was replaced on disk, starting the web host from ", original);
  78. return original;
  79. }
  80. }
  81. CWeb::CWeb (
  82. const Wallpaper& wallpaper, RenderContext& context, AudioContext& audioContext,
  83. const std::filesystem::path& resolvedBackgroundPath, const WallpaperState::TextureUVsScaling& scalingMode,
  84. const uint32_t& clampMode, const glm::ivec2& maxRenderSize
  85. ) : CWallpaper (wallpaper, context, audioContext, scalingMode, clampMode) {
  86. this->setupFramebuffers ();
  87. // shared frame capacity from maxRenderSize, the full output size would oversize separate wallpapers
  88. this->m_shmMaxWidth = static_cast<uint32_t> (std::max (1, maxRenderSize.x));
  89. this->m_shmMaxHeight = static_cast<uint32_t> (std::max (1, maxRenderSize.y));
  90. this->m_shm = createSharedMemory (this->m_shmName, this->m_shmMaxWidth, this->m_shmMaxHeight);
  91. if (this->m_shm == nullptr) {
  92. sLog.exception ("CWeb: failed to create shared memory for the web host process");
  93. }
  94. this->m_width = static_cast<int> (this->m_shmMaxWidth);
  95. this->m_height = static_cast<int> (this->m_shmMaxHeight);
  96. this->m_shm->desiredWidth.store (static_cast<uint32_t> (this->m_width), std::memory_order_relaxed);
  97. this->m_shm->desiredHeight.store (static_cast<uint32_t> (this->m_height), std::memory_order_relaxed);
  98. // pushed from the recorder's capture thread, the host process only ever reads these atomics
  99. auto* shm = this->m_shm;
  100. this->m_spectrumRecorder = &this->getAudioContext ().getRecorder ();
  101. this->m_spectrumListenerId = this->m_spectrumRecorder->addSpectrumListener ([shm] (const float* bands) {
  102. for (std::size_t i = 0; i < WebHostSharedMemory::AUDIO_BANDS; i++) {
  103. shm->audioBands[i].store (bands[i], std::memory_order_relaxed);
  104. }
  105. });
  106. this->m_statsEnabled = std::getenv ("LWE_WEB_STATS") != nullptr;
  107. this->m_hostBackgroundPath = resolvedBackgroundPath;
  108. this->m_frameMode = this->chooseFrameMode ();
  109. this->spawnHost (resolvedBackgroundPath);
  110. this->m_streamVolume = std::make_unique<Audio::Drivers::PulseProcessVolume> (this->m_hostPid);
  111. this->setAudioPolicy (false, std::nullopt);
  112. }
  113. CWeb::FrameMode CWeb::chooseFrameMode () const {
  114. const std::string& request = this->getContext ().getApp ().getContext ().settings.render.webFrames;
  115. if (request == "shm") {
  116. return FrameMode::Shm;
  117. }
  118. const bool forced = request == "dmabuf";
  119. const char* wayland = std::getenv ("WAYLAND_DISPLAY");
  120. const char* x11 = std::getenv ("DISPLAY");
  121. if (!WebDmabufImport::available ()) {
  122. if (forced) {
  123. sLog.error (
  124. "--web-frames dmabuf: this OpenGL context cannot import dmabufs (needs EGL), using shared memory"
  125. );
  126. }
  127. return FrameMode::Shm;
  128. }
  129. if ((wayland == nullptr || wayland[0] == '\0') && (x11 == nullptr || x11[0] == '\0')) {
  130. // the browser makes shareable buffers on Wayland's dmabuf support or X11's DRI3 only, not headless
  131. if (forced) {
  132. sLog.error (
  133. "--web-frames dmabuf: no Wayland or X11 session for the browser to render on, using shared memory"
  134. );
  135. }
  136. return FrameMode::Shm;
  137. }
  138. if (!forced) {
  139. // auto stays on shared memory where dmabufs are known to be a gamble: the NVIDIA proprietary driver is picky
  140. // about modifiers and EGL imports. --web-frames dmabuf tries anyway
  141. const auto* vendor = reinterpret_cast<const char*> (glGetString (GL_VENDOR));
  142. if (vendor != nullptr && std::string_view (vendor).find ("NVIDIA") != std::string_view::npos) {
  143. return FrameMode::Shm;
  144. }
  145. }
  146. return FrameMode::Dmabuf;
  147. }
  148. void CWeb::spawnHost (const std::filesystem::path& resolvedBackgroundPath) {
  149. auto& appContext = this->getContext ().getApp ().getContext ();
  150. const std::string executable = hostExecutable ();
  151. int hostSocket = -1;
  152. if (this->m_frameMode == FrameMode::Dmabuf) {
  153. if (!WallpaperEngine::WebBrowser::IPC::makeDmabufSocketPair (this->m_dmabufSocket, hostSocket)) {
  154. sLog.error ("CWeb: cannot make the dmabuf socket, using shared memory frames");
  155. this->m_frameMode = FrameMode::Shm;
  156. this->m_dmabufSocket = -1;
  157. } else if (this->m_dmabufImport == nullptr) {
  158. this->m_dmabufImport = std::make_unique<WebDmabufImport> ();
  159. }
  160. }
  161. // stream restore would hand our "Chromium" volume to the user's browser, so the host's stream opts out
  162. // tests only (HEADLESS_RENDER_WEB=1): LD_PRELOAD for the host alone, libcef.so before libc for its close() wrapper
  163. const char* preload = std::getenv ("LWE_WEB_HOST_PRELOAD");
  164. if (preload != nullptr && preload[0] != '\0' && !WallpaperEngine::WebBrowser::CEF::trustedPreloadFile (preload)) {
  165. sLog.error (
  166. "LWE_WEB_HOST_PRELOAD: ignoring ", preload, ", it must be an absolute path to a file only you can write"
  167. );
  168. preload = nullptr;
  169. }
  170. std::vector<std::string> environment;
  171. for (char** entry = environ; *entry != nullptr; entry++) {
  172. const std::string_view variable (*entry);
  173. if (!variable.starts_with ("PULSE_PROP_state.restore-props=")
  174. && !variable.starts_with ("PULSE_PROP_module-stream-restore.id=")
  175. && !(preload != nullptr && preload[0] != '\0' && variable.starts_with ("LD_PRELOAD="))) {
  176. environment.emplace_back (*entry);
  177. }
  178. }
  179. environment.emplace_back ("PULSE_PROP_state.restore-props=false");
  180. environment.emplace_back ("PULSE_PROP_module-stream-restore.id=lwe-web");
  181. if (preload != nullptr && preload[0] != '\0') {
  182. environment.emplace_back (std::string ("LD_PRELOAD=") + preload);
  183. }
  184. std::vector<char*> envp;
  185. for (auto& entry : environment) {
  186. envp.push_back (entry.data ());
  187. }
  188. envp.push_back (nullptr);
  189. const pid_t pid = fork ();
  190. if (pid < 0) {
  191. // sLog.exception() throws before ~CWeb() runs, unlink the shm segment here
  192. closeSharedMemory (this->m_shm, this->m_shmName, this->m_shmMaxWidth, this->m_shmMaxHeight, true);
  193. if (hostSocket >= 0) {
  194. close (hostSocket);
  195. }
  196. sLog.exception ("CWeb: fork() failed while spawning the web host process");
  197. }
  198. if (pid == 0) {
  199. if (hostSocket >= 0) {
  200. // the one descriptor the host keeps, at a fixed number; dup2 clears close-on-exec, and when it already sits
  201. // there the flag has to go by hand
  202. if (hostSocket != HOST_SOCKET_FD) {
  203. dup2 (hostSocket, HOST_SOCKET_FD);
  204. } else {
  205. fcntl (HOST_SOCKET_FD, F_SETFD, 0);
  206. }
  207. closeInheritedFds (HOST_SOCKET_FD + 1);
  208. } else {
  209. closeInheritedFds ();
  210. }
  211. // kill this child if the parent dies without telling it to quit over shared memory
  212. prctl (PR_SET_PDEATHSIG, SIGTERM);
  213. std::vector<std::string> args;
  214. args.emplace_back (resolvedBackgroundPath.string ());
  215. args.emplace_back ("--web-host");
  216. args.emplace_back ("--web-host-shm");
  217. args.emplace_back (this->m_shmName);
  218. args.emplace_back ("--web-host-width");
  219. args.emplace_back (std::to_string (this->m_shmMaxWidth));
  220. args.emplace_back ("--web-host-height");
  221. args.emplace_back (std::to_string (this->m_shmMaxHeight));
  222. if (hostSocket >= 0) {
  223. args.emplace_back ("--web-host-frames");
  224. args.emplace_back ("dmabuf");
  225. args.emplace_back ("--web-host-socket");
  226. args.emplace_back (std::to_string (HOST_SOCKET_FD));
  227. }
  228. if (!appContext.settings.general.assets.empty ()) {
  229. args.emplace_back ("--assets-dir");
  230. args.emplace_back (appContext.settings.general.assets.string ());
  231. }
  232. // the host reads the wallpaper's project on its own, so it only knows about property values that were passed on
  233. // the command line or through a hotswap request if they are handed to it again
  234. for (const auto& [name, value] : appContext.settings.general.properties) {
  235. args.emplace_back ("--set-property");
  236. args.emplace_back (name + "=" + value);
  237. }
  238. std::vector<char*> argv;
  239. argv.reserve (args.size () + 2);
  240. // cosmetic argv[0], the executable run is hostExecutable()
  241. argv.push_back (appContext.getArgv ()[0]);
  242. for (auto& arg : args) {
  243. argv.push_back (arg.data ());
  244. }
  245. argv.push_back (nullptr);
  246. execve (executable.c_str (), argv.data (), envp.data ());
  247. _exit (127);
  248. }
  249. this->m_hostPid = pid;
  250. if (hostSocket >= 0) {
  251. close (hostSocket);
  252. }
  253. }
  254. void CWeb::setAudioPolicy (bool muted, std::optional<int> ambientVolume) {
  255. if (this->m_shm == nullptr) {
  256. return;
  257. }
  258. const auto& appContext = this->getContext ().getApp ().getContext ();
  259. const int volume
  260. = muted || !appContext.settings.audio.enabled ? 0 : ambientVolume.value_or (appContext.state.audio.volume);
  261. this->m_shm->audioMuted.store (volume == 0, std::memory_order_relaxed);
  262. this->m_audioVolume = static_cast<float> (volume) / 128.0f;
  263. if (this->m_streamVolume) {
  264. this->m_streamVolume->setVolume (static_cast<float> (volume) / 128.0f);
  265. }
  266. }
  267. void CWeb::setSize (const int width, const int height) {
  268. this->m_width = width > 0 ? width : this->m_width;
  269. this->m_height = height > 0 ? height : this->m_height;
  270. if (this->m_width <= 0 || this->m_height <= 0) {
  271. return;
  272. }
  273. // clamped to the capacity, the host notices and calls WasResized()
  274. this->m_shm->desiredWidth.store (
  275. std::min (static_cast<uint32_t> (this->m_width), this->m_shmMaxWidth), std::memory_order_relaxed
  276. );
  277. this->m_shm->desiredHeight.store (
  278. std::min (static_cast<uint32_t> (this->m_height), this->m_shmMaxHeight), std::memory_order_relaxed
  279. );
  280. }
  281. void CWeb::renderFrame (const glm::ivec4& viewport) {
  282. LWE_ZONE ("web frame");
  283. if (!this->m_helperFailureLogged && this->m_shm->helperFailed.load (std::memory_order_relaxed)) {
  284. sLog.error ("CWeb: host process failed to start, this web wallpaper will not render");
  285. this->m_helperFailureLogged = true;
  286. }
  287. if (viewport.z != this->getWidth () || viewport.w != this->getHeight ()) {
  288. this->setSize (viewport.z, viewport.w);
  289. }
  290. this->updateMouse (this->cursorViewport ());
  291. this->updateMedia ();
  292. this->m_streamVolume->update ();
  293. glBindFramebuffer (GL_FRAMEBUFFER, this->getWallpaperFramebuffer ());
  294. glViewport (0, 0, this->getWidth (), this->getHeight ());
  295. if (this->m_frameMode == FrameMode::Dmabuf) {
  296. this->renderDmabufFrame ();
  297. return;
  298. }
  299. const auto taken = this->m_shm->takeFrame (this->m_frontSlot);
  300. if (!taken.has_value ()) {
  301. this->requestPageFrame ();
  302. return;
  303. }
  304. if (*taken >= WebHostSharedMemory::FRAME_SLOTS) {
  305. this->rejectFrame ();
  306. return;
  307. }
  308. this->m_frontSlot = *taken;
  309. const uint32_t frameWidth = this->m_shm->slotWidth[this->m_frontSlot].load (std::memory_order_relaxed);
  310. const uint32_t frameHeight = this->m_shm->slotHeight[this->m_frontSlot].load (std::memory_order_relaxed);
  311. if (frameWidth == 0 || frameHeight == 0) {
  312. this->requestPageFrame ();
  313. return;
  314. }
  315. if (!WebHostSharedMemory::frameFits (
  316. this->m_frontSlot, frameWidth, frameHeight, this->m_shmMaxWidth, this->m_shmMaxHeight
  317. )) {
  318. this->rejectFrame ();
  319. return;
  320. }
  321. uint8_t* const pixels = this->m_shm->frameBuffer (this->m_frontSlot, this->m_shmMaxWidth, this->m_shmMaxHeight);
  322. if (frameWidth != this->m_uploadedTextureWidth || frameHeight != this->m_uploadedTextureHeight) {
  323. this->find ("_rt_FullFrameBuffer")->resize (frameWidth, frameHeight);
  324. this->m_uploadedTextureWidth = frameWidth;
  325. this->m_uploadedTextureHeight = frameHeight;
  326. }
  327. glBindTexture (GL_TEXTURE_2D, this->getWallpaperTexture ());
  328. glTexSubImage2D (
  329. GL_TEXTURE_2D, 0, 0, 0, static_cast<GLsizei> (frameWidth), static_cast<GLsizei> (frameHeight), GL_BGRA_EXT,
  330. GL_UNSIGNED_BYTE, pixels
  331. );
  332. glBindTexture (GL_TEXTURE_2D, 0);
  333. if (!this->m_pageHasContent && frameHasContent (pixels, frameWidth, frameHeight)) {
  334. this->noteFirstContent ();
  335. }
  336. this->m_statsFrames++;
  337. // ask for the next frame only after taking this one, so what gets painted is always what the next render shows
  338. this->requestPageFrame ();
  339. }
  340. void CWeb::noteFirstContent () {
  341. this->m_pageHasContent = true;
  342. if (this->m_statsEnabled) {
  343. sLog.out (
  344. "CWeb host ", this->m_hostPid, ": first page content after ",
  345. std::chrono::duration_cast<std::chrono::milliseconds> (std::chrono::steady_clock::now () - this->m_created)
  346. .count (),
  347. "ms"
  348. );
  349. }
  350. }
  351. void CWeb::renderDmabufFrame () {
  352. LWE_ZONE ("web dmabuf import");
  353. using namespace std::chrono;
  354. bool closed = false;
  355. auto frame = WallpaperEngine::WebBrowser::IPC::receiveLatestDmabufFrame (
  356. this->m_dmabufSocket, this->m_shmMaxWidth, this->m_shmMaxHeight, closed
  357. );
  358. if (!frame.has_value ()) {
  359. if (this->m_shm->dmabufRejected.load (std::memory_order_acquire)) {
  360. this->fallBackToShm ("the browser's buffers have a format the engine cannot import");
  361. return;
  362. }
  363. if (this->m_dmabufFrames == 0 && this->m_shm->helperReady.load (std::memory_order_acquire)) {
  364. if (this->m_helperReadyAt == steady_clock::time_point {}) {
  365. this->m_helperReadyAt = steady_clock::now ();
  366. } else if (steady_clock::now () - this->m_helperReadyAt > seconds (6)) {
  367. this->fallBackToShm ("the browser made no GPU buffer");
  368. return;
  369. }
  370. }
  371. this->requestPageFrame ();
  372. return;
  373. }
  374. this->m_shm->dmabufTaken.store (frame->sequence, std::memory_order_release);
  375. if (frame->width != this->m_uploadedTextureWidth || frame->height != this->m_uploadedTextureHeight) {
  376. this->find ("_rt_FullFrameBuffer")->resize (frame->width, frame->height);
  377. this->m_uploadedTextureWidth = frame->width;
  378. this->m_uploadedTextureHeight = frame->height;
  379. }
  380. const bool copied = this->m_dmabufImport->copyTo (*frame, this->getWallpaperFramebuffer ());
  381. frame->closeAll ();
  382. if (!copied) {
  383. this->fallBackToShm ("a GPU buffer could not be imported");
  384. return;
  385. }
  386. if (++this->m_dmabufFrames == 1) {
  387. // the frame slots of the segment are not used in this mode
  388. WallpaperEngine::WebBrowser::IPC::setFrameSlotsResident (
  389. this->m_shmName, this->m_shmMaxWidth, this->m_shmMaxHeight, false
  390. );
  391. if (this->m_statsEnabled) {
  392. sLog.out ("CWeb host ", this->m_hostPid, ": frames arrive as dmabufs");
  393. }
  394. }
  395. if (!this->m_pageHasContent
  396. && this->m_dmabufImport->framebufferHasContent (
  397. this->getWallpaperFramebuffer (), frame->width, frame->height
  398. )) {
  399. this->noteFirstContent ();
  400. }
  401. this->m_statsFrames++;
  402. this->requestPageFrame ();
  403. }
  404. void CWeb::fallBackToShm (const char* reason) {
  405. sLog.out ("CWeb: dmabuf frames do not work here (", reason, "), restarting the web host with shared memory frames");
  406. this->m_frameMode = FrameMode::Shm;
  407. this->stopHost (false);
  408. this->m_dmabufImport.reset ();
  409. if (this->m_dmabufSocket >= 0) {
  410. close (this->m_dmabufSocket);
  411. this->m_dmabufSocket = -1;
  412. }
  413. auto& shm = *this->m_shm;
  414. shm.quitRequested.store (false, std::memory_order_release);
  415. shm.helperReady.store (false, std::memory_order_release);
  416. shm.helperFailed.store (false, std::memory_order_release);
  417. shm.dmabufRejected.store (false, std::memory_order_release);
  418. WallpaperEngine::WebBrowser::IPC::setFrameSlotsResident (
  419. this->m_shmName, this->m_shmMaxWidth, this->m_shmMaxHeight, true
  420. );
  421. this->m_helperReadyAt = {};
  422. this->m_helperFailureLogged = false;
  423. this->spawnHost (this->m_hostBackgroundPath);
  424. this->m_streamVolume = std::make_unique<Audio::Drivers::PulseProcessVolume> (this->m_hostPid);
  425. this->m_streamVolume->setVolume (this->m_audioVolume);
  426. this->requestPageFrame ();
  427. }
  428. bool CWeb::hasContent () const {
  429. constexpr auto patience = std::chrono::seconds (10);
  430. return this->m_pageHasContent || this->m_shm->helperFailed.load (std::memory_order_relaxed)
  431. || std::chrono::steady_clock::now () - this->m_created > patience;
  432. }
  433. void CWeb::rejectFrame () {
  434. if (!this->m_badFrameLogged) {
  435. sLog.error ("CWeb: the host published a frame that does not fit its shared memory, ignoring it");
  436. this->m_badFrameLogged = true;
  437. }
  438. this->requestPageFrame ();
  439. }
  440. void CWeb::requestPageFrame () {
  441. LWE_ZONE ("web begin frame request");
  442. const auto now = std::chrono::steady_clock::now ();
  443. if (this->m_lastRender != std::chrono::steady_clock::time_point {}) {
  444. const double interval = std::chrono::duration<double> (now - this->m_lastRender).count ();
  445. if (interval < 0.1) {
  446. this->m_renderInterval = WallpaperEngine::Data::Utils::isZero (this->m_renderInterval)
  447. ? interval
  448. : this->m_renderInterval * 0.95 + interval * 0.05;
  449. // renders per 60Hz frame, only switching once clearly closer to another whole number so a rate sitting
  450. // between two (90Hz) doesn't flip back and forth
  451. const double ratio = 1.0 / (this->m_renderInterval * 60.0);
  452. if (std::abs (ratio - this->m_frameRequestDivisor) > 0.65) {
  453. this->m_frameRequestDivisor = static_cast<uint32_t> (std::max (1L, std::lround (ratio)));
  454. }
  455. }
  456. }
  457. this->m_lastRender = now;
  458. if (this->m_statsEnabled) {
  459. this->m_statsRenders++;
  460. if (this->m_statsStart == std::chrono::steady_clock::time_point {}) {
  461. this->m_statsStart = now;
  462. } else if (
  463. const double elapsed = std::chrono::duration<double> (now - this->m_statsStart).count (); elapsed >= 5.0
  464. ) {
  465. sLog.out (
  466. "CWeb host ", this->m_hostPid, ": ", this->m_statsRenders / elapsed, " renders/s, ",
  467. this->m_statsFrames / elapsed, " page frames/s, one page frame every ", this->m_frameRequestDivisor,
  468. " render(s)"
  469. );
  470. this->m_statsStart = now;
  471. this->m_statsRenders = 0;
  472. this->m_statsFrames = 0;
  473. }
  474. }
  475. if (++this->m_rendersSinceRequest < this->m_frameRequestDivisor) {
  476. return;
  477. }
  478. this->m_rendersSinceRequest = 0;
  479. this->m_shm->requestFrame ();
  480. }
  481. namespace {
  482. // truncates to what fits, without leaving half of a multi byte character at the end
  483. void copyText (char* target, std::size_t capacity, const std::string& text) {
  484. std::size_t length = std::min (text.size (), capacity - 1);
  485. while (length > 0 && length < text.size () && (static_cast<unsigned char> (text[length]) & 0xC0) == 0x80) {
  486. length--;
  487. }
  488. std::memcpy (target, text.data (), length);
  489. target[length] = '\0';
  490. }
  491. }
  492. void CWeb::updateMedia () {
  493. const auto& info = this->getContext ().getMediaSource ().getMediaInfo ();
  494. const auto& last = this->m_lastMedia;
  495. if (this->m_mediaPublished && info.title == last.title && info.artist == last.artist && info.album == last.album
  496. && info.cover == last.cover && info.playbackState == last.playbackState && info.available == last.available
  497. && info.duration == last.duration && info.position == last.position) {
  498. return;
  499. }
  500. const bool coverChanged = !this->m_mediaPublished || info.cover != last.cover;
  501. const std::string coverPath = info.cover.has_value () ? info.cover->string () : "";
  502. Media::ThumbnailPalette palette;
  503. if (coverChanged) {
  504. this->m_coverVersion++;
  505. if (!coverPath.empty ()) {
  506. palette = Media::loadThumbnailPalette (coverPath);
  507. }
  508. }
  509. auto& shm = *this->m_shm;
  510. const uint32_t seq = shm.mediaSeq.load (std::memory_order_relaxed);
  511. shm.mediaSeq.store (seq + 1, std::memory_order_release);
  512. std::atomic_thread_fence (std::memory_order_seq_cst);
  513. shm.mediaState = static_cast<int32_t> (info.playbackState);
  514. shm.mediaAvailable = info.available;
  515. // MPRIS reports microseconds, pages are given seconds
  516. shm.mediaPosition = info.position / 1000000.0;
  517. shm.mediaDuration = info.duration / 1000000.0;
  518. copyText (shm.mediaTitle, WebHostSharedMemory::MEDIA_TEXT, info.title);
  519. copyText (shm.mediaArtist, WebHostSharedMemory::MEDIA_TEXT, info.artist);
  520. copyText (shm.mediaAlbum, WebHostSharedMemory::MEDIA_TEXT, info.album);
  521. if (coverChanged) {
  522. shm.mediaCoverVersion = this->m_coverVersion;
  523. copyText (shm.mediaCoverPath, WebHostSharedMemory::MEDIA_PATH, coverPath);
  524. const glm::vec3 colors[5]
  525. = { palette.primary, palette.secondary, palette.tertiary, palette.text, palette.highContrast };
  526. for (int i = 0; i < 5; i++) {
  527. for (int channel = 0; channel < 3; channel++) {
  528. shm.mediaPalette[i][channel]
  529. = static_cast<uint8_t> (std::clamp (colors[i][channel], 0.0f, 1.0f) * 255.0f + 0.5f);
  530. }
  531. }
  532. }
  533. std::atomic_thread_fence (std::memory_order_seq_cst);
  534. shm.mediaSeq.store (seq + 2, std::memory_order_release);
  535. this->m_lastMedia = info;
  536. this->m_mediaPublished = true;
  537. }
  538. void CWeb::updateMouse (const glm::ivec4& viewport) {
  539. const glm::dvec2 position = this->cursorPosition ();
  540. // GL y up to CEF y down; written every frame, the host only forwards clicks when the value changes
  541. const int x = std::clamp (static_cast<int> (position.x - viewport.x), 0, viewport.z);
  542. const int y = viewport.w - std::clamp (static_cast<int> (position.y - viewport.y), 0, viewport.w);
  543. this->m_shm->mouseX.store (static_cast<double> (x), std::memory_order_relaxed);
  544. this->m_shm->mouseY.store (static_cast<double> (y), std::memory_order_relaxed);
  545. this->m_shm->leftClick.store (static_cast<int32_t> (this->cursorLeftClick ()), std::memory_order_relaxed);
  546. this->m_shm->rightClick.store (static_cast<int32_t> (this->cursorRightClick ()), std::memory_order_relaxed);
  547. }
  548. CWeb::~CWeb () {
  549. // waits for a callback that's running right now, so the shared memory can be unmapped safely below
  550. this->m_spectrumRecorder->removeSpectrumListener (this->m_spectrumListenerId);
  551. this->stopHost (true);
  552. if (this->m_dmabufSocket >= 0) {
  553. close (this->m_dmabufSocket);
  554. }
  555. closeSharedMemory (this->m_shm, this->m_shmName, this->m_shmMaxWidth, this->m_shmMaxHeight, true);
  556. }
  557. void CWeb::stopHost (const bool graceful) {
  558. this->m_shm->quitRequested.store (true, std::memory_order_release);
  559. // let the host close CEF cleanly before killing it, bounded like the old embedded loop
  560. bool exited = false;
  561. const auto shutdownStart = std::chrono::steady_clock::now ();
  562. for (int i = 0; i < (graceful ? 500 : 50); i++) {
  563. int status = 0;
  564. if (waitpid (this->m_hostPid, &status, WNOHANG) == this->m_hostPid) {
  565. exited = true;
  566. break;
  567. }
  568. std::this_thread::sleep_for (std::chrono::milliseconds (10));
  569. }
  570. if (this->m_statsEnabled) {
  571. sLog.out (
  572. "CWeb host ", this->m_hostPid, exited ? " exited after " : " had to be killed after ",
  573. std::chrono::duration_cast<std::chrono::milliseconds> (std::chrono::steady_clock::now () - shutdownStart)
  574. .count (),
  575. "ms"
  576. );
  577. }
  578. if (!exited) {
  579. if (graceful) {
  580. sLog.error ("CWeb: web host ", this->m_hostPid, " did not shut down in time, killing it");
  581. }
  582. kill (this->m_hostPid, SIGKILL);
  583. waitpid (this->m_hostPid, nullptr, 0);
  584. }
  585. this->m_hostPid = -1;
  586. }
  587. void CWeb::setPropertyOverrides (const std::map<std::string, std::string>& overrides) {
  588. if (this->m_shm == nullptr) {
  589. return;
  590. }
  591. std::string text;
  592. for (const auto& [name, value] : overrides) {
  593. text += name + "=" + value + "\n";
  594. }
  595. if (text.size () >= WebHostSharedMemory::PROPERTIES_TEXT) {
  596. sLog.error (
  597. "Property overrides too long for the web host (", text.size (), " bytes), the page keeps its values"
  598. );
  599. return;
  600. }
  601. auto& shm = *this->m_shm;
  602. const uint32_t seq = shm.propertiesSeq.load (std::memory_order_relaxed);
  603. shm.propertiesSeq.store (seq + 1, std::memory_order_release);
  604. std::atomic_thread_fence (std::memory_order_seq_cst);
  605. copyText (shm.propertiesText, WebHostSharedMemory::PROPERTIES_TEXT, text);
  606. std::atomic_thread_fence (std::memory_order_seq_cst);
  607. shm.propertiesSeq.store (seq + 2, std::memory_order_release);
  608. }