summaryrefslogtreecommitdiff
path: root/src/imports/texture-sharing/sharedtextureprovider.cpp
blob: 45da333307345897071cdd165eef1032d67495f8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
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
/****************************************************************************
**
** Copyright (C) 2019 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the plugins of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/


#include "sharedtextureprovider.h"

#include <QFile>
#include <QDebug>
#include <qopenglfunctions.h>
#include <QQuickWindow>

#include <QtWaylandClient/private/qwaylandintegration_p.h>
#include <QtWaylandClient/private/qwaylandserverbufferintegration_p.h>
#include <QtGui/QGuiApplication>
#include <QtGui/private/qguiapplication_p.h>
#include <QtQuick/private/qsgrhisupport_p.h>
#include <QtGui/qpa/qplatformnativeinterface.h>
#include <QtGui/QWindow>
#include <QOpenGLTexture>
#include <QImageReader>

#include <QTimer>

#include "texturesharingextension.h"

QT_BEGIN_NAMESPACE

class SharedTextureFactory : public QQuickTextureFactory
{
public:
    SharedTextureFactory(const QtWaylandClient::QWaylandServerBuffer *buffer, const QString &id, SharedTextureRegistry *registry)
        : m_buffer(buffer), m_id(id), m_registry(registry)
    {
    }

    ~SharedTextureFactory() override
    {
        //qDebug() << "====> DESTRUCTOR SharedTextureFactory" << this;
        if (m_registry)
            m_registry->abandonBuffer(m_id);
        delete m_buffer; // TODO: make sure we are not keeping references to this elsewhere
        //qDebug() << "buffer deleted";
    }

    QSize textureSize() const override
    {
        return m_buffer ? m_buffer->size() : QSize();
    }

    int textureByteCount() const override
    {
        return m_buffer ? (m_buffer->size().width() * m_buffer->size().height() * 4) : 0;
    }

    QSGTexture *createTexture(QQuickWindow *window) const override
    {
        if (m_buffer != nullptr) {
            QOpenGLTexture *texture = const_cast<QtWaylandClient::QWaylandServerBuffer *>(m_buffer)->toOpenGlTexture();
            return QNativeInterface::QSGOpenGLTexture::fromNative(texture->textureId(),
                                                                  window,
                                                                  m_buffer->size(),
                                                                  QQuickWindow::TextureHasAlphaChannel);
        }
        return nullptr;
    }

private:
    const QtWaylandClient::QWaylandServerBuffer *m_buffer = nullptr;
    QString m_id;
    QPointer<SharedTextureRegistry> m_registry;
};


SharedTextureRegistry::SharedTextureRegistry()
    : m_extension(new TextureSharingExtension)
{
    connect(m_extension, &TextureSharingExtension::bufferReceived, this, &SharedTextureRegistry::receiveBuffer);
    connect(m_extension, &TextureSharingExtension::activeChanged, this, &SharedTextureRegistry::handleExtensionActive);
}

SharedTextureRegistry::~SharedTextureRegistry()
{
    delete m_extension;
}

const QtWaylandClient::QWaylandServerBuffer *SharedTextureRegistry::bufferForId(const QString &id) const
{
    return m_buffers.value(id);
}

void SharedTextureRegistry::requestBuffer(const QString &id)
{
    if (!m_extension->isActive()) {
        //qDebug() << "Extension not active, adding" << id << "to queue";
        m_pendingBuffers << id;
        return;
    }
    m_extension->requestImage(id);
}

void SharedTextureRegistry::abandonBuffer(const QString &id)
{
    m_buffers.remove(id);
    m_extension->abandonImage(id);
}


void SharedTextureRegistry::handleExtensionActive()
{
    //qDebug() << "handleExtensionActive, queue:" << m_pendingBuffers;
    if (m_extension->isActive())
        while (!m_pendingBuffers.isEmpty())
            requestBuffer(m_pendingBuffers.takeFirst());
}

bool SharedTextureRegistry::preinitialize()
{
    if (QSGRhiSupport::instance()->rhiBackend() != QRhi::OpenGLES2) {
        qWarning() << "The shared-texture extension is only supported on OpenGL. Use QQuickWindow::setSceneGraphBackend() to override the default.";
        return false;
    }

    auto *serverBufferIntegration = QGuiApplicationPrivate::platformIntegration()->nativeInterface()->nativeResourceForIntegration("server_buffer_integration");

    if (!serverBufferIntegration) {
        qWarning() << "Wayland Server Buffer Integration not available.";
        return false;
    }

    return true;
}

void SharedTextureRegistry::receiveBuffer(QtWaylandClient::QWaylandServerBuffer *buffer, const QString& id)
{
    //qDebug() << "ReceiveBuffer for id" << id;
    if (buffer)
        m_buffers.insert(id, buffer);
    emit replyReceived(id);
}

class SharedTextureImageResponse : public QQuickImageResponse
{
    Q_OBJECT
public:
    SharedTextureImageResponse(SharedTextureRegistry *registry, const QString &id)
        : m_id(id), m_registry(registry)
    {
        if (!m_registry || m_registry->bufferForId(id)) {
            // Shortcut: no server roundtrip needed, just let the event loop call the slot
            QMetaObject::invokeMethod(this, "doResponse", Qt::QueuedConnection, Q_ARG(QString, id));

        } else {
            // TBD: timeout?
            connect(registry, &SharedTextureRegistry::replyReceived, this, &SharedTextureImageResponse::doResponse);
            registry->requestBuffer(id);
        }
    }

    QQuickTextureFactory *textureFactory() const override
    {
        if (m_registry) {
            const QtWaylandClient::QWaylandServerBuffer *buffer = m_registry->bufferForId(m_id);
            if (buffer) {
                //qDebug() << "Creating shared buffer texture for" << m_id;
                return new SharedTextureFactory(buffer, m_id, m_registry);
            }
            //qDebug() << "Shared buffer NOT found for" << m_id;
        }

        // No shared buffer, do fallback
        QString fbPath = fallbackPath();
        if (fbPath.isEmpty()) {
            m_errorString = QStringLiteral("Shared buffer not found, and no fallback path set.");
            return nullptr;
        }

        QImageReader reader(fbPath + m_id);
        QImage img = reader.read();
        if (img.isNull()) {
            qWarning() << "Could not load local image from id/path" << reader.fileName();
            m_errorString = QStringLiteral("Shared buffer not found, and fallback local file loading failed: ") + reader.errorString();
            return nullptr;
        }
        return QQuickTextureFactory::textureFactoryForImage(img);
    }

    QString errorString() const override
    {
        return m_errorString;
    }

    static QString fallbackPath()
    {
        static QString fbPath;
        static bool isInit = false;
        if (!isInit) {
            isInit = true;
            QByteArray envVal = qgetenv("QT_SHAREDTEXTURE_FALLBACK_DIR");
            if (!envVal.isEmpty()) {
                fbPath = QString::fromLocal8Bit(envVal);
                if (!fbPath.endsWith(QLatin1Char('/')))
                    fbPath.append(QLatin1Char('/'));
            }
        }
        return fbPath;
    }


public slots:
    void doResponse(const QString &key) {
        if (key != m_id)
            return; // not our buffer

        // No need to be called again
        if (m_registry)
            disconnect(m_registry, &SharedTextureRegistry::replyReceived, this, &SharedTextureImageResponse::doResponse);

        emit finished();
    }

private:
    QString m_id;
    SharedTextureRegistry *m_registry = nullptr;
    mutable QString m_errorString;
};


SharedTextureProvider::SharedTextureProvider()
{
    m_sharingAvailable = SharedTextureRegistry::preinitialize();
    if (!m_sharingAvailable) {
        if (SharedTextureImageResponse::fallbackPath().isEmpty())
            qWarning() << "Shared buffer images not available, and no fallback directory set.";
        else
            qWarning() << "Shared buffer images not available, will fallback to local image files from" << SharedTextureImageResponse::fallbackPath();
    }
}

SharedTextureProvider::~SharedTextureProvider()
{
    delete m_registry;
}

QQuickImageResponse *SharedTextureProvider::requestImageResponse(const QString &id, const QSize &requestedSize)
{
    Q_UNUSED(requestedSize);

    //qDebug() << "Provider: got request for" << id;

    if (m_sharingAvailable && !m_registry)
        m_registry = new SharedTextureRegistry;

    return new SharedTextureImageResponse(m_registry, id);
}

QT_END_NAMESPACE

#include "sharedtextureprovider.moc"