Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qdxgivsyncservice.cpp
Go to the documentation of this file.
1// Copyright (C) 2024 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:significant reason:default
4
6#include <QThread>
7#include <QWaitCondition>
8#include <QElapsedTimer>
9#include <QCoreApplication>
10#include <QLoggingCategory>
11#include <QScreen>
12#include <QVarLengthArray>
13#include <QtCore/private/qsystemerror_p.h>
14
16
17using namespace Qt::StringLiterals;
18
19Q_STATIC_LOGGING_CATEGORY(lcQpaScreenUpdates, "qt.qpa.screen.updates", QtCriticalMsg);
20
22{
23public:
24 // the HMONITOR is unique (i.e. identifies the output), the IDXGIOutput (the pointer/object itself) is not
26 QDxgiVSyncThread(IDXGIOutput *output, float vsyncIntervalMsReportedForScreen, Callback callback);
27 void stop(); // to be called from a thread that's not this thread
28 void run() override;
29
30private:
31 IDXGIOutput *output;
32 float vsyncIntervalMsReportedForScreen;
33 Callback callback;
34 HMONITOR monitor;
35 QAtomicInt quit;
36 QMutex mutex;
37 QWaitCondition cond;
38};
39
40QDxgiVSyncThread::QDxgiVSyncThread(IDXGIOutput *output, float vsyncIntervalMsReportedForScreen, Callback callback)
41 : output(output),
42 vsyncIntervalMsReportedForScreen(vsyncIntervalMsReportedForScreen),
44{
45 QThread::setObjectName(u"QDxgiVSyncThread"_s);
46
47 DXGI_OUTPUT_DESC desc;
48 output->GetDesc(&desc);
49 monitor = desc.Monitor;
50}
51
53{
54 qCDebug(lcQpaScreenUpdates) << "QDxgiVSyncThread" << this << "for output" << output << "monitor" << monitor << "entered run()";
55 QElapsedTimer timestamp;
56 QElapsedTimer elapsed;
57 timestamp.start();
58 while (!quit.loadAcquire()) {
59 elapsed.start();
60 HRESULT hr = output->WaitForVBlank();
61 if (FAILED(hr) || elapsed.nsecsElapsed() <= 1000000) {
62 // 1 ms minimum; if less than that was spent in WaitForVBlank
63 // (reportedly can happen e.g. when a screen gets powered on/off?),
64 // or it reported an error, do a sleep; spinning unthrottled is
65 // never acceptable
66 QThread::msleep((unsigned long) vsyncIntervalMsReportedForScreen);
67 } else {
68 callback(output, monitor, timestamp.nsecsElapsed());
69 }
70 }
71 qCDebug(lcQpaScreenUpdates) << "QDxgiVSyncThread" << this << "is stopping";
72 mutex.lock();
73 cond.wakeOne();
74 mutex.unlock();
75 qCDebug(lcQpaScreenUpdates) << "QDxgiVSyncThread" << this << "run() out";
76}
77
79{
80 mutex.lock();
81 qCDebug(lcQpaScreenUpdates) << "Requesting QDxgiVSyncThread stop from thread" << QThread::currentThread() << "on" << this;
82 if (isRunning() && !quit.loadAcquire()) {
83 quit.storeRelease(1);
84 cond.wait(&mutex);
85 }
86 wait();
87 mutex.unlock();
88}
89
90QDxgiVSyncService *QDxgiVSyncService::instance()
91{
92 static QDxgiVSyncService service;
93 return &service;
94}
95
96QDxgiVSyncService::QDxgiVSyncService()
97{
98 qCDebug(lcQpaScreenUpdates) << "New QDxgiVSyncService" << this;
99
100 disableService = qEnvironmentVariableIntValue("QT_D3D_NO_VBLANK_THREAD");
101 if (disableService) {
102 qCDebug(lcQpaScreenUpdates) << "QDxgiVSyncService disabled by environment";
103 return;
104 }
105}
106
107QDxgiVSyncService::~QDxgiVSyncService()
108{
109 qCDebug(lcQpaScreenUpdates) << "~QDxgiVSyncService" << this;
110
111 // Deadlock is almost guaranteed if we try to clean up here, when the global static is being destructed.
112 // Must have been done earlier.
113 if (dxgiFactory)
114 qWarning("QDxgiVSyncService not destroyed in time");
115}
116
117void QDxgiVSyncService::global_destroy()
118{
119 QDxgiVSyncService *inst = QDxgiVSyncService::instance();
120 inst->cleanupRegistered = false;
121 inst->destroy();
122}
123
124void QDxgiVSyncService::destroy()
125{
126 qCDebug(lcQpaScreenUpdates) << "QDxgiVSyncService::destroy()";
127
128 if (disableService)
129 return;
130
131 for (auto it = windows.begin(), end = windows.end(); it != end; ++it)
132 cleanupWindowData(&*it);
133 windows.clear();
134
135 teardownDxgi();
136}
137
138void QDxgiVSyncService::teardownDxgi()
139{
140 for (auto it = adapters.begin(), end = adapters.end(); it != end; ++it)
141 cleanupAdapterData(&*it);
142 adapters.clear();
143
144 if (dxgiFactory) {
145 dxgiFactory->Release();
146 dxgiFactory = nullptr;
147 }
148
149 qCDebug(lcQpaScreenUpdates) << "QDxgiVSyncService DXGI teardown complete";
150}
151
152void QDxgiVSyncService::beginFrame(LUID)
153{
154 QMutexLocker lock(&mutex);
155 if (disableService)
156 return;
157
158 // Handle "the possible need to re-create the factory and re-enumerate
159 // adapters". At the time of writing the QRhi D3D11 and D3D12 backends do
160 // not handle this at all (and rendering does not actually break or stop
161 // just because the factory says !IsCurrent), whereas here it makes more
162 // sense to act since we may want to get rid of threads that are no longer
163 // needed. Keep the adapter IDs with their ref counts (one per QRhi) and
164 // the registered windows, drop everything else, then start from scratch.
165
166 recreateDxgiIfStale(lock);
167}
168
169void QDxgiVSyncService::recreateDxgiIfStale(QMutexLocker<QMutex> &lock)
170{
171 if (dxgiFactory && !dxgiFactory->IsCurrent()) {
172 qCDebug(lcQpaScreenUpdates, "QDxgiVSyncService: DXGI Factory is no longer Current");
173 recreateDxgi(lock);
174 }
175}
176
177void QDxgiVSyncService::recreateDxgi(QMutexLocker<QMutex> &lock)
178{
179 QVarLengthArray<std::pair<LUID, int>, 8> luids;
180 for (auto it = adapters.begin(), end = adapters.end(); it != end; ++it)
181 luids.append({ it->luid, it->ref });
182 CallbackWindowList windowsWithOutput;
183 for (auto it = windows.begin(), end = windows.end(); it != end; ++it) {
184 if (it->output)
185 windowsWithOutput.append(it.key());
186 cleanupWindowData(&*it);
187 }
188 QVector<AdapterData> staleAdapters = std::exchange(adapters, {});
189 IDXGIFactory2 *staleFactory = std::exchange(dxgiFactory, nullptr);
190 lock.unlock();
191 for (AdapterData &a : staleAdapters)
192 cleanupAdapterData(&a);
193 staleFactory->Release();
194 for (const auto &[luid, ref] : luids)
195 refAdapter(luid, ref);
196 lock.relock();
197 for (auto it = windows.begin(), end = windows.end(); it != end; ++it)
198 updateWindowData(it.key(), &*it);
199
200 CallbackWindowList windowsThatLostTheirOutput;
201 for (QWindow *window : std::as_const(windowsWithOutput)) {
202 const auto it = windows.constFind(window);
203 if (it != windows.cend() && !it->output)
204 windowsThatLostTheirOutput.append(window);
205 }
206 if (!windowsThatLostTheirOutput.isEmpty()) {
207 const qint64 noVBlankTimestamp = 0;
208 for (const Callback &cb : std::as_const(callbacks)) {
209 if (cb)
210 cb(windowsThatLostTheirOutput, noVBlankTimestamp);
211 }
212 }
213}
214
215#ifdef QT_BUILD_INTERNAL
216void QDxgiVSyncService::simulateStaleFactory()
217{
218 QMutexLocker lock(&mutex);
219 if (!disableService && dxgiFactory)
220 recreateDxgi(lock);
221}
222#endif
223
224void QDxgiVSyncService::refAdapter(LUID luid, int count)
225{
226 QMutexLocker lock(&mutex);
227 if (disableService)
228 return;
229
230 if (!dxgiFactory) {
231 HRESULT hr = CreateDXGIFactory2(0, __uuidof(IDXGIFactory2), reinterpret_cast<void **>(&dxgiFactory));
232 if (FAILED(hr)) {
233 disableService = true;
234 qWarning("QDxgiVSyncService: CreateDXGIFactory2 failed: %s", qPrintable(QSystemError::windowsComString(hr)));
235 return;
236 }
237 if (!cleanupRegistered) {
238 qAddPostRoutine(QDxgiVSyncService::global_destroy);
239 cleanupRegistered = true;
240 }
241 }
242
243 for (AdapterData &a : adapters) {
244 if (a.luid.LowPart == luid.LowPart && a.luid.HighPart == luid.HighPart) {
245 a.ref += count;
246 return;
247 }
248 }
249
250 AdapterData a;
251 a.ref = count;
252 a.luid = luid;
253 a.adapter = nullptr;
254
255 IDXGIAdapter1 *ad;
256 for (int adapterIndex = 0; dxgiFactory->EnumAdapters1(UINT(adapterIndex), &ad) != DXGI_ERROR_NOT_FOUND; ++adapterIndex) {
257 DXGI_ADAPTER_DESC1 desc;
258 ad->GetDesc1(&desc);
259 if (desc.AdapterLuid.LowPart == luid.LowPart && desc.AdapterLuid.HighPart == luid.HighPart) {
260 a.adapter = ad;
261 break;
262 }
263 ad->Release();
264 }
265
266 if (!a.adapter) {
267 qWarning("VSyncService: Failed to find adapter (via EnumAdapters1), skipping");
268 return;
269 }
270
271 adapters.append(a);
272
273 qCDebug(lcQpaScreenUpdates) << "QDxgiVSyncService refAdapter for not yet seen adapter" << luid.LowPart << luid.HighPart;
274
275 // windows may have been registered before any adapters
276 for (auto it = windows.begin(), end = windows.end(); it != end; ++it)
277 updateWindowData(it.key(), &*it);
278}
279
280void QDxgiVSyncService::derefAdapter(LUID luid)
281{
282 QVarLengthArray<AdapterData, 4> cleanupList;
283
284 {
285 QMutexLocker lock(&mutex);
286 if (disableService)
287 return;
288
289 for (qsizetype i = 0; i < adapters.count(); ++i) {
290 AdapterData &a(adapters[i]);
291 if (a.luid.LowPart == luid.LowPart && a.luid.HighPart == luid.HighPart) {
292 if (!--a.ref) {
293 cleanupList.append(a);
294 adapters.removeAt(i);
295 }
296 break;
297 }
298 }
299 }
300
301 // the lock must *not* be held when triggering cleanup
302 for (AdapterData &a : cleanupList)
303 cleanupAdapterData(&a);
304}
305
306void QDxgiVSyncService::cleanupAdapterData(AdapterData *a)
307{
308 for (auto it = a->notifiers.begin(), end = a->notifiers.end(); it != end; ++it) {
309 qCDebug(lcQpaScreenUpdates) << "QDxgiVSyncService::cleanupAdapterData(): about to call stop()";
310 it->thread->stop();
311 qCDebug(lcQpaScreenUpdates) << "QDxgiVSyncService::cleanupAdapterData(): stop() called";
312 delete it->thread;
313 it->output->Release();
314 }
315 a->notifiers.clear();
316
317 a->adapter->Release();
318 a->adapter = nullptr;
319}
320
321void QDxgiVSyncService::cleanupWindowData(WindowData *w)
322{
323 if (w->output) {
324 w->output->Release();
325 w->output = nullptr;
326 }
327}
328
329static IDXGIOutput *outputForWindow(QWindow *w, IDXGIAdapter *adapter)
330{
331 // Generic canonical solution as per
332 // https://learn.microsoft.com/en-us/windows/win32/api/dxgi/nf-dxgi-idxgiswapchain-getcontainingoutput
333 // and
334 // https://learn.microsoft.com/en-us/windows/win32/direct3darticles/high-dynamic-range
335
336 HMONITOR monitor = nullptr;
337 QPoint center{};
338 if (w->handle()) {
339 // The returned HMONITOR will never be null unless using MONITOR_DEFAULTTONULL.
340 monitor = MonitorFromWindow(reinterpret_cast<HWND>(w->winId()), MONITOR_DEFAULTTONEAREST);
341 } else {
342 QRect wr = w->geometry();
343 wr = QRect(wr.topLeft() * w->devicePixelRatio(), wr.size() * w->devicePixelRatio());
344 center = wr.center();
345 }
346 IDXGIOutput *currentOutput = nullptr;
347 IDXGIOutput *output = nullptr;
348 for (UINT i = 0; adapter->EnumOutputs(i, &output) != DXGI_ERROR_NOT_FOUND; ++i) {
349 DXGI_OUTPUT_DESC desc;
350 if (FAILED(output->GetDesc(&desc))) {
351 output->Release();
352 continue;
353 }
354 const RECT r = desc.DesktopCoordinates;
355 const QRect dr(QPoint(r.left, r.top), QSize(r.right - r.left, r.bottom - r.top));
356 if ((monitor && desc.Monitor == monitor) || (!monitor && dr.contains(center))) {
357 currentOutput = output;
358 break;
359 } else {
360 output->Release();
361 }
362 }
363 return currentOutput; // has a ref on it, will need Release by caller
364}
365
366void QDxgiVSyncService::updateWindowData(QWindow *window, WindowData *wd)
367{
368 for (auto it = adapters.begin(), end = adapters.end(); it != end; ++it) {
369 IDXGIOutput *output = outputForWindow(window, it->adapter);
370 if (!output)
371 continue;
372
373 // Two windows on the same screen may well return two different
374 // IDXGIOutput pointers due to enumerating outputs every time; always
375 // compare the HMONITOR, not the pointer itself.
376
377 DXGI_OUTPUT_DESC desc;
378 output->GetDesc(&desc);
379
380 if (wd->output && wd->output != output) {
381 if (desc.Monitor == wd->monitor) {
382 output->Release();
383 return;
384 }
385 wd->output->Release();
386 }
387
388 wd->output = output;
389 wd->monitor = desc.Monitor;
390
391 QScreen *screen = window->screen();
392 const qreal refresh = screen ? screen->refreshRate() : 60;
393 wd->reportedRefreshIntervalMs = refresh > 0 ? 1000.0f / float(refresh) : 1000.f / 60.0f;
394
395 qCDebug(lcQpaScreenUpdates) << "QDxgiVSyncService: Output for window" << window
396 << "on the actively used adapters is now" << output
397 << "HMONITOR" << wd->monitor
398 << "refresh" << wd->reportedRefreshIntervalMs;
399
400 if (!it->notifiers.contains(wd->monitor)) {
401 output->AddRef();
402 QDxgiVSyncThread *t = new QDxgiVSyncThread(output, wd->reportedRefreshIntervalMs,
403 [this](IDXGIOutput *, HMONITOR monitor, qint64 timestampNs) {
404 CallbackWindowList w;
405 QMutexLocker lock(&mutex);
406 for (auto it = windows.cbegin(), end = windows.cend(); it != end; ++it) {
407 if (it->output && it->monitor == monitor)
408 w.append(it.key());
409 }
410 if (!w.isEmpty()) {
411#if 0
412 qDebug() << "vsync thread" << QThread::currentThread() << monitor << "window list" << w << timestampNs;
413#endif
414 for (const Callback &cb : std::as_const(callbacks)) {
415 if (cb)
416 cb(w, timestampNs);
417 }
418 }
419 });
420 t->start(QThread::TimeCriticalPriority);
421 it->notifiers.insert(wd->monitor, { wd->output, t });
422 }
423 return;
424 }
425
426 // If we get here, there is no IDXGIOutput and supportsWindow() will return false for this window.
427 // This is perfectly normal when using an adapter such as WARP.
428}
429
430void QDxgiVSyncService::registerWindow(QWindow *window)
431{
432 QMutexLocker lock(&mutex);
433 if (disableService || windows.contains(window))
434 return;
435
436 if (window->format().swapInterval() == 0) {
437 qCDebug(lcQpaScreenUpdates) << "QDxgiVSyncService: window" << window
438 << "has swapInterval 0, skipping this window";
439 return;
440 }
441
442 qCDebug(lcQpaScreenUpdates) << "QDxgiVSyncService: adding window" << window;
443
444 WindowData wd;
445 wd.output = nullptr;
446 updateWindowData(window, &wd);
447 windows.insert(window, wd);
448
449 QObject::connect(window, &QWindow::screenChanged, window, [this, window](QScreen *screen) {
450 qCDebug(lcQpaScreenUpdates) << "QDxgiVSyncService: screen changed for window:" << window << screen;
451 QMutexLocker lock(&mutex);
452 recreateDxgiIfStale(lock);
453 auto it = windows.find(window);
454 if (it != windows.end())
455 updateWindowData(window, &*it);
456 }, Qt::QueuedConnection); // intentionally using Queued
457 // It has been observed that with DirectConnection _sometimes_ we do not
458 // find any IDXGIOutput for the window when moving it to a different screen.
459 // Add a delay by going through the event loop.
460
461 // Ensure a missed unregisterWindow() does not leave a dangling QWindow pointer
462 // behind. unregisterWindow() only ever uses the pointer as an opaque hash key, so
463 // this is safe to call on QObject::destroyed even though the QWindow part of the
464 // object has already been destroyed by this point.
465 QObject::connect(window, &QObject::destroyed, window, [this, window](QObject *) {
466 qCDebug(lcQpaScreenUpdates)
467 << "QDxgiVSyncService: window destroyed, pruning stale registration for:"
468 << window;
469 unregisterWindow(window);
470 }, Qt::DirectConnection);
471}
472
473void QDxgiVSyncService::unregisterWindow(QWindow *window)
474{
475 QMutexLocker lock(&mutex);
476 auto it = windows.find(window);
477 if (it == windows.end())
478 return;
479
480 qCDebug(lcQpaScreenUpdates) << "QDxgiVSyncService: removing window" << window;
481
482 cleanupWindowData(&*it);
483
484 windows.remove(window);
485}
486
487bool QDxgiVSyncService::supportsWindow(QWindow *window)
488{
489 QMutexLocker lock(&mutex);
490 auto it = windows.constFind(window);
491 return it != windows.cend() ? (it->output != nullptr) : false;
492}
493
494qsizetype QDxgiVSyncService::registerCallback(Callback cb)
495{
496 QMutexLocker lock(&mutex);
497 for (qsizetype i = 0; i < callbacks.count(); ++i) {
498 if (!callbacks[i]) {
499 callbacks[i] = cb;
500 return i + 1;
501 }
502 }
503 callbacks.append(cb);
504 return callbacks.count();
505}
506
507void QDxgiVSyncService::unregisterCallback(qsizetype id)
508{
509 QMutexLocker lock(&mutex);
510 const qsizetype index = id - 1;
511 if (index >= 0 && index < callbacks.count())
512 callbacks[index] = nullptr;
513}
514
515QT_END_NAMESPACE
QDxgiVSyncThread(IDXGIOutput *output, float vsyncIntervalMsReportedForScreen, Callback callback)
void run() override
Combined button and popup list for selecting options.
static IDXGIOutput * outputForWindow(QWindow *w, IDXGIAdapter *adapter)
QT_BEGIN_NAMESPACE Q_STATIC_LOGGING_CATEGORY(lcSynthesizedIterableAccess, "qt.iterable.synthesized", QtWarningMsg)