egl_gbm_backend.cpp 19.2 KB
Newer Older
Vlad Zahorodnii's avatar
Vlad Zahorodnii committed
1 2 3
/*
    KWin - the KDE window manager
    This file is part of the KDE project.
4

Vlad Zahorodnii's avatar
Vlad Zahorodnii committed
5
    SPDX-FileCopyrightText: 2015 Martin Gräßlin <mgraesslin@kde.org>
6

Vlad Zahorodnii's avatar
Vlad Zahorodnii committed
7 8
    SPDX-License-Identifier: GPL-2.0-or-later
*/
9 10 11 12
#include "egl_gbm_backend.h"
// kwin
#include "composite.h"
#include "drm_backend.h"
13
#include "drm_output.h"
14
#include "gbm_surface.h"
15
#include "logging.h"
16 17 18 19
#include "options.h"
#include "screens.h"
// kwin libs
#include <kwinglplatform.h>
20
#include <kwineglimagetexture.h>
21 22 23 24 25 26
// system
#include <gbm.h>

namespace KWin
{

27
EglGbmBackend::EglGbmBackend(DrmBackend *drmBackend)
28
    : AbstractEglBackend()
29
    , m_backend(drmBackend)
30
{
31
    // Egl is always direct rendering.
32
    setIsDirectRendering(true);
33
    setSyncsToVBlank(true);
34
    connect(m_backend, &DrmBackend::outputAdded, this, &EglGbmBackend::createOutput);
35
    connect(m_backend, &DrmBackend::outputRemoved, this, &EglGbmBackend::removeOutput);
36 37 38 39 40 41 42
}

EglGbmBackend::~EglGbmBackend()
{
    cleanup();
}

43 44
void EglGbmBackend::cleanupSurfaces()
{
45
    for (auto it = m_outputs.begin(); it != m_outputs.end(); ++it) {
46 47
        cleanupOutput(*it);
    }
48
    m_outputs.clear();
49 50
}

51
void EglGbmBackend::cleanupFramebuffer(Output &output)
52
{
53 54 55 56 57 58 59 60 61 62 63 64
    if (!output.render.framebuffer) {
        return;
    }
    glDeleteTextures(1, &output.render.texture);
    output.render.texture = 0;
    glDeleteFramebuffers(1, &output.render.framebuffer);
    output.render.framebuffer = 0;
}

void EglGbmBackend::cleanupOutput(Output &output)
{
    cleanupFramebuffer(output);
65
    output.output->releaseGbm();
66

67 68
    if (output.eglSurface != EGL_NO_SURFACE) {
        eglDestroySurface(eglDisplay(), output.eglSurface);
69
    }
70 71
}

72 73 74
bool EglGbmBackend::initializeEgl()
{
    initClientExtensions();
75
    EGLDisplay display = m_backend->sceneEglDisplay();
76 77 78

    // Use eglGetPlatformDisplayEXT() to get the display pointer
    // if the implementation supports it.
79
    if (display == EGL_NO_DISPLAY) {
80 81 82 83
        const bool hasMesaGBM = hasClientExtension(QByteArrayLiteral("EGL_MESA_platform_gbm"));
        const bool hasKHRGBM = hasClientExtension(QByteArrayLiteral("EGL_KHR_platform_gbm"));
        const GLenum platform = hasMesaGBM ? EGL_PLATFORM_GBM_MESA : EGL_PLATFORM_GBM_KHR;

84
        if (!hasClientExtension(QByteArrayLiteral("EGL_EXT_platform_base")) ||
85
                (!hasMesaGBM && !hasKHRGBM)) {
86 87
            setFailed("Missing one or more extensions between EGL_EXT_platform_base, "
                      "EGL_MESA_platform_gbm, EGL_KHR_platform_gbm");
88 89
            return false;
        }
90

91 92
        auto device = gbm_create_device(m_backend->fd());
        if (!device) {
93 94 95
            setFailed("Could not create gbm device");
            return false;
        }
96
        m_backend->setGbmDevice(device);
97

98
        display = eglGetPlatformDisplayEXT(platform, device, nullptr);
99
    }
100

101
    if (display == EGL_NO_DISPLAY) {
102
        return false;
103
    }
104 105 106 107 108 109
    setEglDisplay(display);
    return initEglAPI();
}

void EglGbmBackend::init()
{
110 111 112 113
    if (!initializeEgl()) {
        setFailed("Could not initialize egl");
        return;
    }
114 115 116 117 118 119 120 121 122 123 124 125 126
    if (!initRenderingContext()) {
        setFailed("Could not initialize rendering context");
        return;
    }

    initKWinGL();
    initBufferAge();
    initWayland();
}

bool EglGbmBackend::initRenderingContext()
{
    initBufferConfigs();
127 128
    if (!createContext()) {
        return false;
129 130
    }

Roman Gilg's avatar
Roman Gilg committed
131
    const auto outputs = m_backend->drmOutputs();
132

133
    for (DrmOutput *drmOutput: outputs) {
134
        createOutput(drmOutput);
135
    }
136

137
    if (m_outputs.isEmpty()) {
138
        qCCritical(KWIN_DRM) << "Create Window Surfaces failed";
139 140
        return false;
    }
141 142

    // Set our first surface as the one for the abstract backend, just to make it happy.
143
    setSurface(m_outputs.first().eglSurface);
144

145
    return makeContextCurrent(m_outputs.first());
146 147
}

148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
std::shared_ptr<GbmSurface> EglGbmBackend::createGbmSurface(const QSize &size) const
{
    auto gbmSurface = std::make_shared<GbmSurface>(m_backend->gbmDevice(),
                                                   size.width(), size.height(),
                                                   GBM_FORMAT_XRGB8888,
                                                   GBM_BO_USE_SCANOUT | GBM_BO_USE_RENDERING);
    if (!gbmSurface) {
        qCCritical(KWIN_DRM) << "Creating GBM surface failed";
        return nullptr;
    }
    return gbmSurface;
}

EGLSurface EglGbmBackend::createEglSurface(std::shared_ptr<GbmSurface> gbmSurface) const
{
    auto eglSurface = eglCreatePlatformWindowSurfaceEXT(eglDisplay(), config(),
                                                        (void *)(gbmSurface->surface()), nullptr);
    if (eglSurface == EGL_NO_SURFACE) {
        qCCritical(KWIN_DRM) << "Creating EGL surface failed";
        return EGL_NO_SURFACE;
    }
    return eglSurface;
}

bool EglGbmBackend::resetOutput(Output &output, DrmOutput *drmOutput)
173
{
174
    output.output = drmOutput;
175 176
    const QSize size = drmOutput->hardwareTransforms() ? drmOutput->pixelSize() :
                                                         drmOutput->modeSize();
David Edmundson's avatar
David Edmundson committed
177

178
    auto gbmSurface = createGbmSurface(size);
179 180
    if (!gbmSurface) {
        return false;
181
    }
182
    auto eglSurface = createEglSurface(gbmSurface);
183 184
    if (eglSurface == EGL_NO_SURFACE) {
        return false;
185 186 187 188 189 190
    }

    // destroy previous surface
    if (output.eglSurface != EGL_NO_SURFACE) {
        if (surface() == output.eglSurface) {
            setSurface(eglSurface);
191
        }
192
        eglDestroySurface(eglDisplay(), output.eglSurface);
193
    }
194 195
    output.eglSurface = eglSurface;
    output.gbmSurface = gbmSurface;
196 197

    resetFramebuffer(output);
198 199 200 201 202
    return true;
}

void EglGbmBackend::createOutput(DrmOutput *drmOutput)
{
203 204
    Output newOutput;
    if (resetOutput(newOutput, drmOutput)) {
205 206 207
        connect(drmOutput, &DrmOutput::modeChanged, this,
            [drmOutput, this] {
                auto it = std::find_if(m_outputs.begin(), m_outputs.end(),
208 209
                    [drmOutput] (const auto &output) {
                        return output.output == drmOutput;
210 211 212 213 214 215 216 217
                    }
                );
                if (it == m_outputs.end()) {
                    return;
                }
                resetOutput(*it, drmOutput);
            }
        );
218
        m_outputs << newOutput;
219 220 221
    }
}

222 223 224 225 226 227 228 229 230 231
void EglGbmBackend::removeOutput(DrmOutput *drmOutput)
{
    auto it = std::find_if(m_outputs.begin(), m_outputs.end(),
        [drmOutput] (const Output &output) {
            return output.output == drmOutput;
        }
    );
    if (it == m_outputs.end()) {
        return;
    }
232

233 234 235 236
    cleanupOutput(*it);
    m_outputs.erase(it);
}

237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
const float vertices[] = {
   -1.0f,  1.0f,
   -1.0f, -1.0f,
    1.0f, -1.0f,

   -1.0f,  1.0f,
    1.0f, -1.0f,
    1.0f,  1.0f,
};

const float texCoords[] = {
    0.0f,  1.0f,
    0.0f,  0.0f,
    1.0f,  0.0f,

    0.0f,  1.0f,
    1.0f,  0.0f,
    1.0f,  1.0f
};

bool EglGbmBackend::resetFramebuffer(Output &output)
{
    cleanupFramebuffer(output);

    if (output.output->hardwareTransforms()) {
        // No need for an extra render target.
        return true;
    }

    makeContextCurrent(output);

    glGenFramebuffers(1, &output.render.framebuffer);
    glBindFramebuffer(GL_FRAMEBUFFER, output.render.framebuffer);
    GLRenderTarget::setKWinFramebuffer(output.render.framebuffer);

    glGenTextures(1, &output.render.texture);
    glBindTexture(GL_TEXTURE_2D, output.render.texture);

    const QSize texSize = output.output->pixelSize();
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, texSize.width(), texSize.height(),
                 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST );
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

    glBindTexture(GL_TEXTURE_2D, 0);

    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
                           output.render.texture, 0);

    if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
        qCWarning(KWIN_DRM) << "Error: framebuffer not complete";
        return false;
    }

    glBindFramebuffer(GL_FRAMEBUFFER, 0);
    GLRenderTarget::setKWinFramebuffer(0);
    return true;
}

296
void EglGbmBackend::initRenderTarget(Output &output)
297
{
298
    if (output.render.vbo) {
299
        // Already initialized.
300
        return;
301 302 303 304 305 306 307 308 309 310 311 312
    }
    std::shared_ptr<GLVertexBuffer> vbo(new GLVertexBuffer(KWin::GLVertexBuffer::Static));
    vbo->setData(6, 2, vertices, texCoords);
    output.render.vbo = vbo;
}

void EglGbmBackend::renderFramebufferToSurface(Output &output)
{
    if (!output.render.framebuffer) {
        // No additional render target.
        return;
    }
313
    initRenderTarget(output);
314 315 316 317 318 319 320

    glBindFramebuffer(GL_FRAMEBUFFER, 0);
    GLRenderTarget::setKWinFramebuffer(0);

    const auto size = output.output->modeSize();
    glViewport(0, 0, size.width(), size.height());

321 322
    auto shader = ShaderManager::instance()->pushShader(ShaderTrait::MapTexture);

323 324
    QMatrix4x4 rotationMatrix;
    rotationMatrix.rotate(output.output->rotation(), 0, 0, 1);
325
    shader->setUniform(GLShader::ModelViewProjectionMatrix, rotationMatrix);
326 327 328

    glBindTexture(GL_TEXTURE_2D, output.render.texture);
    output.render.vbo->render(GL_TRIANGLES);
329
    ShaderManager::instance()->popShader();
330 331 332 333 334 335 336 337 338
}

void EglGbmBackend::prepareRenderFramebuffer(const Output &output) const
{
    // When render.framebuffer is 0 we may just reset to the screen framebuffer.
    glBindFramebuffer(GL_FRAMEBUFFER, output.render.framebuffer);
    GLRenderTarget::setKWinFramebuffer(output.render.framebuffer);
}

339
bool EglGbmBackend::makeContextCurrent(const Output &output) const
340
{
341 342 343 344 345
    const EGLSurface surface = output.eglSurface;
    if (surface == EGL_NO_SURFACE) {
        return false;
    }
    if (eglMakeCurrent(eglDisplay(), surface, surface, context()) == EGL_FALSE) {
346
        qCCritical(KWIN_DRM) << "Make Context Current failed" << eglGetError();
347 348 349 350 351 352 353 354 355 356 357 358 359
        return false;
    }
    return true;
}

bool EglGbmBackend::initBufferConfigs()
{
    const EGLint config_attribs[] = {
        EGL_SURFACE_TYPE,         EGL_WINDOW_BIT,
        EGL_RED_SIZE,             1,
        EGL_GREEN_SIZE,           1,
        EGL_BLUE_SIZE,            1,
        EGL_ALPHA_SIZE,           0,
360
        EGL_RENDERABLE_TYPE,      isOpenGLES() ? EGL_OPENGL_ES2_BIT : EGL_OPENGL_BIT,
361 362 363 364 365 366
        EGL_CONFIG_CAVEAT,        EGL_NONE,
        EGL_NONE,
    };

    EGLint count;
    EGLConfig configs[1024];
367 368 369
    if (!eglChooseConfig(eglDisplay(), config_attribs, configs,
                         sizeof(configs) / sizeof(EGLConfig),
                         &count)) {
370
        qCCritical(KWIN_DRM) << "choose config failed";
371 372
        return false;
    }
373 374 375

    qCDebug(KWIN_DRM) << "EGL buffer configs count:" << count;

376
    // Loop through all configs, choosing the first one that has suitable format.
377 378
    for (EGLint i = 0; i < count; i++) {
        EGLint gbmFormat;
379
        // Query some configuration parameters, to show in debug log.
380 381 382
        eglGetConfigAttrib(eglDisplay(), configs[i], EGL_NATIVE_VISUAL_ID, &gbmFormat);

        if (KWIN_DRM().isDebugEnabled()) {
383
            // GBM formats are declared as FOURCC code (integer from ASCII chars, so use this fact).
384 385
            char gbmFormatStr[sizeof(EGLint) + 1] = {0};
            memcpy(gbmFormatStr, &gbmFormat, sizeof(EGLint));
386 387

            // Query number of bits for color channel.
388 389 390 391 392 393
            EGLint blueSize, redSize, greenSize, alphaSize;
            eglGetConfigAttrib(eglDisplay(), configs[i], EGL_RED_SIZE, &redSize);
            eglGetConfigAttrib(eglDisplay(), configs[i], EGL_GREEN_SIZE, &greenSize);
            eglGetConfigAttrib(eglDisplay(), configs[i], EGL_BLUE_SIZE, &blueSize);
            eglGetConfigAttrib(eglDisplay(), configs[i], EGL_ALPHA_SIZE, &alphaSize);
            qCDebug(KWIN_DRM) << "  EGL config #" << i << " has GBM FOURCC format:" << gbmFormatStr
394 395
                              << "; color sizes (RGBA order):"
                              << redSize << greenSize << blueSize << alphaSize;
396 397 398 399 400 401
        }

        if ((gbmFormat == GBM_FORMAT_XRGB8888) || (gbmFormat == GBM_FORMAT_ARGB8888)) {
            setConfig(configs[i]);
            return true;
        }
402 403
    }

404 405
    qCCritical(KWIN_DRM) << "Choosing EGL config did not return a suitable config. There were"
                         << count << "configs.";
406
    return false;
407 408 409 410
}

void EglGbmBackend::present()
{
411 412
    Q_UNREACHABLE();
    // Not in use. This backend does per-screen rendering.
413 414
}

415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453
static QVector<EGLint> regionToRects(const QRegion &region, AbstractWaylandOutput *output)
{
    const int height = output->modeSize().height();

    const QMatrix4x4 matrix = output->transformation();

    QVector<EGLint> rects;
    rects.reserve(region.rectCount() * 4);
    for (const QRect &_rect : region) {
        const QRect rect = matrix.mapRect(_rect);

        rects << rect.left();
        rects << height - (rect.y() + rect.height());
        rects << rect.width();
        rects << rect.height();
    }
    return rects;
}

void EglGbmBackend::aboutToStartPainting(const QRegion &damagedRegion)
{
    // See EglGbmBackend::endRenderingFrameForScreen comment for the reason why we only support screenId=0
    if (m_outputs.count() > 1) {
        return;
    }

    const Output &output = m_outputs.at(0);
    if (output.bufferAge > 0 && !damagedRegion.isEmpty() && supportsPartialUpdate()) {
        const QRegion region = damagedRegion & output.output->geometry();

        QVector<EGLint> rects = regionToRects(region, output.output);
        const bool correct = eglSetDamageRegionKHR(eglDisplay(), output.eglSurface,
                                                   rects.data(), rects.count()/4);
        if (!correct) {
            qCWarning(KWIN_DRM) << "failed eglSetDamageRegionKHR" << eglGetError();
        }
    }
}

454
void EglGbmBackend::presentOnOutput(Output &output, const QRegion &damagedRegion)
455
{
456 457 458 459 460 461 462
    if (supportsSwapBuffersWithDamage()) {
        QVector<EGLint> rects = regionToRects(output.damageHistory.constFirst(), output.output);
        eglSwapBuffersWithDamageEXT(eglDisplay(), output.eglSurface,
                                    rects.data(), rects.count()/4);
    } else {
        eglSwapBuffers(eglDisplay(), output.eglSurface);
    }
463 464
    output.buffer = m_backend->createBuffer(output.gbmSurface);

465
    Q_EMIT output.output->outputChange(damagedRegion);
466
    m_backend->present(output.buffer, output.output);
467

468
    if (supportsBufferAge()) {
469
        eglQuerySurface(eglDisplay(), output.eglSurface, EGL_BUFFER_AGE_EXT, &output.bufferAge);
470 471 472
    }
}

473 474 475 476 477 478
void EglGbmBackend::screenGeometryChanged(const QSize &size)
{
    Q_UNUSED(size)
    // TODO, create new buffer?
}

479
SceneOpenGLTexturePrivate *EglGbmBackend::createBackendTexture(SceneOpenGLTexture *texture)
480 481 482 483 484 485
{
    return new EglGbmTexture(texture, this);
}

QRegion EglGbmBackend::prepareRenderingFrame()
{
486 487 488 489
    startRenderTimer();
    return QRegion();
}

490 491 492 493 494 495 496 497 498 499
void EglGbmBackend::setViewport(const Output &output) const
{
    const QSize &overall = screens()->size();
    const QRect &v = output.output->geometry();
    qreal scale = output.output->scale();

    glViewport(-v.x() * scale, (v.height() - overall.height() + v.y()) * scale,
               overall.width() * scale, overall.height() * scale);
}

500 501
QRegion EglGbmBackend::prepareRenderingForScreen(int screenId)
{
502 503 504
    const Output &output = m_outputs.at(screenId);

    makeContextCurrent(output);
505
    prepareRenderFramebuffer(output);
506 507
    setViewport(output);

508
    if (supportsBufferAge()) {
509 510 511
        QRegion region;

        // Note: An age of zero means the buffer contents are undefined
512 513 514
        if (output.bufferAge > 0 && output.bufferAge <= output.damageHistory.count()) {
            for (int i = 0; i < output.bufferAge - 1; i++)
                region |= output.damageHistory[i];
515
        } else {
516
            region = output.output->geometry();
517
        }
518 519

        return region;
520
    }
521
    return output.output->geometry();
522 523
}

524
void EglGbmBackend::endRenderingFrame(const QRegion &renderedRegion, const QRegion &damagedRegion)
525
{
526 527
    Q_UNUSED(renderedRegion)
    Q_UNUSED(damagedRegion)
528 529
}

530 531 532
void EglGbmBackend::endRenderingFrameForScreen(int screenId,
                                               const QRegion &renderedRegion,
                                               const QRegion &damagedRegion)
533
{
534
    Output &output = m_outputs[screenId];
535
    renderFramebufferToSurface(output);
536 537

    if (damagedRegion.intersected(output.output->geometry()).isEmpty() && screenId == 0) {
538 539 540 541 542 543 544 545

        // If the damaged region of a window is fully occluded, the only
        // rendering done, if any, will have been to repair a reused back
        // buffer, making it identical to the front buffer.
        //
        // In this case we won't post the back buffer. Instead we'll just
        // set the buffer age to 1, so the repaired regions won't be
        // rendered again in the next frame.
546
        if (!renderedRegion.intersected(output.output->geometry()).isEmpty())
547 548
            glFlush();

549 550
        for (auto &output: m_outputs) {
            output.bufferAge = 1;
551
        }
552 553
        return;
    }
554
    presentOnOutput(output, damagedRegion);
555 556

    // Save the damaged region to history
557 558 559 560 561 562 563
    // Note: damage history is only collected for the first screen. For any other screen full
    // repaints are triggered. This is due to a limitation in Scene::paintGenericScreen which resets
    // the Toplevel's repaint. So multiple calls to Scene::paintScreen as it's done in multi-output
    // rendering only have correct damage information for the first screen. If we try to track
    // damage nevertheless, it creates artifacts. So for the time being we work around the problem
    // by only supporting buffer age on the first output. To properly support buffer age on all
    // outputs the rendering needs to be refactored in general.
564
    if (supportsBufferAge() && screenId == 0) {
565 566
        if (output.damageHistory.count() > 10) {
            output.damageHistory.removeLast();
567
        }
568
        output.damageHistory.prepend(damagedRegion.intersected(output.output->geometry()));
569
    }
570 571 572 573 574 575 576
}

bool EglGbmBackend::usesOverlayWindow() const
{
    return false;
}

577 578 579 580 581
bool EglGbmBackend::perScreenRendering() const
{
    return true;
}

582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608
QSharedPointer<GLTexture> EglGbmBackend::textureForOutput(AbstractOutput *abstractOutput) const
{
    const QVector<KWin::EglGbmBackend::Output>::const_iterator itOutput = std::find_if(m_outputs.begin(), m_outputs.end(),
        [abstractOutput] (const auto &output) {
            return output.output == abstractOutput;
        }
    );
    if (itOutput == m_outputs.end()) {
        return {};
    }

    DrmOutput *drmOutput = itOutput->output;
    if (!drmOutput->hardwareTransforms()) {
        const auto glTexture = QSharedPointer<KWin::GLTexture>::create(itOutput->render.texture, GL_RGBA8, drmOutput->pixelSize());
        glTexture->setYInverted(true);
        return glTexture;
    }

    EGLImageKHR image = eglCreateImageKHR(eglDisplay(), nullptr, EGL_NATIVE_PIXMAP_KHR, itOutput->buffer->getBo(), nullptr);
    if (image == EGL_NO_IMAGE_KHR) {
        qCWarning(KWIN_DRM) << "Failed to record frame: Error creating EGLImageKHR - " << glGetError();
        return {};
    }

    return QSharedPointer<EGLImageTexture>::create(eglDisplay(), image, GL_RGBA8, drmOutput->modeSize());
}

609 610 611 612
/************************************************
 * EglTexture
 ************************************************/

613
EglGbmTexture::EglGbmTexture(KWin::SceneOpenGLTexture *texture, EglGbmBackend *backend)
614 615 616 617 618 619
    : AbstractEglTexture(texture, backend)
{
}

EglGbmTexture::~EglGbmTexture() = default;

620
}