summaryrefslogtreecommitdiffstats
path: root/src/plugins/multimedia/ffmpeg/qgdiwindowcapture.cpp
blob: ed85cd73ac54d6e73b762b66ae2e5743136b2f52 (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
// Copyright (C) 2023 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 "qgdiwindowcapture_p.h"

#include "qvideoframe.h"
#include "qffmpegsurfacecapturegrabber_p.h"
#include "private/qcapturablewindow_p.h"
#include "private/qmemoryvideobuffer_p.h"

#include <qt_windows.h>
#include <QtCore/qloggingcategory.h>

static Q_LOGGING_CATEGORY(qLcGdiWindowCapture, "qt.multimedia.ffmpeg.gdiwindowcapture");

QT_BEGIN_NAMESPACE

class QGdiWindowCapture::Grabber : public QFFmpegSurfaceCaptureGrabber
{
public:
    static std::unique_ptr<Grabber> create(QGdiWindowCapture &capture, HWND hWnd)
    {
        auto hdcWindow = GetDC(hWnd);
        if (!hdcWindow) {
            capture.updateError(QPlatformSurfaceCapture::CaptureFailed,
                                QLatin1String("Cannot create a window drawing context"));
            return nullptr;
        }

        auto hdcMem = CreateCompatibleDC(hdcWindow);

        if (!hdcMem) {
            capture.updateError(QPlatformSurfaceCapture::CaptureFailed,
                                QLatin1String("Cannot create a compatible drawing context"));
            return nullptr;
        }

        std::unique_ptr<Grabber> result(new Grabber(capture, hWnd, hdcWindow, hdcMem));
        if (!result->update())
            return nullptr;

        result->start();
        return result;
    }

    ~Grabber() override
    {
        stop();

        if (m_hBitmap)
            DeleteObject(m_hBitmap);

        if (m_hdcMem)
            DeleteDC(m_hdcMem);

        if (m_hdcWindow)
            ReleaseDC(m_hwnd, m_hdcWindow);
    }

    QVideoFrameFormat format() const { return m_format; }

private:
    Grabber(QGdiWindowCapture &capture, HWND hWnd, HDC hdcWindow, HDC hdcMem)
        : m_hwnd(hWnd), m_hdcWindow(hdcWindow), m_hdcMem(hdcMem)
    {
        if (auto rate = GetDeviceCaps(hdcWindow, VREFRESH); rate > 0)
            setFrameRate(rate);

        addFrameCallback(capture, &QGdiWindowCapture::newVideoFrame);
        connect(this, &Grabber::errorUpdated, &capture, &QGdiWindowCapture::updateError);
    }

    bool update()
    {
        RECT windowRect{};
        if (!GetWindowRect(m_hwnd, &windowRect)) {
            updateError(QPlatformSurfaceCapture::CaptureFailed,
                        QLatin1String("Cannot get window size"));
            return false;
        }

        const QSize size{ windowRect.right - windowRect.left, windowRect.bottom - windowRect.top };

        if (m_format.isValid() && size == m_format.frameSize() && m_hBitmap)
            return true;

        if (m_hBitmap)
            DeleteObject(std::exchange(m_hBitmap, nullptr));

        if (size.isEmpty()) {
            m_format = {};
            updateError(QPlatformSurfaceCapture::CaptureFailed,
                        QLatin1String("Invalid window size"));
            return false;
        }

        m_hBitmap = CreateCompatibleBitmap(m_hdcWindow, size.width(), size.height());

        if (!m_hBitmap) {
            m_format = {};
            updateError(QPlatformSurfaceCapture::CaptureFailed,
                        QLatin1String("Cannot create a compatible bitmap"));
            return false;
        }

        QVideoFrameFormat format(size, QVideoFrameFormat::Format_BGRX8888);
        format.setStreamFrameRate(frameRate());
        m_format = format;
        return true;
    }

    QVideoFrame grabFrame() override
    {
        if (!update())
            return {};

        const auto oldBitmap = SelectObject(m_hdcMem, m_hBitmap);
        auto deselect = qScopeGuard([&]() { SelectObject(m_hdcMem, oldBitmap); });

        const auto size = m_format.frameSize();

        if (!BitBlt(m_hdcMem, 0, 0, size.width(), size.height(), m_hdcWindow, 0, 0, SRCCOPY)) {
            updateError(QPlatformSurfaceCapture::CaptureFailed,
                        QLatin1String("Cannot copy image to the compatible DC"));
            return {};
        }

        BITMAPINFO info{};
        auto &header = info.bmiHeader;
        header.biSize = sizeof(BITMAPINFOHEADER);
        header.biWidth = size.width();
        header.biHeight = -size.height(); // negative height to ensure top-down orientation
        header.biPlanes = 1;
        header.biBitCount = 32;
        header.biCompression = BI_RGB;

        const auto bytesPerLine = size.width() * 4;

        QByteArray array(size.height() * bytesPerLine, Qt::Uninitialized);

        const auto copiedHeight = GetDIBits(m_hdcMem, m_hBitmap, 0, size.height(), array.data(), &info, DIB_RGB_COLORS);
        if (copiedHeight != size.height()) {
            qCWarning(qLcGdiWindowCapture) << copiedHeight << "lines have been copied, expected:" << size.height();
           // In practice, it might fail randomly first time after start. So we don't consider it as an error.
           // TODO: investigate reasons and properly handle the error
           // updateError(QPlatformSurfaceCapture::CaptureFailed,
           //             QLatin1String("Cannot get raw image data"));
            return {};
        }

        if (header.biWidth != size.width() || header.biHeight != -size.height()
            || header.biPlanes != 1 || header.biBitCount != 32 || header.biCompression != BI_RGB) {
            updateError(QPlatformSurfaceCapture::CaptureFailed,
                        QLatin1String("Output bitmap info is unexpected"));
            return {};
        }

        return QVideoFrame(new QMemoryVideoBuffer(array, bytesPerLine), m_format);
    }

private:
    HWND m_hwnd = {};
    QVideoFrameFormat m_format;
    HDC m_hdcWindow = {};
    HDC m_hdcMem = {};
    HBITMAP m_hBitmap = {};
};

QGdiWindowCapture::QGdiWindowCapture() : QPlatformSurfaceCapture(WindowSource{}) { }

QGdiWindowCapture::~QGdiWindowCapture() = default;

QVideoFrameFormat QGdiWindowCapture::frameFormat() const
{
    return m_grabber ? m_grabber->format() : QVideoFrameFormat();
}

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

    if (m_grabber) {
        m_grabber.reset();
    } else {
        auto window = source<WindowSource>();
        auto handle = QCapturableWindowPrivate::handle(window);

        m_grabber = Grabber::create(*this, reinterpret_cast<HWND>(handle ? handle->id : 0));
    }

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

QT_END_NAMESPACE