r/CodingHelp • • Oct 25 '26

[C] I fail to comperhend what eglSwapBuffers does

Using OpenglES I made a simple piece of code:

// Source - https://stackoverflow.com/q/80012457
// Posted by Dimitrios Desyllas
// Retrieved 2026-10-25, License - CC BY-SA 4.0

#include <stdlib.h>
#include <fcntl.h>       
#include <unistd.h>
#include <stdio.h>

#define GLFW_INCLUDE_ES2

#include <drm.h>  
#include <drm_mode.h>  
#include <gbm.h>
#include <xf86drm.h>

#include "square.h"
#include "egl_init.h"
#include "drm_init.h"

int main(void)
{
    int drm_fd = open("/dev/dri/card0", O_RDWR);  
    struct gbm_device *gbm_dev = gbm_create_device(drm_fd);      
    struct gbm_surface *gbm_surf=NULL;

    puts("Get Connector \n");
    drmModeConnector *connector = getDRMConnector(drm_fd);
    if (!connector) {
        fprintf(stderr, "No connected DRM connector found\n");
        close(drm_fd);
        return 1;
    }

    drmModeModeInfo mode = connector->modes[0];

    unsigned int mode_w = mode.hdisplay;
    unsigned int mode_h = mode.vdisplay;

    puts("Get CRTC\n");

    drmModeCrtc *crtc = getDRMCrtc(drm_fd, connector);
    if (!crtc) {
        fprintf(stderr, "No compatible CRTC found\n");
        drmModeFreeConnector(connector);
        close(drm_fd);
        return 1;
    }

    puts("Initiaslize GBM display");

    EGLDisplay egl_display = initEGLDisplay(gbm_dev);
    if(egl_display == EGL_NO_DISPLAY){
        fprintf(stderr,"Unable to Initialize EGL display");
        return 1;
    }

    EGLConfig config;  
    EGLint num_configs;

    static const EGLint config_attribs[] = {  
        EGL_SURFACE_TYPE, EGL_WINDOW_BIT,  
        EGL_RED_SIZE, 8,
        EGL_GREEN_SIZE, 8, 
        EGL_BLUE_SIZE, 8, 
        EGL_ALPHA_SIZE, 8, 
        EGL_NONE
    };

    eglChooseConfig(egl_display, config_attribs, &config, 1, &num_configs);  

    puts("Initiaslize surface \n");
    EGLSurface egl_surface = initEGLSurface(gbm_dev,egl_display,config,mode_w,mode_h, &gbm_surf);

    if (egl_surface == EGL_NO_SURFACE) {
        fprintf(stderr, "Failed to create EGL surface\n");
        return 1;
    }

    if (!gbm_surf) {
        fprintf(stderr, "Failed to create GBM surface\n");
        return 1;
    }

    puts("Initiaslize context \n");
    EGLContext egl_context = initEGLContext(egl_display,config);
    eglMakeCurrent(egl_display, egl_surface, egl_surface, egl_context);  

    puts("Init program\n");
    GLuint program = createProgram();
    if (!program) {
        return 1;
    }

    uint32_t conn_id = connector->connector_id;
    uint32_t crtc_id = crtc->crtc_id;     
    DisplayFrame current = {0};

    puts("Draw Square\n");

    drawSquare(program, mode_w,mode_h);
    eglSwapBuffers(egl_display, egl_surface);
        
    if (displayRefresh( drm_fd, gbm_surf, crtc_id, conn_id, &mode, &current) != 0) {
        fprintf(stderr, "Display refresh failed\n");
        return 1;
    }

    puts("Framebuffer displayed");
    sleep(10);

    puts("Cleanup\n");

    eglDestroySurface(egl_display, egl_surface);  
    eglDestroyContext(egl_display, egl_context);  
    eglTerminate(egl_display);  
    gbm_device_destroy(gbm_dev);  
    close(drm_fd);

    return 0;
}

As I ask upon on stackoverflow as well I cannot understand rthe relationship between:

  • gbm_surface
  • EGLSurface
  • EGLDisplay

In my example I seperated the initialization of each egl component into a seprrate library egl_init.c:

#include "egl_init.h"

EGLDisplay initEGLDisplay(struct gbm_device *gbm_dev)
{
    PFNEGLGETPLATFORMDISPLAYEXTPROC getPlatformDisplay =(PFNEGLGETPLATFORMDISPLAYEXTPROC)eglGetProcAddress("eglGetPlatformDisplayEXT");

    if (!getPlatformDisplay) {
        return EGL_NO_DISPLAY;
    }

    EGLDisplay egl_display = getPlatformDisplay(EGL_PLATFORM_GBM_KHR,gbm_dev,NULL);

    if (egl_display == EGL_NO_DISPLAY) {
        return EGL_NO_DISPLAY;
    }

    if (!eglInitialize(egl_display, NULL, NULL)) {
        return EGL_NO_DISPLAY;
    }

    return egl_display;
}


EGLSurface initEGLSurface(struct gbm_device *gbm_dev,EGLDisplay display, EGLConfig config, unsigned int width, unsigned int height, struct gbm_surface **gbm_surf ){
    *gbm_surf = gbm_surface_create(gbm_dev, width, height, GBM_FORMAT_XRGB8888, GBM_BO_USE_RENDERING|GBM_BO_USE_SCANOUT);  
    return eglCreateWindowSurface(display, config, (EGLNativeWindowType)*gbm_surf, NULL);
}

EGLContext initEGLContext(EGLDisplay display, EGLConfig config){
    return eglCreateContext(display, config, EGL_NO_CONTEXT, (const EGLint[]){EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE});  
}

And same I do for gbm:

#include "drm_init.h"

drmModeConnector *getDRMConnector(int drm_fd)
{
    drmModeRes *resources = drmModeGetResources(drm_fd);

    if (!resources){
        return NULL;
    }

    drmModeConnector *connector = NULL;

    for (int i = 0; i < resources->count_connectors; i++) {
        drmModeConnector *candidate = drmModeGetConnector(drm_fd,resources->connectors[i]);

        if (!candidate){
            continue;
        }

        if (candidate->connection == DRM_MODE_CONNECTED && candidate->count_modes > 0) {
            connector = candidate;
            break;
        }

        drmModeFreeConnector(candidate);
    }

    drmModeFreeResources(resources);

    return connector;
}


drmModeCrtc *getDRMCrtc( int drm_fd, drmModeConnector *connector )
{
    if (!connector)
        return NULL;

    drmModeRes *resources = drmModeGetResources(drm_fd);

    if (!resources)
        return NULL;

    drmModeCrtc *crtc = NULL;

    for (int i = 0; i < connector->count_encoders && !crtc; i++) {
        drmModeEncoder *encoder = drmModeGetEncoder(
            drm_fd,
            connector->encoders[i]
        );

        if (!encoder)
            continue;

        for (int j = 0; j < resources->count_crtcs; j++) {
            if (encoder->possible_crtcs & (1u << j)) {
                crtc = drmModeGetCrtc(
                    drm_fd,
                    resources->crtcs[j]
                );

                if (crtc)
                    break;
            }
        }

        drmModeFreeEncoder(encoder);
    }

    drmModeFreeResources(resources);

    return crtc;
}



int displayRefresh(int drm_fd, struct gbm_surface *gbm_surf, uint32_t crtc_id, uint32_t conn_id,drmModeModeInfo *mode, DisplayFrame *current) {

    // 1. Lock the new front buffer
    struct gbm_bo *bo = gbm_surface_lock_front_buffer(gbm_surf);

    if (!bo) {
        return -1;
    }

    // 2. Get buffer information
    uint32_t handle = gbm_bo_get_handle(bo).u32;
    uint32_t pitch = gbm_bo_get_stride(bo);
    uint32_t width = gbm_bo_get_width(bo);
    uint32_t height = gbm_bo_get_height(bo);

    uint32_t fb_id = 0;

    // 3. Create DRM framebuffer
    int ret = drmModeAddFB(drm_fd,width,height,24,32,pitch,handle,&fb_id);

    if (ret != 0) {
        perror("drmModeAddFB");
        gbm_surface_release_buffer(gbm_surf, bo);
        return -1;
    }

    // 4. Display the framebuffer
    ret = drmModeSetCrtc(drm_fd,crtc_id,fb_id,0,0,&conn_id,1,mode);

    if (ret != 0) {
        perror("drmModeSetCrtc");
        drmModeRmFB(drm_fd, fb_id);
        gbm_surface_release_buffer(gbm_surf, bo);
        return -1;
    }

    // 5. Release the previous framebuffer
    if (current->bo) {
        drmModeRmFB(drm_fd, current->fb_id);
        gbm_surface_release_buffer(gbm_surf,current->bo);
    }

    // 6. Remember the currently displayed buffer
    current->bo = bo;
    current->fb_id = fb_id;

    return 0;
}

But int confuses me why I need to swap buffers via eglSwapBuffers. And once swapped buffers why I need to manually refresh the screen via locking the buffer and manually associating into crtc?

int displayRefresh(int drm_fd, struct gbm_surface *gbm_surf, uint32_t crtc_id, uint32_t conn_id,drmModeModeInfo *mode, DisplayFrame *current) {

    // 1. Lock the new front buffer
    struct gbm_bo *bo = gbm_surface_lock_front_buffer(gbm_surf);

    if (!bo) {
        return -1;
    }

    // 2. Get buffer information
    uint32_t handle = gbm_bo_get_handle(bo).u32;
    uint32_t pitch = gbm_bo_get_stride(bo);
    uint32_t width = gbm_bo_get_width(bo);
    uint32_t height = gbm_bo_get_height(bo);

    uint32_t fb_id = 0;

    // 3. Create DRM framebuffer
    int ret = drmModeAddFB(drm_fd,width,height,24,32,pitch,handle,&fb_id);

    if (ret != 0) {
        perror("drmModeAddFB");
        gbm_surface_release_buffer(gbm_surf, bo);
        return -1;
    }

    // 4. Display the framebuffer
    ret = drmModeSetCrtc(drm_fd,crtc_id,fb_id,0,0,&conn_id,1,mode);

    if (ret != 0) {
        perror("drmModeSetCrtc");
        drmModeRmFB(drm_fd, fb_id);
        gbm_surface_release_buffer(gbm_surf, bo);
        return -1;
    }

    // 5. Release the previous framebuffer
    if (current->bo) {
        drmModeRmFB(drm_fd, current->fb_id);
        gbm_surface_release_buffer(gbm_surf,current->bo);
    }

    // 6. Remember the currently displayed buffer
    current->bo = bo;
    current->fb_id = fb_id;

    return 0;
}

A googling let me into this website: https://registry.khronos.org/EGL/sdk/docs/man/html/eglSwapBuffers.xhtml

That confuses me even more on how wexplains the eglSwapBuffers on it:

If surface is a back-buffered window surface, then the color buffer is copied (posted) to the native window associated with that surface. If surface is a single-buffered window, pixmap, or pixel buffer surface, eglSwapBuffers has no effect.

The contents of ancillary buffers are always undefined after calling eglSwapBuffers. The contents of the color buffer are undefined if the value of the EGL_SWAP_BEHAVIOR attribute of surface is not EGL_BUFFER_PRESERVED. The value of EGL_SWAP_BEHAVIOR can be set for some surfaces using eglSurfaceAttrib. EGL_SWAP_BEHAVIOR applies only to the color buffer. EGL has no way to specify or query whether or not ancillary buffers are preserved, and applications should not rely on this behavior.

eglSwapBuffers performs an implicit flush operation on the context (glFlush for an OpenGL ES or OpenGL context, vgFlush for an OpenVG context) bound to surface before swapping. Subsequent client API commands may be issued on that context immediately after calling eglSwapBuffers, but are not executed until the buffer exchange is completed.

3 Upvotes

3 comments sorted by

•

u/AutoModerator Oct 25 '26

Thank you for posting on r/CodingHelp!

Please check our Wiki for answers, guides, and FAQs: https://coding-help.vercel.app

Our Wiki is open source - if you would like to contribute, create a pull request via GitHub! https://github.com/DudeThatsErin/CodingHelp

We are accepting moderator applications: https://forms.fillout.com/t/ua41TU57DGus

We also have a Discord server: https://discord.gg/geQEUBm

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

1

u/gofuckadick Oct 26 '26

The thing that seems to be confusing you is that eglSwapBuffers() and drmModeSetCrtc() are doing two different things, at two different stages of the process. Think of it like drawing a picture and putting it on a screen. Finishing the picture and making it available doesn't automatically mean the screen is displaying it.

When you call eglSwapBuffers(), you're telling EGL that you're finished rendering the current frame. EGL presents that frame to the underlying GBM surface, making it available as a completed buffer. But that doesn't tell the display hardware to actually show it.

That's why you still need the other calls:

  • gbm_surface_lock_front_buffer() gets the completed buffer from GBM and locks it so GBM won't reuse it until you release it.
  • drmModeAddFB() registers that buffer as a framebuffer that DRM/KMS can use.
  • drmModeSetCrtc() tells the display controller to scan out that framebuffer to the monitor.

The reason you have to do both manually is that you're using DRM/KMS directly, without a window system or compositor handling the final display step for you. In a normal desktop application, the window system takes care of getting completed frames onto the screen. In your code, you're responsible for that yourself.

And to clarify the relationship between your objects:

  • EGLDisplay is your connection to the EGL graphics platform, initialized using the GBM device.
  • EGLSurface is the rendering surface OpenGL draws into.
  • gbm_surface manages the underlying buffers used by that EGL surface.

Swapping the rendering buffers doesn't automatically change which framebuffer the physical display is scanning out. That's what your DRM/KMS calls are for.

So the simplest way to think about it is:

eglSwapBuffers() = "My next frame is ready."

drmModeSetCrtc() = "Display this frame on the monitor."

They're two different stages of the same process, not two ways of doing the same thing.

Let me know if this helps make sense of it for you.

0

u/mredding Oct 26 '26

This is typical double-buffering. You draw to a back-buffer off screen, then swap it wholly and completely with the front-buffer, so now your back-buffer IS your front buffer to be rendered, and the old front-buffer is the new back-buffer to be drawn.

Why not render directly to the active screen buffer? Buffer sheering, and other render artifacts become visible. You can SEE the render happen. Even if you're rendering 60 FPS, you're going to see artifacts.