forked from mixxxdj/mixxx
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcontrollerrenderingengine.cpp
More file actions
423 lines (362 loc) · 14.5 KB
/
Copy pathcontrollerrenderingengine.cpp
File metadata and controls
423 lines (362 loc) · 14.5 KB
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
#include "controllers/rendering/controllerrenderingengine.h"
#include <QOffscreenSurface>
#include <QOpenGLContext>
#include <QOpenGLFramebufferObject>
#include <QOpenGLFunctions>
#include <QQmlEngine>
#include <QQuickGraphicsDevice>
#include <QQuickRenderControl>
#include <QQuickRenderTarget>
#include <QQuickWindow>
#include <QThread>
#include "controllers/controller.h"
#include "controllers/controllerenginethreadcontrol.h"
#include "controllers/scripting/legacy/controllerscriptenginelegacy.h"
#include "controllers/scripting/legacy/controllerscriptinterfacelegacy.h"
#include "moc_controllerrenderingengine.cpp"
#include "qml/qmlwaveformoverview.h"
#include "util/cmdlineargs.h"
#include "util/logger.h"
#include "util/thread_affinity.h"
#include "util/time.h"
#include "util/timer.h"
// Used in the renderFrame method to properly abort the rendering and terminate the engine.
#define VERIFY_OR_TERMINATE(cond, msg) \
VERIFY_OR_DEBUG_ASSERT(cond) { \
kLogger.warning() << msg; \
m_pThread->quit(); \
return; \
}
namespace {
const mixxx::Logger kLogger("ControllerRenderingEngine");
} // anonymous namespace
using Clock = std::chrono::steady_clock;
ControllerRenderingEngine::ControllerRenderingEngine(
const LegacyControllerMapping::ScreenInfo& info,
gsl::not_null<ControllerEngineThreadControl*> engineThreadControl)
: QObject(),
m_screenInfo(info),
m_GLDataFormat(GL_RGBA),
m_GLDataType(GL_UNSIGNED_BYTE),
m_isValid(true),
m_pEngineThreadControl(engineThreadControl) {
switch (m_screenInfo.pixelFormat) {
case QImage::Format_RGB16:
m_GLDataFormat = GL_RGB;
if (m_screenInfo.reversedColor) {
#ifdef QT_OPENGL_ES_2
m_isValid = false;
kLogger.critical() << "Reversed RGB16 format is not supported in OpenGL ES";
#else
m_GLDataType = GL_UNSIGNED_SHORT_5_6_5_REV;
#endif
} else {
m_GLDataType = GL_UNSIGNED_SHORT_5_6_5;
}
break;
case QImage::Format_RGB888:
if (m_screenInfo.reversedColor) {
#ifdef QT_OPENGL_ES_2
m_isValid = false;
kLogger.critical() << "Reversed RGB8 format is not supported in OpenGL ES";
#else
m_GLDataFormat = GL_BGR;
#endif
} else {
m_GLDataFormat = GL_RGB;
}
m_GLDataType = GL_UNSIGNED_BYTE;
break;
case QImage::Format_RGBA8888:
if (m_screenInfo.reversedColor) {
#ifdef __EMSCRIPTEN__
m_isValid = false;
kLogger.critical() << "Reversed RGBA format is not supported in Emscripten/WebAssembly";
#else
m_GLDataFormat = GL_BGRA;
#endif
} else {
m_GLDataFormat = GL_RGBA;
}
m_GLDataType = GL_UNSIGNED_BYTE;
break;
default:
m_isValid = false;
}
if (!m_isValid) {
DEBUG_ASSERT(!"Unsupported format");
return;
}
prepare();
}
void ControllerRenderingEngine::prepare() {
m_pThread = std::make_unique<QThread>();
m_pThread->setObjectName("ControllerScreenRenderer");
#if QT_VERSION >= QT_VERSION_CHECK(6, 7, 0)
[[maybe_unused]] bool successful = moveToThread(m_pThread.get());
DEBUG_ASSERT(successful);
#else
moveToThread(m_pThread.get());
#endif
// these at first sight weird-looking connections facilitate thread-safe communication.
connect(this,
&ControllerRenderingEngine::sendFrameDataRequested,
this,
&ControllerRenderingEngine::send);
connect(m_pThread.get(),
&QThread::finished,
this,
&ControllerRenderingEngine::finish);
m_pThread->start(QThread::NormalPriority);
}
ControllerRenderingEngine::~ControllerRenderingEngine() {
DEBUG_ASSERT_THIS_QOBJECT_THREAD_ANTI_AFFINITY();
m_pThread->wait();
VERIFY_OR_DEBUG_ASSERT(!m_fbo) {
kLogger.critical() << "The ControllerEngine is being deleted but hasn't been "
"cleaned up. Brace for impact";
};
}
void ControllerRenderingEngine::start() {
VERIFY_OR_DEBUG_ASSERT(!thread()->isFinished() && !thread()->isInterruptionRequested()) {
kLogger.critical() << "Render thread has or is about to terminate. Cannot "
"start this render anymore.";
return;
}
QCoreApplication::postEvent(this, new QEvent(QEvent::UpdateRequest));
}
bool ControllerRenderingEngine::isRunning() const {
return m_pThread && m_pThread->isRunning();
}
void ControllerRenderingEngine::requestEngineSetup(std::shared_ptr<QQmlEngine> qmlEngine) {
DEBUG_ASSERT(!m_quickWindow);
VERIFY_OR_DEBUG_ASSERT(qmlEngine) {
kLogger.critical() << "No QML engine was passed!";
return;
}
VERIFY_OR_DEBUG_ASSERT_THIS_QOBJECT_THREAD_ANTI_AFFINITY() {
kLogger.warning() << "Unable to setup OpenGL rendering context from the same "
"thread as the render object";
return;
}
QMetaObject::invokeMethod(
this,
[this, qmlEngine]() {
setup(qmlEngine);
},
// This invocation will block the current thread!
Qt::BlockingQueuedConnection);
if (m_quickWindow) {
m_renderControl->prepareThread(m_pThread.get());
}
}
void ControllerRenderingEngine::requestSendingFrameData(
Controller* controller, const QByteArray& frame) {
emit sendFrameDataRequested(controller, frame);
}
void ControllerRenderingEngine::setup(std::shared_ptr<QQmlEngine> qmlEngine) {
VERIFY_OR_DEBUG_ASSERT_THIS_QOBJECT_THREAD_AFFINITY() {
kLogger.warning() << "The ControllerRenderingEngine setup must be done by its own thread!";
return;
}
QSurfaceFormat format;
format.setSamples(m_screenInfo.msaa);
format.setDepthBufferSize(16);
format.setStencilBufferSize(8);
m_context = std::make_unique<QOpenGLContext>();
m_context->setFormat(format);
VERIFY_OR_DEBUG_ASSERT(m_context->create()) {
kLogger.warning() << "Unable to initialize controller screen rendering. Giving up";
return;
}
connect(m_context.get(),
&QOpenGLContext::aboutToBeDestroyed,
this,
&ControllerRenderingEngine::finish);
m_offscreenSurface = std::make_unique<QOffscreenSurface>();
m_offscreenSurface->setFormat(m_context->format());
// offscreen surface needs to be created from application main thread.
VERIFY_OR_DEBUG_ASSERT(QMetaObject::invokeMethod(
qApp,
[this] {
m_offscreenSurface->create();
},
// This invocation will block the current thread!
Qt::BlockingQueuedConnection) &&
m_offscreenSurface->isValid()) {
kLogger.warning() << "Unable to create the OffscreenSurface for controller "
"screen rendering. Giving up";
m_offscreenSurface.reset();
return;
}
m_renderControl = std::make_unique<QQuickRenderControl>(this);
m_quickWindow = std::make_unique<QQuickWindow>(m_renderControl.get());
if (!qmlEngine->incubationController()) {
qmlEngine->setIncubationController(m_quickWindow->incubationController());
}
m_quickWindow->setGeometry(0, 0, m_screenInfo.size.width(), m_screenInfo.size.height());
}
void ControllerRenderingEngine::finish() {
DEBUG_ASSERT_THIS_QOBJECT_THREAD_AFFINITY();
emit stopping();
m_isValid = false;
if (m_context && m_context->isValid()) {
disconnect(m_context.get(),
&QOpenGLContext::aboutToBeDestroyed,
this,
&ControllerRenderingEngine::finish);
m_context->makeCurrent(m_offscreenSurface.get());
m_renderControl.reset();
std::shared_ptr<QOffscreenSurface> pOffscreenSurface = std::move(m_offscreenSurface);
QMetaObject::invokeMethod(
qApp,
[pOffscreenSurface] {
pOffscreenSurface->destroy();
});
m_quickWindow.reset();
// Free the engine and FBO.
m_fbo.reset();
m_context->doneCurrent();
}
m_context.reset();
}
void ControllerRenderingEngine::renderFrame() {
ScopedTimer t(QStringLiteral("ControllerRenderingEngine::renderFrame"));
if (!m_isValid) {
DEBUG_ASSERT(!"Trying to render frame on an invalid engine");
return;
}
VERIFY_OR_TERMINATE(m_offscreenSurface->isValid(), "OffscreenSurface isn't valid anymore.");
VERIFY_OR_TERMINATE(m_context->isValid(), "GLContext isn't valid anymore.");
VERIFY_OR_TERMINATE(m_context->makeCurrent(m_offscreenSurface.get()),
"Couldn't make the GLContext current to the OffscreenSurface.");
if (!m_fbo) {
ScopedTimer t(QStringLiteral("ControllerRenderingEngine::renderFrame::initFBO"));
VERIFY_OR_TERMINATE(
QOpenGLFramebufferObject::hasOpenGLFramebufferObjects(),
"OpenGL doesn't support FBO");
m_fbo = std::make_unique<QOpenGLFramebufferObject>(
m_screenInfo.size, QOpenGLFramebufferObject::CombinedDepthStencil);
GLenum glError;
glError = m_context->functions()->glGetError();
VERIFY_OR_TERMINATE(glError == GL_NO_ERROR, "GLError: " << glError);
VERIFY_OR_TERMINATE(m_fbo->isValid(), "Failed to initialize FBO");
m_quickWindow->setGraphicsDevice(QQuickGraphicsDevice::fromOpenGLContext(m_context.get()));
VERIFY_OR_TERMINATE(m_renderControl->initialize(),
"Failed to initialize redirected Qt Quick rendering");
m_quickWindow->setRenderTarget(QQuickRenderTarget::fromOpenGLTexture(m_fbo->texture(),
m_screenInfo.size));
m_quickWindow->setGeometry(0, 0, m_screenInfo.size.width(), m_screenInfo.size.height());
}
m_nextFrameStart = Clock::now();
m_renderControl->beginFrame();
if (m_pEngineThreadControl) {
m_pEngineThreadControl->pause();
}
m_renderControl->polishItems();
{
ScopedTimer t(QStringLiteral("ControllerRenderingEngine::renderFrame::sync"));
VERIFY_OR_DEBUG_ASSERT(m_renderControl->sync()) {
kLogger.warning() << "Couldn't sync the render control. Scene may be stuck";
};
}
if (m_pEngineThreadControl) {
m_pEngineThreadControl->resume();
}
QImage fboImage(m_screenInfo.size, m_screenInfo.pixelFormat);
VERIFY_OR_DEBUG_ASSERT(m_fbo->bind()) {
kLogger.warning() << "Couldn't bind the FBO.";
}
GLenum glError;
m_context->functions()->glFlush();
glError = m_context->functions()->glGetError();
VERIFY_OR_TERMINATE(glError == GL_NO_ERROR, "GLError: " << glError);
if (static_cast<std::endian>(m_screenInfo.endian) != std::endian::native) {
#ifdef QT_OPENGL_ES_2
kLogger.critical()
<< "Screen endianness mismatches native endianness, but OpenGL "
"ES does not let us specify a reverse pixel store order. "
"This will likely lead to invalid colors.";
#else
m_context->functions()->glPixelStorei(GL_PACK_SWAP_BYTES, GL_TRUE);
#endif
}
glError = m_context->functions()->glGetError();
VERIFY_OR_TERMINATE(glError == GL_NO_ERROR, "GLError: " << glError);
QDateTime timestamp = QDateTime::currentDateTime();
m_renderControl->render();
m_renderControl->endFrame();
// Flush any remaining GL errors.
while ((glError = m_context->functions()->glGetError()) != GL_NO_ERROR) {
kLogger.debug() << "Retrieved a previously unhandled GL error: " << glError;
}
{
ScopedTimer t(QStringLiteral("ControllerRenderingEngine::renderFrame::glReadPixels"));
m_context->functions()->glReadPixels(0,
0,
m_screenInfo.size.width(),
m_screenInfo.size.height(),
m_GLDataFormat,
m_GLDataType,
fboImage.bits());
}
glError = m_context->functions()->glGetError();
VERIFY_OR_TERMINATE(glError == GL_NO_ERROR, "GLError: " << glError);
VERIFY_OR_DEBUG_ASSERT(!fboImage.isNull()) {
kLogger.warning() << "Screen frame is null!";
}
VERIFY_OR_DEBUG_ASSERT(m_fbo->release()) {
kLogger.debug() << "Couldn't release the FBO.";
}
fboImage.mirror(false, true);
emit frameRendered(m_screenInfo, fboImage.copy(), timestamp);
m_context->doneCurrent();
}
bool ControllerRenderingEngine::stop() {
m_pThread->quit();
return m_pThread->wait();
}
void ControllerRenderingEngine::send(Controller* controller, const QByteArray& frame) {
DEBUG_ASSERT_THIS_QOBJECT_THREAD_AFFINITY();
ScopedTimer t(QStringLiteral("ControllerRenderingEngine::send"));
if (!frame.isEmpty()) {
VERIFY_OR_TERMINATE(controller->sendBytes(frame), "Unable to send frame to device");
}
if (CmdlineArgs::Instance()
.getControllerDebug()) {
auto endOfFrameCycle = Clock::now();
kLogger.debug()
<< "Frame took "
<< std::chrono::duration_cast<std::chrono::milliseconds>(
endOfFrameCycle - m_nextFrameStart)
.count()
<< "milliseconds and frame has" << frame.size() << "bytes";
}
m_nextFrameStart += std::chrono::microseconds(1000000 / m_screenInfo.target_fps);
auto durationToWaitBeforeFrame =
std::chrono::duration_cast<std::chrono::milliseconds>(
m_nextFrameStart - Clock::now());
if (durationToWaitBeforeFrame > std::chrono::milliseconds(0)) {
if (CmdlineArgs::Instance()
.getControllerDebug()) {
kLogger.debug() << "Waiting for "
<< durationToWaitBeforeFrame.count()
<< "milliseconds before rendering next frame";
}
QTimer::singleShot(durationToWaitBeforeFrame,
Qt::PreciseTimer,
this,
&ControllerRenderingEngine::renderFrame);
} else {
QCoreApplication::postEvent(this, new QEvent(QEvent::UpdateRequest));
}
}
bool ControllerRenderingEngine::event(QEvent* event) {
// In case there is a request for update (e.g using QWindow::requestUpdate),
// we emit the signal to request rendering using the engine.
if (event->type() == QEvent::UpdateRequest) {
renderFrame();
return true;
}
return QObject::event(event);
}