7#include <QWaitCondition>
8#include <QElapsedTimer>
9#include <QCoreApplication>
10#include <QLoggingCategory>
12#include <QVarLengthArray>
13#include <QtCore/private/qsystemerror_p.h>
17using namespace Qt::StringLiterals;
26 QDxgiVSyncThread(IDXGIOutput *output,
float vsyncIntervalMsReportedForScreen, Callback callback);
32 float vsyncIntervalMsReportedForScreen;
42 vsyncIntervalMsReportedForScreen(vsyncIntervalMsReportedForScreen),
45 QThread::setObjectName(u"QDxgiVSyncThread"_s);
47 DXGI_OUTPUT_DESC desc;
48 output->GetDesc(&desc);
49 monitor = desc.Monitor;
54 qCDebug(lcQpaScreenUpdates) <<
"QDxgiVSyncThread" <<
this <<
"for output" << output <<
"monitor" << monitor <<
"entered run()";
55 QElapsedTimer timestamp;
56 QElapsedTimer elapsed;
58 while (!quit.loadAcquire()) {
60 HRESULT hr = output->WaitForVBlank();
61 if (FAILED(hr) || elapsed.nsecsElapsed() <= 1000000) {
66 QThread::msleep((
unsigned long) vsyncIntervalMsReportedForScreen);
68 callback(output, monitor, timestamp.nsecsElapsed());
71 qCDebug(lcQpaScreenUpdates) <<
"QDxgiVSyncThread" <<
this <<
"is stopping";
75 qCDebug(lcQpaScreenUpdates) <<
"QDxgiVSyncThread" <<
this <<
"run() out";
81 qCDebug(lcQpaScreenUpdates) <<
"Requesting QDxgiVSyncThread stop from thread" << QThread::currentThread() <<
"on" <<
this;
82 if (isRunning() && !quit.loadAcquire()) {
90QDxgiVSyncService *QDxgiVSyncService::instance()
92 static QDxgiVSyncService service;
96QDxgiVSyncService::QDxgiVSyncService()
98 qCDebug(lcQpaScreenUpdates) <<
"New QDxgiVSyncService" <<
this;
100 disableService = qEnvironmentVariableIntValue(
"QT_D3D_NO_VBLANK_THREAD");
101 if (disableService) {
102 qCDebug(lcQpaScreenUpdates) <<
"QDxgiVSyncService disabled by environment";
107QDxgiVSyncService::~QDxgiVSyncService()
109 qCDebug(lcQpaScreenUpdates) <<
"~QDxgiVSyncService" <<
this;
114 qWarning(
"QDxgiVSyncService not destroyed in time");
117void QDxgiVSyncService::global_destroy()
119 QDxgiVSyncService *inst = QDxgiVSyncService::instance();
120 inst->cleanupRegistered =
false;
124void QDxgiVSyncService::destroy()
126 qCDebug(lcQpaScreenUpdates) <<
"QDxgiVSyncService::destroy()";
131 for (
auto it = windows.begin(), end = windows.end(); it != end; ++it)
132 cleanupWindowData(&*it);
138void QDxgiVSyncService::teardownDxgi()
140 for (
auto it = adapters.begin(), end = adapters.end(); it != end; ++it)
141 cleanupAdapterData(&*it);
145 dxgiFactory->Release();
146 dxgiFactory =
nullptr;
149 qCDebug(lcQpaScreenUpdates) <<
"QDxgiVSyncService DXGI teardown complete";
152void QDxgiVSyncService::beginFrame(LUID)
154 QMutexLocker lock(&mutex);
166 recreateDxgiIfStale(lock);
169void QDxgiVSyncService::recreateDxgiIfStale(QMutexLocker<QMutex> &lock)
171 if (dxgiFactory && !dxgiFactory->IsCurrent()) {
172 qCDebug(lcQpaScreenUpdates,
"QDxgiVSyncService: DXGI Factory is no longer Current");
177void QDxgiVSyncService::recreateDxgi(QMutexLocker<QMutex> &lock)
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) {
185 windowsWithOutput.append(it.key());
186 cleanupWindowData(&*it);
188 QVector<AdapterData> staleAdapters = std::exchange(adapters, {});
189 IDXGIFactory2 *staleFactory = std::exchange(dxgiFactory,
nullptr);
191 for (AdapterData &a : staleAdapters)
192 cleanupAdapterData(&a);
193 staleFactory->Release();
194 for (
const auto &[luid, ref] : luids)
195 refAdapter(luid, ref);
197 for (
auto it = windows.begin(), end = windows.end(); it != end; ++it)
198 updateWindowData(it.key(), &*it);
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);
206 if (!windowsThatLostTheirOutput.isEmpty()) {
207 const qint64 noVBlankTimestamp = 0;
208 for (
const Callback &cb : std::as_const(callbacks)) {
210 cb(windowsThatLostTheirOutput, noVBlankTimestamp);
215#ifdef QT_BUILD_INTERNAL
216void QDxgiVSyncService::simulateStaleFactory()
218 QMutexLocker lock(&mutex);
219 if (!disableService && dxgiFactory)
224void QDxgiVSyncService::refAdapter(LUID luid,
int count)
226 QMutexLocker lock(&mutex);
231 HRESULT hr = CreateDXGIFactory2(0, __uuidof(IDXGIFactory2),
reinterpret_cast<
void **>(&dxgiFactory));
233 disableService =
true;
234 qWarning(
"QDxgiVSyncService: CreateDXGIFactory2 failed: %s", qPrintable(QSystemError::windowsComString(hr)));
237 if (!cleanupRegistered) {
238 qAddPostRoutine(QDxgiVSyncService::global_destroy);
239 cleanupRegistered =
true;
243 for (AdapterData &a : adapters) {
244 if (a.luid.LowPart == luid.LowPart && a.luid.HighPart == luid.HighPart) {
256 for (
int adapterIndex = 0; dxgiFactory->EnumAdapters1(UINT(adapterIndex), &ad) != DXGI_ERROR_NOT_FOUND; ++adapterIndex) {
257 DXGI_ADAPTER_DESC1 desc;
259 if (desc.AdapterLuid.LowPart == luid.LowPart && desc.AdapterLuid.HighPart == luid.HighPart) {
267 qWarning(
"VSyncService: Failed to find adapter (via EnumAdapters1), skipping");
273 qCDebug(lcQpaScreenUpdates) <<
"QDxgiVSyncService refAdapter for not yet seen adapter" << luid.LowPart << luid.HighPart;
276 for (
auto it = windows.begin(), end = windows.end(); it != end; ++it)
277 updateWindowData(it.key(), &*it);
280void QDxgiVSyncService::derefAdapter(LUID luid)
282 QVarLengthArray<AdapterData, 4> cleanupList;
285 QMutexLocker lock(&mutex);
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) {
293 cleanupList.append(a);
294 adapters.removeAt(i);
302 for (AdapterData &a : cleanupList)
303 cleanupAdapterData(&a);
306void QDxgiVSyncService::cleanupAdapterData(AdapterData *a)
308 for (
auto it = a->notifiers.begin(), end = a->notifiers.end(); it != end; ++it) {
309 qCDebug(lcQpaScreenUpdates) <<
"QDxgiVSyncService::cleanupAdapterData(): about to call stop()";
311 qCDebug(lcQpaScreenUpdates) <<
"QDxgiVSyncService::cleanupAdapterData(): stop() called";
313 it->output->Release();
315 a->notifiers.clear();
317 a->adapter->Release();
318 a->adapter =
nullptr;
321void QDxgiVSyncService::cleanupWindowData(WindowData *w)
324 w->output->Release();
336 HMONITOR monitor =
nullptr;
340 monitor = MonitorFromWindow(
reinterpret_cast<HWND>(w->winId()), MONITOR_DEFAULTTONEAREST);
342 QRect wr = w->geometry();
343 wr = QRect(wr.topLeft() * w->devicePixelRatio(), wr.size() * w->devicePixelRatio());
344 center = wr.center();
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))) {
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;
363 return currentOutput;
366void QDxgiVSyncService::updateWindowData(QWindow *window, WindowData *wd)
368 for (
auto it = adapters.begin(), end = adapters.end(); it != end; ++it) {
369 IDXGIOutput *output = outputForWindow(window, it->adapter);
377 DXGI_OUTPUT_DESC desc;
378 output->GetDesc(&desc);
380 if (wd->output && wd->output != output) {
381 if (desc.Monitor == wd->monitor) {
385 wd->output->Release();
389 wd->monitor = desc.Monitor;
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;
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;
400 if (!it->notifiers.contains(wd->monitor)) {
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)
412 qDebug() <<
"vsync thread" << QThread::currentThread() << monitor <<
"window list" << w << timestampNs;
414 for (
const Callback &cb : std::as_const(callbacks)) {
420 t->start(QThread::TimeCriticalPriority);
421 it->notifiers.insert(wd->monitor, { wd->output, t });
430void QDxgiVSyncService::registerWindow(QWindow *window)
432 QMutexLocker lock(&mutex);
433 if (disableService || windows.contains(window))
436 if (window->format().swapInterval() == 0) {
437 qCDebug(lcQpaScreenUpdates) <<
"QDxgiVSyncService: window" << window
438 <<
"has swapInterval 0, skipping this window";
442 qCDebug(lcQpaScreenUpdates) <<
"QDxgiVSyncService: adding window" << window;
446 updateWindowData(window, &wd);
447 windows.insert(window, wd);
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);
465 QObject::connect(window, &QObject::destroyed, window, [
this, window](QObject *) {
466 qCDebug(lcQpaScreenUpdates)
467 <<
"QDxgiVSyncService: window destroyed, pruning stale registration for:"
469 unregisterWindow(window);
470 }, Qt::DirectConnection);
473void QDxgiVSyncService::unregisterWindow(QWindow *window)
475 QMutexLocker lock(&mutex);
476 auto it = windows.find(window);
477 if (it == windows.end())
480 qCDebug(lcQpaScreenUpdates) <<
"QDxgiVSyncService: removing window" << window;
482 cleanupWindowData(&*it);
484 windows.remove(window);
487bool QDxgiVSyncService::supportsWindow(QWindow *window)
489 QMutexLocker lock(&mutex);
490 auto it = windows.constFind(window);
491 return it != windows.cend() ? (it->output !=
nullptr) :
false;
494qsizetype QDxgiVSyncService::registerCallback(Callback cb)
496 QMutexLocker lock(&mutex);
497 for (qsizetype i = 0; i < callbacks.count(); ++i) {
503 callbacks.append(cb);
504 return callbacks.count();
507void QDxgiVSyncService::unregisterCallback(qsizetype id)
509 QMutexLocker lock(&mutex);
510 const qsizetype index = id - 1;
511 if (index >= 0 && index < callbacks.count())
512 callbacks[index] =
nullptr;
QDxgiVSyncThread(IDXGIOutput *output, float vsyncIntervalMsReportedForScreen, Callback callback)
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)