SDL: wayland: Add framebuffer vsync support

From a04d5cfb57a19da0c9577ab74e7a149fc74280b3 Mon Sep 17 00:00:00 2001
From: Frank Praznik <[EMAIL REDACTED]>
Date: Fri, 23 Oct 2026 10:59:15 -0400
Subject: [PATCH] wayland: Add framebuffer vsync support

Factor the frame callback wait code out of the EGL backend, and use it to implement framebuffer vsync as well.
---
 src/video/wayland/SDL_waylandframebuffer.c | 130 ++++++++++++++++++---
 src/video/wayland/SDL_waylandframebuffer.h |   4 +
 src/video/wayland/SDL_waylandopengles.c    |  45 +------
 src/video/wayland/SDL_waylandvideo.c       |   2 +
 src/video/wayland/SDL_waylandwindow.c      |  65 ++---------
 src/video/wayland/SDL_waylandwindow.h      |  15 ++-
 6 files changed, 145 insertions(+), 116 deletions(-)

diff --git a/src/video/wayland/SDL_waylandframebuffer.c b/src/video/wayland/SDL_waylandframebuffer.c
index 07bd9aee74fb2..613c0f94f5c4f 100644
--- a/src/video/wayland/SDL_waylandframebuffer.c
+++ b/src/video/wayland/SDL_waylandframebuffer.c
@@ -20,6 +20,7 @@
 */
 
 #include "SDL_waylandframebuffer.h"
+#include "../../core/unix/SDL_poll.h"
 #include "SDL_waylandshmbuffer.h"
 #include "SDL_waylandwindow.h"
 
@@ -36,8 +37,8 @@ struct Wayland_Framebuffer
 {
     Wayland_Buffer buffer[BUFFER_COUNT];
     Wayland_SHMPool *pool;
-    struct wl_event_queue *queue;
     void *pixels;
+    bool vsync;
 };
 
 static void buffer_handle_release(void *data, struct wl_buffer *wl_buffer)
@@ -46,10 +47,108 @@ static void buffer_handle_release(void *data, struct wl_buffer *wl_buffer)
     buffer->busy = false;
 }
 
-static struct wl_buffer_listener buffer_listener = {
+static const struct wl_buffer_listener buffer_listener = {
     buffer_handle_release
 };
 
+static const struct wl_callback_listener swap_frame_listener;
+
+static void swap_frame_done(void *data, struct wl_callback *cb, uint32_t time)
+{
+    SDL_WindowData *wind = (SDL_WindowData *)data;
+    SDL_SetAtomicInt(&wind->presentation.swap_interval_ready, 1); // Mark window as ready to present again.
+
+    // Reset this callback to fire again once a new frame was presented and the compositor wants the next one.
+    wind->presentation.frame_callback = wl_surface_frame(wind->presentation.surface_wrapper);
+    wl_callback_destroy(cb);
+    wl_callback_add_listener(wind->presentation.frame_callback, &swap_frame_listener, data);
+}
+
+static const struct wl_callback_listener swap_frame_listener = {
+    swap_frame_done
+};
+
+static void CreatePresentationQueue(SDL_WindowData *wind)
+{
+    if (!wind->presentation.queue) {
+        wind->presentation.queue = Wayland_DisplayCreateQueue(wind->waylandData->display, "SDL Surface Presentation Queue");
+        wind->presentation.surface_wrapper = WAYLAND_wl_proxy_create_wrapper(wind->surface);
+        WAYLAND_wl_proxy_set_queue((struct wl_proxy *)wind->presentation.surface_wrapper, wind->presentation.queue);
+    }
+}
+
+void Wayland_WaitForSwapInterval(SDL_WindowData *wind)
+{
+    SDL_VideoData *videodata = wind->waylandData;
+
+    if (!wind->presentation.frame_callback) {
+        CreatePresentationQueue(wind);
+        wind->presentation.frame_callback = wl_surface_frame(wind->presentation.surface_wrapper);
+        wl_callback_add_listener(wind->presentation.frame_callback, &swap_frame_listener, wind);
+    } else if (wind->shell_surface_status == WAYLAND_SHELL_SURFACE_STATUS_SHOWN) {
+        // 20hz, so we'll progress even if throttled to zero.
+        const Uint64 max_wait = SDL_GetTicksNS() + (SDL_NS_PER_SECOND / 20);
+        while (SDL_GetAtomicInt(&wind->presentation.swap_interval_ready) == 0) {
+            WAYLAND_wl_display_flush(videodata->display);
+
+            /* wl_display_prepare_read_queue() will return false if the event queue is not empty.
+             * If the event queue is empty, it will prepare us for our SDL_IOReady() call.
+             */
+            if (WAYLAND_wl_display_prepare_read_queue(videodata->display, wind->presentation.queue) != 0) {
+                // We have some pending events. Check if the frame callback happened.
+                WAYLAND_wl_display_dispatch_queue_pending(videodata->display, wind->presentation.queue);
+                continue;
+            }
+
+            // Beyond this point, we must either call wl_display_cancel_read() or wl_display_read_events()
+            const Uint64 now = SDL_GetTicksNS();
+            if (now >= max_wait) {
+                // Timeout expired. Cancel the read.
+                WAYLAND_wl_display_cancel_read(videodata->display);
+                break;
+            }
+
+            if (SDL_IOReady(WAYLAND_wl_display_get_fd(videodata->display), SDL_IOR_READ, max_wait - now) <= 0) {
+                // Error or timeout expired without any events for us. Cancel the read.
+                WAYLAND_wl_display_cancel_read(videodata->display);
+                break;
+            }
+
+            // We have events. Read and dispatch them.
+            WAYLAND_wl_display_read_events(videodata->display);
+            WAYLAND_wl_display_dispatch_queue_pending(videodata->display, wind->presentation.queue);
+        }
+        SDL_SetAtomicInt(&wind->presentation.swap_interval_ready, 0);
+    }
+}
+
+bool Wayland_SetWindowFramebufferVSync(SDL_VideoDevice *_this, SDL_Window *window, int vsync)
+{
+    SDL_WindowData *wind = window->internal;
+    if (!wind->framebuffer) {
+        SDL_SetError("No window framebuffer");
+    }
+    if (vsync < 0) {
+        return SDL_SetError("Unsupported vsync type");
+    }
+
+    wind->framebuffer->vsync = vsync > 0;
+    return true;
+}
+
+bool Wayland_GetWindowFramebufferVSync(SDL_VideoDevice *_this, SDL_Window *window, int *vsync)
+{
+    SDL_WindowData *wind = window->internal;
+    if (!wind->framebuffer) {
+        SDL_SetError("No window framebuffer");
+    }
+
+    if (vsync) {
+        *vsync = (int)wind->framebuffer->vsync;
+    }
+    return true;
+}
+
 bool Wayland_CreateWindowFramebuffer(SDL_VideoDevice *_this, SDL_Window *window, SDL_PixelFormat *format, void **pixels, int *pitch)
 {
     SDL_WindowData *wind = window->internal;
@@ -75,10 +174,13 @@ bool Wayland_CreateWindowFramebuffer(SDL_VideoDevice *_this, SDL_Window *window,
         goto failed;
     }
 
-    framebuffer->queue = Wayland_DisplayCreateQueue(_this->internal->display, "Wayland Framebuffer Queue");
+    CreatePresentationQueue(wind);
+
     for (int i = 0; i < BUFFER_COUNT; ++i) {
         framebuffer->buffer[i].wl_buffer = Wayland_AllocBufferFromPool(framebuffer->pool, w, h, &framebuffer->buffer[i].mem);
-        WAYLAND_wl_proxy_set_queue((struct wl_proxy *)framebuffer->buffer[i].wl_buffer, framebuffer->queue);
+
+        // This isn't racy, as the only buffer event is a release, which is only sent after the buffer is attached.
+        WAYLAND_wl_proxy_set_queue((struct wl_proxy *)framebuffer->buffer[i].wl_buffer, wind->presentation.queue);
         wl_buffer_add_listener(framebuffer->buffer[i].wl_buffer, &buffer_listener, &framebuffer->buffer[i]);
     }
 
@@ -99,9 +201,6 @@ bool Wayland_CreateWindowFramebuffer(SDL_VideoDevice *_this, SDL_Window *window,
     }
 
     Wayland_ReleaseSHMPool(framebuffer->pool);
-    if (framebuffer->queue) {
-        WAYLAND_wl_event_queue_destroy(framebuffer->queue);
-    }
     SDL_free(framebuffer->pixels);
     SDL_free(framebuffer);
 
@@ -114,8 +213,10 @@ bool Wayland_UpdateWindowFramebuffer(SDL_VideoDevice *_this, SDL_Window *window,
     SDL_WindowData *wind = window->internal;
     Wayland_Framebuffer *framebuffer = wind->framebuffer;
 
-    // Process any queued buffer release events.
-    WAYLAND_wl_display_dispatch_queue_pending(viddata->display, framebuffer->queue);
+    // Process the presentation queue, as a buffer release event may have already occurred.
+    if (WAYLAND_wl_display_dispatch_queue_pending(viddata->display, wind->presentation.queue) < 0) {
+        return false;
+    }
 
     // Find a free buffer.
     Wayland_Buffer *buffer = NULL;
@@ -131,10 +232,10 @@ bool Wayland_UpdateWindowFramebuffer(SDL_VideoDevice *_this, SDL_Window *window,
             break;
         }
 
-        /* If nothing is free, wait for a buffer release event.
-         * Not all compositors flush on a release event, so use roundtrips, as they cause a flush.
+        /* If there are no free buffers, wait for a buffer release event.
+         * Not all compositors flush on a release event, so round trips are used, as they cause a flush.
          */
-        if (WAYLAND_wl_display_roundtrip_queue(viddata->display, framebuffer->queue) < 0) {
+        if (WAYLAND_wl_display_roundtrip_queue(viddata->display, wind->presentation.queue) < 0) {
             return false;
         }
     }
@@ -142,6 +243,10 @@ bool Wayland_UpdateWindowFramebuffer(SDL_VideoDevice *_this, SDL_Window *window,
     // Copy the image data.
     SDL_memcpy(buffer->mem, framebuffer->pixels, wind->current.pixel_width * wind->current.pixel_height * 4);
 
+    if (framebuffer->vsync) {
+        Wayland_WaitForSwapInterval(wind);
+    }
+
     // Attach the buffer and commit the surface.
     buffer->busy = true;
     wl_surface_attach(wind->surface, buffer->wl_buffer, 0, 0);
@@ -172,7 +277,6 @@ void Wayland_DestroyWindowFramebuffer(SDL_VideoDevice *_this, SDL_Window *window
     }
 
     Wayland_ReleaseSHMPool(framebuffer->pool);
-    WAYLAND_wl_event_queue_destroy(framebuffer->queue);
     SDL_free(framebuffer->pixels);
     SDL_free(framebuffer);
 }
diff --git a/src/video/wayland/SDL_waylandframebuffer.h b/src/video/wayland/SDL_waylandframebuffer.h
index 06389333b044d..c98e76ff1d7f3 100644
--- a/src/video/wayland/SDL_waylandframebuffer.h
+++ b/src/video/wayland/SDL_waylandframebuffer.h
@@ -28,8 +28,12 @@
 
 typedef struct Wayland_Framebuffer Wayland_Framebuffer;
 
+extern void Wayland_WaitForSwapInterval(SDL_WindowData *wind);
+
 extern bool Wayland_CreateWindowFramebuffer(SDL_VideoDevice *_this, SDL_Window *window, SDL_PixelFormat *format, void **pixels, int *pitch);
 extern bool Wayland_UpdateWindowFramebuffer(SDL_VideoDevice *_this, SDL_Window *window, const SDL_Rect *rects, int numrects);
 extern void Wayland_DestroyWindowFramebuffer(SDL_VideoDevice *_this, SDL_Window *window);
+extern bool Wayland_SetWindowFramebufferVSync(SDL_VideoDevice *_this, SDL_Window *window, int vsync);
+extern bool Wayland_GetWindowFramebufferVSync(SDL_VideoDevice *_this, SDL_Window *window, int *vsync);
 
 #endif // SDL_waylandframebuffer_h_
diff --git a/src/video/wayland/SDL_waylandopengles.c b/src/video/wayland/SDL_waylandopengles.c
index 08ced0e6f39ac..89a400553b9b0 100644
--- a/src/video/wayland/SDL_waylandopengles.c
+++ b/src/video/wayland/SDL_waylandopengles.c
@@ -22,15 +22,12 @@
 
 #if defined(SDL_VIDEO_DRIVER_WAYLAND) && defined(SDL_VIDEO_OPENGL_EGL)
 
-#include "../../core/unix/SDL_poll.h"
 #include "../SDL_sysvideo.h"
-#include "../../events/SDL_windowevents_c.h"
 #include "SDL_waylandvideo.h"
 #include "SDL_waylandopengles.h"
 #include "SDL_waylandwindow.h"
 #include "SDL_waylandevents_c.h"
-
-#include "xdg-shell-client-protocol.h"
+#include "SDL_waylandframebuffer.h"
 
 #ifndef EGL_PLATFORM_WAYLAND_KHR
 #define EGL_PLATFORM_WAYLAND_KHR 0x31D8
@@ -142,44 +139,8 @@ bool Wayland_GLES_SwapWindow(SDL_VideoDevice *_this, SDL_Window *window)
     }
 
     // Control swap interval ourselves. See comments on Wayland_GLES_SetSwapInterval
-    if (swap_interval != 0 && data->shell_surface_status == WAYLAND_SHELL_SURFACE_STATUS_SHOWN) {
-        SDL_VideoData *videodata = _this->internal;
-        struct wl_display *display = videodata->display;
-        // 20hz, so we'll progress even if throttled to zero.
-        const Uint64 max_wait = SDL_GetTicksNS() + (SDL_NS_PER_SECOND / 20);
-        while (SDL_GetAtomicInt(&data->swap_interval_ready) == 0) {
-            Uint64 now;
-
-            WAYLAND_wl_display_flush(display);
-
-            /* wl_display_prepare_read_queue() will return false if the event queue is not empty.
-             * If the event queue is empty, it will prepare us for our SDL_IOReady() call. */
-            if (WAYLAND_wl_display_prepare_read_queue(display, data->gles_swap_frame_event_queue) != 0) {
-                // We have some pending events. Check if the frame callback happened.
-                WAYLAND_wl_display_dispatch_queue_pending(display, data->gles_swap_frame_event_queue);
-                continue;
-            }
-
-            // Beyond this point, we must either call wl_display_cancel_read() or wl_display_read_events()
-
-            now = SDL_GetTicksNS();
-            if (now >= max_wait) {
-                // Timeout expired. Cancel the read.
-                WAYLAND_wl_display_cancel_read(display);
-                break;
-            }
-
-            if (SDL_IOReady(WAYLAND_wl_display_get_fd(display), SDL_IOR_READ, max_wait - now) <= 0) {
-                // Error or timeout expired without any events for us. Cancel the read.
-                WAYLAND_wl_display_cancel_read(display);
-                break;
-            }
-
-            // We have events. Read and dispatch them.
-            WAYLAND_wl_display_read_events(display);
-            WAYLAND_wl_display_dispatch_queue_pending(display, data->gles_swap_frame_event_queue);
-        }
-        SDL_SetAtomicInt(&data->swap_interval_ready, 0);
+    if (swap_interval != 0) {
+        Wayland_WaitForSwapInterval(data);
     }
 
     if (!data->double_buffer) {
diff --git a/src/video/wayland/SDL_waylandvideo.c b/src/video/wayland/SDL_waylandvideo.c
index 8ac21c9739d8a..45ca3df3f3b20 100644
--- a/src/video/wayland/SDL_waylandvideo.c
+++ b/src/video/wayland/SDL_waylandvideo.c
@@ -762,6 +762,8 @@ static SDL_VideoDevice *Wayland_CreateDevice(bool require_preferred_protocols)
     device->CreateWindowFramebuffer = Wayland_CreateWindowFramebuffer;
     device->UpdateWindowFramebuffer = Wayland_UpdateWindowFramebuffer;
     device->DestroyWindowFramebuffer = Wayland_DestroyWindowFramebuffer;
+    device->SetWindowFramebufferVSync = Wayland_SetWindowFramebufferVSync;
+    device->GetWindowFramebufferVSync = Wayland_GetWindowFramebufferVSync;
 
 #ifdef SDL_VIDEO_VULKAN
     device->Vulkan_LoadLibrary = Wayland_Vulkan_LoadLibrary;
diff --git a/src/video/wayland/SDL_waylandwindow.c b/src/video/wayland/SDL_waylandwindow.c
index 81d7ffb0802db..6d113b9d5218f 100644
--- a/src/video/wayland/SDL_waylandwindow.c
+++ b/src/video/wayland/SDL_waylandwindow.c
@@ -958,23 +958,6 @@ static const struct wl_callback_listener surface_frame_listener = {
     surface_frame_done
 };
 
-static const struct wl_callback_listener gles_swap_frame_listener;
-
-static void gles_swap_frame_done(void *data, struct wl_callback *cb, uint32_t time)
-{
-    SDL_WindowData *wind = (SDL_WindowData *)data;
-    SDL_SetAtomicInt(&wind->swap_interval_ready, 1); // mark window as ready to present again.
-
-    // reset this callback to fire again once a new frame was presented and compositor wants the next one.
-    wind->gles_swap_frame_callback = wl_surface_frame(wind->gles_swap_frame_surface_wrapper);
-    wl_callback_destroy(cb);
-    wl_callback_add_listener(wind->gles_swap_frame_callback, &gles_swap_frame_listener, data);
-}
-
-static const struct wl_callback_listener gles_swap_frame_listener = {
-    gles_swap_frame_done
-};
-
 static void handle_xdg_surface_configure(void *data, struct xdg_surface *xdg, uint32_t serial)
 {
     SDL_WindowData *wind = (SDL_WindowData *)data;
@@ -3112,14 +3095,6 @@ bool Wayland_ReconfigureWindow(SDL_VideoDevice *_this, SDL_Window *window, SDL_W
             return false; // SDL_EGL_CreateSurface should have set the error.
         }
 #endif
-
-        if (!data->gles_swap_frame_event_queue) {
-            data->gles_swap_frame_event_queue = WAYLAND_wl_display_create_queue(data->waylandData->display);
-            data->gles_swap_frame_surface_wrapper = WAYLAND_wl_proxy_create_wrapper(data->surface);
-            WAYLAND_wl_proxy_set_queue((struct wl_proxy *)data->gles_swap_frame_surface_wrapper, data->gles_swap_frame_event_queue);
-            data->gles_swap_frame_callback = wl_surface_frame(data->gles_swap_frame_surface_wrapper);
-            wl_callback_add_listener(data->gles_swap_frame_callback, &gles_swap_frame_listener, data);
-        }
     } else {
 #ifdef SDL_VIDEO_OPENGL_EGL
         if (data->egl_surface) {
@@ -3132,21 +3107,6 @@ bool Wayland_ReconfigureWindow(SDL_VideoDevice *_this, SDL_Window *window, SDL_W
             WAYLAND_wl_egl_window_destroy(data->egl_window);
             data->egl_window = NULL;
         }
-
-        if (data->gles_swap_frame_callback) {
-            wl_callback_destroy(data->gles_swap_frame_callback);
-            data->gles_swap_frame_callback = NULL;
-        }
-
-        if (data->gles_swap_frame_surface_wrapper) {
-            WAYLAND_wl_proxy_wrapper_destroy(data->gles_swap_frame_surface_wrapper);
-            data->gles_swap_frame_surface_wrapper = NULL;
-        }
-
-        if (data->gles_swap_frame_event_queue) {
-            WAYLAND_wl_event_queue_destroy(data->gles_swap_frame_event_queue);
-            data->gles_swap_frame_event_queue = NULL;
-        }
     }
 
     return true;
@@ -3265,19 +3225,6 @@ bool Wayland_CreateWindow(SDL_VideoDevice *_this, SDL_Window *window, SDL_Proper
     // Must be called before EGL configuration to set the drawable backbuffer size.
     ConfigureWindowGeometry(window);
 
-    /* Fire a callback when the compositor wants a new frame rendered.
-     * Right now this only matters for OpenGL; we use this callback to add a
-     * wait timeout that avoids getting deadlocked by the compositor when the
-     * window isn't visible.
-     */
-    if (window->flags & SDL_WINDOW_OPENGL) {
-        data->gles_swap_frame_event_queue = WAYLAND_wl_display_create_queue(data->waylandData->display);
-        data->gles_swap_frame_surface_wrapper = WAYLAND_wl_proxy_create_wrapper(data->surface);
-        WAYLAND_wl_proxy_set_queue((struct wl_proxy *)data->gles_swap_frame_surface_wrapper, data->gles_swap_frame_event_queue);
-        data->gles_swap_frame_callback = wl_surface_frame(data->gles_swap_frame_surface_wrapper);
-        wl_callback_add_listener(data->gles_swap_frame_callback, &gles_swap_frame_listener, data);
-    }
-
     if (window->flags & SDL_WINDOW_TRANSPARENT) {
         if (_this->gl_config.alpha_size == 0) {
             _this->gl_config.alpha_size = 8;
@@ -3901,10 +3848,14 @@ void Wayland_DestroyWindow(SDL_VideoDevice *_this, SDL_Window *window)
         SDL_free(wind->outputs);
         SDL_free(wind->app_id);
 
-        if (wind->gles_swap_frame_callback) {
-            wl_callback_destroy(wind->gles_swap_frame_callback);
-            WAYLAND_wl_proxy_wrapper_destroy(wind->gles_swap_frame_surface_wrapper);
-            WAYLAND_wl_event_queue_destroy(wind->gles_swap_frame_event_queue);
+        if (wind->presentation.frame_callback) {
+            wl_callback_destroy(wind->presentation.frame_callback);
+        }
+        if (wind->presentation.surface_wrapper) {
+            WAYLAND_wl_proxy_wrapper_destroy(wind->presentation.surface_wrapper);
+        }
+        if (wind->presentation.queue) {
+            WAYLAND_wl_event_queue_destroy(wind->presentation.queue);
         }
 
         if (!(window->flags & SDL_WINDOW_EXTERNAL)) {
diff --git a/src/video/wayland/SDL_waylandwindow.h b/src/video/wayland/SDL_waylandwindow.h
index e22bd0e5861e0..64ae2742f7492 100644
--- a/src/video/wayland/SDL_waylandwindow.h
+++ b/src/video/wayland/SDL_waylandwindow.h
@@ -35,9 +35,6 @@ struct SDL_WindowData
     SDL_Window *sdlwindow;
     SDL_VideoData *waylandData;
     struct wl_surface *surface;
-    struct wl_callback *gles_swap_frame_callback;
-    struct wl_event_queue *gles_swap_frame_event_queue;
-    struct wl_surface *gles_swap_frame_surface_wrapper;
     struct wl_callback *surface_frame_callback;
 
     union
@@ -67,6 +64,7 @@ struct SDL_WindowData
             Uint32 serial;
         } xdg;
     } shell_surface;
+
     enum
     {
         WAYLAND_SHELL_SURFACE_TYPE_UNKNOWN = 0,
@@ -75,6 +73,7 @@ struct SDL_WindowData
         WAYLAND_SHELL_SURFACE_TYPE_LIBDECOR,
         WAYLAND_SHELL_SURFACE_TYPE_CUSTOM
     } shell_surface_type;
+
     enum
     {
         WAYLAND_SHELL_SURFACE_STATUS_HIDDEN = 0,
@@ -83,6 +82,7 @@ struct SDL_WindowData
         WAYLAND_SHELL_SURFACE_STATUS_SHOW_PENDING,
         WAYLAND_SHELL_SURFACE_STATUS_SHOWN
     } shell_surface_status;
+
     enum
     {
         WAYLAND_WM_CAPS_WINDOW_MENU = 0x01,
@@ -95,6 +95,7 @@ struct SDL_WindowData
                               WAYLAND_WM_CAPS_FULLSCREEN |
                               WAYLAND_WM_CAPS_MINIMIZE
     } wm_caps;
+
     enum
     {
         WAYLAND_TOPLEVEL_CONSTRAINED_LEFT = 0x01,
@@ -130,7 +131,13 @@ struct SDL_WindowData
     struct Wayland_ColorInfoState *color_info_state;
     struct Wayland_Framebuffer *framebuffer;
 
-    SDL_AtomicInt swap_interval_ready;
+    struct
+    {
+        struct wl_callback *frame_callback;
+        struct wl_event_queue *queue;
+        struct wl_surface *surface_wrapper;
+        SDL_AtomicInt swap_interval_ready;
+    } presentation;
 
     SDL_DisplayData **outputs;
     int num_outputs;