summaryrefslogtreecommitdiffstats
path: root/src/plugins/multimedia/ffmpeg/qgrabwindowsurfacecapture.cpp
blob: 57eda3495c79d1ebbc6d942654b8af74f558ad7b (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
// Copyright (C) 2022 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only

#include "qvideoframe.h"
#include "qgrabwindowsurfacecapture_p.h"
#include "qscreencapture.h"
#include "qffmpegsurfacecapturegrabber_p.h"

#include "private/qimagevideobuffer_p.h"
#include "private/qcapturablewindow_p.h"

#include "qscreen.h"
#include "qmutex.h"
#include "qwaitcondition.h"
#include "qpixmap.h"
#include "qguiapplication.h"
#include "qwindow.h"
#include "qpointer.h"

#include <QtCore/qloggingcategory.h>

QT_BEGIN_NAMESPACE

namespace {

using WindowUPtr = std::unique_ptr<QWindow>;

} // namespace

class QGrabWindowSurfaceCapture::Grabber : public QFFmpegSurfaceCaptureGrabber
{
public:
    Grabber(QGrabWindowSurfaceCapture &capture, QScreen *screen) : Grabber(capture, screen, nullptr)
    {
        Q_ASSERT(screen);
    }

    Grabber(QGrabWindowSurfaceCapture &capture, WindowUPtr window)
        : Grabber(capture, nullptr, std::move(window))
    {
        Q_ASSERT(m_window);
    }

    ~Grabber() override {
        stop();

        Q_ASSERT(!m_screenRemovingLocked);
    }

    const QVideoFrameFormat &format()
    {
        QMutexLocker locker(&m_formatMutex);
        while (!m_format)
            m_waitForFormat.wait(&m_formatMutex);
        return *m_format;
    }

private:
    Grabber(QGrabWindowSurfaceCapture &capture, QScreen *screen, WindowUPtr window)
        : QFFmpegSurfaceCaptureGrabber(
                QGuiApplication::platformName() == QLatin1String("eglfs")
                        ? QFFmpegSurfaceCaptureGrabber::UseCurrentThread
                        : QFFmpegSurfaceCaptureGrabber::CreateGrabbingThread),
          m_capture(capture),
          m_screen(screen),
          m_window(std::move(window))
    {
        connect(qApp, &QGuiApplication::screenRemoved, this, &Grabber::onScreenRemoved);
        addFrameCallback(m_capture, &QGrabWindowSurfaceCapture::newVideoFrame);
        connect(this, &Grabber::errorUpdated, &m_capture, &QGrabWindowSurfaceCapture::updateError);
    }

    void onScreenRemoved(QScreen *screen)
    {
        /* The hack allows to lock screens removing while QScreen::grabWindow is in progress.
         * The current solution works since QGuiApplication::screenRemoved is emitted from
         *     the destructor of QScreen before destruction members of the object.
         * Note, QGuiApplication works with screens in the main thread, and any removing of a screen
         *    must be synchronized with grabbing thread.
         */
        QMutexLocker locker(&m_screenRemovingMutex);

        if (m_screenRemovingLocked) {
            qDebug() << "Screen" << screen->name()
                     << "is removed while screen window grabbing lock is active";
        }

        while (m_screenRemovingLocked)
            m_screenRemovingWc.wait(&m_screenRemovingMutex);
    }

    void setScreenRemovingLocked(bool locked)
    {
        Q_ASSERT(locked != m_screenRemovingLocked);

        {
            QMutexLocker locker(&m_screenRemovingMutex);
            m_screenRemovingLocked = locked;
        }

        if (!locked)
            m_screenRemovingWc.wakeAll();
    }

    void updateFormat(const QVideoFrameFormat &format)
    {
        if (m_format && m_format->isValid())
            return;

        {
            QMutexLocker locker(&m_formatMutex);
            m_format = format;
        }

        m_waitForFormat.wakeAll();
    }

    QVideoFrame grabFrame() override
    {
        setScreenRemovingLocked(true);
        auto screenGuard = qScopeGuard(std::bind(&Grabber::setScreenRemovingLocked, this, false));

        WId wid = m_window ? m_window->winId() : 0;
        QScreen *screen = m_window ? m_window->screen() : m_screen ? m_screen.data() : nullptr;

        if (!screen) {
            updateError(QPlatformSurfaceCapture::CaptureFailed, "Screen not found");
            return {};
        }

        setFrameRate(screen->refreshRate());

        QPixmap p = screen->grabWindow(wid);
        auto buffer = std::make_unique<QImageVideoBuffer>(p.toImage());
        const auto img = buffer->underlyingImage();

        QVideoFrameFormat format(img.size(),
                                 QVideoFrameFormat::pixelFormatFromImageFormat(img.format()));
        format.setStreamFrameRate(screen->refreshRate());
        updateFormat(format);

        if (!format.isValid()) {
            updateError(QPlatformSurfaceCapture::CaptureFailed,
                        "Failed to grab the screen content");
            return {};
        }

        return QVideoFrame(buffer.release(), format);
    }

private:
    QGrabWindowSurfaceCapture &m_capture;
    QPointer<QScreen> m_screen;
    WindowUPtr m_window;

    QMutex m_formatMutex;
    QWaitCondition m_waitForFormat;
    std::optional<QVideoFrameFormat> m_format;

    QMutex m_screenRemovingMutex;
    bool m_screenRemovingLocked = false;
    QWaitCondition m_screenRemovingWc;
};

QGrabWindowSurfaceCapture::QGrabWindowSurfaceCapture(Source initialSource)
    : QPlatformSurfaceCapture(initialSource)
{
}

QGrabWindowSurfaceCapture::~QGrabWindowSurfaceCapture() = default;

QVideoFrameFormat QGrabWindowSurfaceCapture::frameFormat() const
{
    if (m_grabber)
        return m_grabber->format();
    else
        return {};
}

bool QGrabWindowSurfaceCapture::setActiveInternal(bool active)
{
    if (active == static_cast<bool>(m_grabber))
        return true;

    if (m_grabber)
        m_grabber.reset();
    else
        std::visit([this](auto source) { activate(source); }, source());

    return static_cast<bool>(m_grabber) == active;
}

void QGrabWindowSurfaceCapture::activate(ScreenSource screen)
{
    if (!checkScreenWithError(screen))
        return;

    m_grabber = std::make_unique<Grabber>(*this, screen);
    m_grabber->start();
}

void QGrabWindowSurfaceCapture::activate(WindowSource window)
{
    auto handle = QCapturableWindowPrivate::handle(window);
    auto wid = handle ? handle->id : 0;
    if (auto wnd = WindowUPtr(QWindow::fromWinId(wid))) {
        if (!wnd->screen()) {
            updateError(InternalError,
                        "Window " + QString::number(wid) + " doesn't belong to any screen");
        } else {
            m_grabber = std::make_unique<Grabber>(*this, std::move(wnd));
            m_grabber->start();
        }
    } else {
        updateError(NotFound,
                    "Window " + QString::number(wid) + "doesn't exist or permissions denied");
    }
}

QT_END_NAMESPACE