summaryrefslogtreecommitdiffstats
path: root/src/gui/rhi/qdxgivsyncservice.cpp
blob: ce4a37f055eb1035a3cbc457017aa85414401377 (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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
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
// Copyright (C) 2024 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 "qdxgivsyncservice_p.h"
#include <QThread>
#include <QWaitCondition>
#include <QElapsedTimer>
#include <QCoreApplication>
#include <QLoggingCategory>
#include <QScreen>
#include <QVarLengthArray>
#include <QtCore/private/qsystemerror_p.h>

QT_BEGIN_NAMESPACE

Q_STATIC_LOGGING_CATEGORY(lcQpaScreenUpdates, "qt.qpa.screen.updates", QtCriticalMsg);

class QDxgiVSyncThread : public QThread
{
public:
    // the HMONITOR is unique (i.e. identifies the output), the IDXGIOutput (the pointer/object itself) is not
    using Callback = std::function<void(IDXGIOutput *, HMONITOR, qint64)>;
    QDxgiVSyncThread(IDXGIOutput *output, float vsyncIntervalMsReportedForScreen, Callback callback);
    void stop(); // to be called from a thread that's not this thread
    void run() override;

private:
    IDXGIOutput *output;
    float vsyncIntervalMsReportedForScreen;
    Callback callback;
    HMONITOR monitor;
    QAtomicInt quit;
    QMutex mutex;
    QWaitCondition cond;
};

QDxgiVSyncThread::QDxgiVSyncThread(IDXGIOutput *output, float vsyncIntervalMsReportedForScreen, Callback callback)
    : output(output),
      vsyncIntervalMsReportedForScreen(vsyncIntervalMsReportedForScreen),
      callback(callback)
{
    DXGI_OUTPUT_DESC desc;
    output->GetDesc(&desc);
    monitor = desc.Monitor;
}

void QDxgiVSyncThread::run()
{
    qCDebug(lcQpaScreenUpdates) << "QDxgiVSyncThread" << this << "for output" << output << "monitor" << monitor << "entered run()";
    QElapsedTimer timestamp;
    QElapsedTimer elapsed;
    timestamp.start();
    while (!quit.loadAcquire()) {
        elapsed.start();
        HRESULT hr = output->WaitForVBlank();
        if (FAILED(hr) || elapsed.nsecsElapsed() <= 1000000) {
            // 1 ms minimum; if less than that was spent in WaitForVBlank
            // (reportedly can happen e.g. when a screen gets powered on/off?),
            // or it reported an error, do a sleep; spinning unthrottled is
            // never acceptable
            QThread::msleep((unsigned long) vsyncIntervalMsReportedForScreen);
        } else {
            callback(output, monitor, timestamp.nsecsElapsed());
        }
    }
    qCDebug(lcQpaScreenUpdates) << "QDxgiVSyncThread" << this << "is stopping";
    mutex.lock();
    cond.wakeOne();
    mutex.unlock();
    qCDebug(lcQpaScreenUpdates) << "QDxgiVSyncThread" << this << "run() out";
}

void QDxgiVSyncThread::stop()
{
    mutex.lock();
    qCDebug(lcQpaScreenUpdates) << "Requesting QDxgiVSyncThread stop from thread" << QThread::currentThread() << "on" << this;
    if (isRunning() && !quit.loadAcquire()) {
        quit.storeRelease(1);
        cond.wait(&mutex);
    }
    wait();
    mutex.unlock();
}

QDxgiVSyncService *QDxgiVSyncService::instance()
{
    static QDxgiVSyncService service;
    return &service;
}

QDxgiVSyncService::QDxgiVSyncService()
{
    qCDebug(lcQpaScreenUpdates) << "New QDxgiVSyncService" << this;

    disableService = qEnvironmentVariableIntValue("QT_D3D_NO_VBLANK_THREAD");
    if (disableService) {
        qCDebug(lcQpaScreenUpdates) << "QDxgiVSyncService disabled by environment";
        return;
    }
}

QDxgiVSyncService::~QDxgiVSyncService()
{
    qCDebug(lcQpaScreenUpdates) << "~QDxgiVSyncService" << this;

    // Deadlock is almost guaranteed if we try to clean up here, when the global static is being destructed.
    // Must have been done earlier.
    if (dxgiFactory)
        qWarning("QDxgiVSyncService not destroyed in time");
}

void QDxgiVSyncService::global_destroy()
{
    QDxgiVSyncService *inst = QDxgiVSyncService::instance();
    inst->cleanupRegistered = false;
    inst->destroy();
}

void QDxgiVSyncService::destroy()
{
    qCDebug(lcQpaScreenUpdates) << "QDxgiVSyncService::destroy()";

    if (disableService)
        return;

    for (auto it = windows.begin(), end = windows.end(); it != end; ++it)
        cleanupWindowData(&*it);
    windows.clear();

    teardownDxgi();
}

void QDxgiVSyncService::teardownDxgi()
{
    for (auto it = adapters.begin(), end = adapters.end(); it != end; ++it)
        cleanupAdapterData(&*it);
    adapters.clear();

    if (dxgiFactory) {
        dxgiFactory->Release();
        dxgiFactory = nullptr;
    }

    qCDebug(lcQpaScreenUpdates) << "QDxgiVSyncService DXGI teardown complete";
}

void QDxgiVSyncService::beginFrame(LUID)
{
    QMutexLocker lock(&mutex);
    if (disableService)
        return;

    // Handle "the possible need to re-create the factory and re-enumerate
    // adapters". At the time of writing the QRhi D3D11 and D3D12 backends do
    // not handle this at all (and rendering does not actually break or stop
    // just because the factory says !IsCurrent), whereas here it makes more
    // sense to act since we may want to get rid of threads that are no longer
    // needed. Keep the adapter IDs and the registered windows, drop everything
    // else, then start from scratch.

    if (dxgiFactory && !dxgiFactory->IsCurrent()) {
        qWarning("QDxgiVSyncService: DXGI Factory is no longer Current");
        QVarLengthArray<LUID, 8> luids;
        for (auto it = adapters.begin(), end = adapters.end(); it != end; ++it)
            luids.append(it->luid);
        for (auto it = windows.begin(), end = windows.end(); it != end; ++it)
            cleanupWindowData(&*it);
        lock.unlock();
        teardownDxgi();
        for (LUID luid : luids)
            refAdapter(luid);
        lock.relock();
        for (auto it = windows.begin(), end = windows.end(); it != end; ++it)
            updateWindowData(it.key(), &*it);
    }
}

void QDxgiVSyncService::refAdapter(LUID luid)
{
    QMutexLocker lock(&mutex);
    if (disableService)
        return;

    if (!dxgiFactory) {
        HRESULT hr = CreateDXGIFactory2(0, __uuidof(IDXGIFactory2), reinterpret_cast<void **>(&dxgiFactory));
        if (FAILED(hr)) {
            disableService = true;
            qWarning("QDxgiVSyncService: CreateDXGIFactory2 failed: %s", qPrintable(QSystemError::windowsComString(hr)));
            return;
        }
        if (!cleanupRegistered) {
            qAddPostRoutine(QDxgiVSyncService::global_destroy);
            cleanupRegistered = true;
        }
    }

    for (AdapterData &a : adapters) {
        if (a.luid.LowPart == luid.LowPart && a.luid.HighPart == luid.HighPart) {
            a.ref += 1;
            return;
        }
    }

    AdapterData a;
    a.ref = 1;
    a.luid = luid;
    a.adapter = nullptr;

    IDXGIAdapter1 *ad;
    for (int adapterIndex = 0; dxgiFactory->EnumAdapters1(UINT(adapterIndex), &ad) != DXGI_ERROR_NOT_FOUND; ++adapterIndex) {
        DXGI_ADAPTER_DESC1 desc;
        ad->GetDesc1(&desc);
        if (desc.AdapterLuid.LowPart == luid.LowPart && desc.AdapterLuid.HighPart == luid.HighPart) {
            a.adapter = ad;
            break;
        }
        ad->Release();
    }

    if (!a.adapter) {
        qWarning("VSyncService: Failed to find adapter (via EnumAdapters1), skipping");
        return;
    }

    adapters.append(a);

    qCDebug(lcQpaScreenUpdates) << "QDxgiVSyncService refAdapter for not yet seen adapter" << luid.LowPart << luid.HighPart;

    // windows may have been registered before any adapters
    for (auto it = windows.begin(), end = windows.end(); it != end; ++it)
        updateWindowData(it.key(), &*it);
}

void QDxgiVSyncService::derefAdapter(LUID luid)
{
    QVarLengthArray<AdapterData, 4> cleanupList;

    {
        QMutexLocker lock(&mutex);
        if (disableService)
            return;

        for (qsizetype i = 0; i < adapters.count(); ++i) {
            AdapterData &a(adapters[i]);
            if (a.luid.LowPart == luid.LowPart && a.luid.HighPart == luid.HighPart) {
                if (!--a.ref) {
                    cleanupList.append(a);
                    adapters.removeAt(i);
                }
                break;
            }
        }
    }

    // the lock must *not* be held when triggering cleanup
    for (AdapterData &a : cleanupList)
        cleanupAdapterData(&a);
}

void QDxgiVSyncService::cleanupAdapterData(AdapterData *a)
{
    for (auto it = a->notifiers.begin(), end = a->notifiers.end(); it != end; ++it) {
        qCDebug(lcQpaScreenUpdates) << "QDxgiVSyncService::cleanupAdapterData(): about to call stop()";
        it->thread->stop();
        qCDebug(lcQpaScreenUpdates) << "QDxgiVSyncService::cleanupAdapterData(): stop() called";
        delete it->thread;
        it->output->Release();
    }
    a->notifiers.clear();

    a->adapter->Release();
    a->adapter = nullptr;
}

void QDxgiVSyncService::cleanupWindowData(WindowData *w)
{
    if (w->output) {
        w->output->Release();
        w->output = nullptr;
    }
}

static IDXGIOutput *outputForWindow(QWindow *w, IDXGIAdapter *adapter)
{
    // Generic canonical solution as per
    // https://learn.microsoft.com/en-us/windows/win32/api/dxgi/nf-dxgi-idxgiswapchain-getcontainingoutput
    // and
    // https://learn.microsoft.com/en-us/windows/win32/direct3darticles/high-dynamic-range

    QRect wr = w->geometry();
    wr = QRect(wr.topLeft() * w->devicePixelRatio(), wr.size() * w->devicePixelRatio());
    const QPoint center = wr.center();
    IDXGIOutput *currentOutput = nullptr;
    IDXGIOutput *output = nullptr;
    for (UINT i = 0; adapter->EnumOutputs(i, &output) != DXGI_ERROR_NOT_FOUND; ++i) {
        DXGI_OUTPUT_DESC desc;
        output->GetDesc(&desc);
        const RECT r = desc.DesktopCoordinates;
        const QRect dr(QPoint(r.left, r.top), QPoint(r.right - 1, r.bottom - 1));
        if (dr.contains(center)) {
            currentOutput = output;
            break;
        } else {
            output->Release();
        }
    }
    return currentOutput; // has a ref on it, will need Release by caller
}

void QDxgiVSyncService::updateWindowData(QWindow *window, WindowData *wd)
{
    for (auto it = adapters.begin(), end = adapters.end(); it != end; ++it) {
        IDXGIOutput *output = outputForWindow(window, it->adapter);
        if (!output)
            continue;

        // Two windows on the same screen may well return two different
        // IDXGIOutput pointers due to enumerating outputs every time; always
        // compare the HMONITOR, not the pointer itself.

        DXGI_OUTPUT_DESC desc;
        output->GetDesc(&desc);

        if (wd->output && wd->output != output) {
            if (desc.Monitor == wd->monitor) {
                output->Release();
                return;
            }
            wd->output->Release();
        }

        wd->output = output;
        wd->monitor = desc.Monitor;

        QScreen *screen = window->screen();
        const qreal refresh = screen ? screen->refreshRate() : 60;
        wd->reportedRefreshIntervalMs = refresh > 0 ? 1000.0f / float(refresh) : 1000.f / 60.0f;

        qCDebug(lcQpaScreenUpdates) << "QDxgiVSyncService: Output for window" << window
                                    << "on the actively used adapters is now" << output
                                    << "HMONITOR" << wd->monitor
                                    << "refresh" << wd->reportedRefreshIntervalMs;

        if (!it->notifiers.contains(wd->monitor)) {
            output->AddRef();
            QDxgiVSyncThread *t = new QDxgiVSyncThread(output, wd->reportedRefreshIntervalMs,
            [this](IDXGIOutput *, HMONITOR monitor, qint64 timestampNs) {
                CallbackWindowList w;
                QMutexLocker lock(&mutex);
                for (auto it = windows.cbegin(), end = windows.cend(); it != end; ++it) {
                    if (it->output && it->monitor == monitor)
                        w.append(it.key());
                }
                if (!w.isEmpty()) {
#if 0
                    qDebug() << "vsync thread" << QThread::currentThread() << monitor << "window list" << w << timestampNs;
#endif
                    for (const Callback &cb : std::as_const(callbacks)) {
                        if (cb)
                            cb(w, timestampNs);
                    }
                }
            });
            t->start(QThread::TimeCriticalPriority);
            it->notifiers.insert(wd->monitor, { wd->output, t });
        }
        return;
    }

    // If we get here, there is no IDXGIOutput and supportsWindow() will return false for this window.
    // This is perfectly normal when using an adapter such as WARP.
}

void QDxgiVSyncService::registerWindow(QWindow *window)
{
    QMutexLocker lock(&mutex);
    if (disableService || windows.contains(window))
        return;

    qCDebug(lcQpaScreenUpdates) << "QDxgiVSyncService: adding window" << window;

    WindowData wd;
    wd.output = nullptr;
    updateWindowData(window, &wd);
    windows.insert(window, wd);

    QObject::connect(window, &QWindow::screenChanged, window, [this, window](QScreen *screen) {
        qCDebug(lcQpaScreenUpdates) << "QDxgiVSyncService: screen changed for window:" << window << screen;
        QMutexLocker lock(&mutex);
        auto it = windows.find(window);
        if (it != windows.end())
            updateWindowData(window, &*it);
    }, Qt::QueuedConnection); // intentionally using Queued
    // It has been observed that with DirectConnection _sometimes_ we do not
    // find any IDXGIOutput for the window when moving it to a different screen.
    // Add a delay by going through the event loop.
}

void QDxgiVSyncService::unregisterWindow(QWindow *window)
{
    QMutexLocker lock(&mutex);
    auto it = windows.find(window);
    if (it == windows.end())
        return;

    qCDebug(lcQpaScreenUpdates) << "QDxgiVSyncService: removing window" << window;

    cleanupWindowData(&*it);

    windows.remove(window);
}

bool QDxgiVSyncService::supportsWindow(QWindow *window)
{
    QMutexLocker lock(&mutex);
    auto it = windows.constFind(window);
    return it != windows.cend() ? (it->output != nullptr) : false;
}

qsizetype QDxgiVSyncService::registerCallback(Callback cb)
{
    QMutexLocker lock(&mutex);
    for (qsizetype i = 0; i < callbacks.count(); ++i) {
        if (!callbacks[i]) {
            callbacks[i] = cb;
            return i + 1;
        }
    }
    callbacks.append(cb);
    return callbacks.count();
}

void QDxgiVSyncService::unregisterCallback(qsizetype id)
{
    QMutexLocker lock(&mutex);
    const qsizetype index = id - 1;
    if (index >= 0 && index < callbacks.count())
        callbacks[index] = nullptr;
}

QT_END_NAMESPACE