summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorAnton <anton@picapica.im>2026-08-16 03:28:51 +0400
committerAnton <anton@picapica.im>2026-08-16 03:28:51 +0400
commit1b7b9d46c84c38cbf2df293113a687481e205585 (patch)
tree59f95bc2900e5e12141d40777e332ce4e2ee91d6
parentad95ec8759777c4b8df0dcd66fd8200d24e912b1 (diff)
downloadpica-pica-1b7b9d46c84c38cbf2df293113a687481e205585.tar.gz
pica-pica-1b7b9d46c84c38cbf2df293113a687481e205585.zip
pica-client: VAAPI on X11, two codepaths
-rw-r--r--Makefile.am15
-rw-r--r--configure.ac36
-rw-r--r--pica-client/audiovideocallcontroller.cpp23
-rw-r--r--pica-client/audiovideocallcontroller.h3
-rw-r--r--pica-client/callwindow.cpp35
-rw-r--r--pica-client/callwindow.h16
-rw-r--r--pica-client/dialogs/settingsdialog.cpp41
-rw-r--r--pica-client/dialogs/settingsdialog.h4
-rw-r--r--pica-client/main.cpp10
-rw-r--r--pica-client/vaapi.cpp229
-rw-r--r--pica-client/vaapi.h73
-rw-r--r--pica-client/vaapivideowidget.cpp62
-rw-r--r--pica-client/vaapivideowidget.h34
-rw-r--r--pica-client/vaapix11widget.cpp237
-rw-r--r--pica-client/vaapix11widget.h97
-rw-r--r--pica-client/videodevice.cpp10
-rw-r--r--pica-client/videodevice.h11
17 files changed, 871 insertions, 65 deletions
diff --git a/Makefile.am b/Makefile.am
index 88e9853..fa97f67 100644
--- a/Makefile.am
+++ b/Makefile.am
@@ -203,6 +203,21 @@ pica_client_pica_client_LDADD += $(VAAPI_LIBS) -lGL
MOCFLAGS += -DHAVE_VAAPI
endif
+# Drawing a decoded surface in an X11 session, where Qt's OpenGL contexts come
+# from GLX and cannot import DMA-BUF handles: the driver draws the surface
+# straight onto the widget's X window instead.
+if PICA_VAAPI_X11
+pica_client_pica_client_SOURCES += \
+pica-client/vaapix11widget.cpp \
+pica-client/vaapix11widget.h
+
+nodist_pica_client_pica_client_SOURCES += moc_vaapix11widget.cpp
+
+pica_client_pica_client_CPPFLAGS += $(VAAPI_X11_CFLAGS)
+pica_client_pica_client_LDADD += $(VAAPI_X11_LIBS)
+MOCFLAGS += -DHAVE_VAAPI_X11
+endif
+
pkgpicaclientdir = ${datarootdir}/pica-client
dist_pkgpicaclient_DATA = \
dhparam4096.pem \
diff --git a/configure.ac b/configure.ac
index b8bcc02..2db202c 100644
--- a/configure.ac
+++ b/configure.ac
@@ -92,6 +92,19 @@ AC_ARG_ENABLE([vaapi],
AS_HELP_STRING([--disable-vaapi],
[Disable VAAPI accelerated video encoding, decoding and rendering]))
+#checking if the X11 rendering path is wanted
+#Qt gives widgets a GLX context by default in an X11 session, and a GLX
+#context has no way to import the DMA-BUF handles a VA surface is exported
+#as - that path needs EGL. vaPutSurface() leaves OpenGL out of it altogether
+#and has the driver draw the surface straight onto an X11 window, which is
+#what makes hardware rendering work in such a session. Autodetected like
+#VAAPI itself, and pointless without it.
+AC_ARG_ENABLE([vaapi-x11],
+ AS_HELP_STRING([--enable-vaapi-x11],
+ [Enable vaPutSurface() rendering, for X11 sessions where Qt uses GLX rather than EGL (default: autodetect)])
+ AS_HELP_STRING([--disable-vaapi-x11],
+ [Disable vaPutSurface() rendering]))
+
#at least one program must be enabled
AS_IF([test "x$PICA_NODE_ENABLED" != "xyes" && test "x$PICA_CLIENT_ENABLED" != "xyes" ],
AC_MSG_ERROR(["Either pica-node or pica-client must be enabled"])
@@ -159,9 +172,32 @@ AS_IF([test "x$enable_vaapi" != "xno"], [
[AC_MSG_WARN(["libva, libva-drm or EGL not found - building without VAAPI acceleration"])])
])
])
+
+#check for libva's X11 rendering support, needed to draw a decoded surface in
+#an X11 session, where Qt's OpenGL contexts are GLX rather than EGL ones.
+#libGL comes along because working out which of the two a session gives means
+#asking GLX whether it owns the context.
+AS_IF([test "x$enable_vaapi_x11" = "xyes" && test "x$PICA_VAAPI_ENABLED" != "xyes"],
+ [AC_MSG_ERROR(["X11 rendering was requested but VAAPI support is not enabled"])])
+
+AS_IF([test "x$PICA_VAAPI_ENABLED" = "xyes" && test "x$enable_vaapi_x11" != "xno"], [
+ PKG_CHECK_MODULES([VAAPI_X11], [libva-x11 x11 gl],
+ [
+ PICA_VAAPI_X11_ENABLED=yes
+ AC_DEFINE([HAVE_VAAPI_X11], [1], [Define to 1 if libva X11 rendering support is available])
+ AC_SUBST([VAAPI_X11_CFLAGS])
+ AC_SUBST([VAAPI_X11_LIBS])
+ ],
+ [
+ AS_IF([test "x$enable_vaapi_x11" = "xyes"],
+ [AC_MSG_ERROR(["X11 rendering was requested but libva-x11, libX11 or libGL was not found"])],
+ [AC_MSG_WARN(["libva-x11, libX11 or libGL not found - building without X11 rendering, hardware rendering will need an EGL session"])])
+ ])
+])
])
AM_CONDITIONAL([PICA_VAAPI], [test "x$PICA_VAAPI_ENABLED" = "xyes"])
+AM_CONDITIONAL([PICA_VAAPI_X11], [test "x$PICA_VAAPI_X11_ENABLED" = "xyes"])
AC_SUBST([PLATFORM_DEPS_CFLAGS])
AC_SUBST([PLATFORM_DEPS_LIBS])
diff --git a/pica-client/audiovideocallcontroller.cpp b/pica-client/audiovideocallcontroller.cpp
index 59ffad9..7d3875c 100644
--- a/pica-client/audiovideocallcontroller.cpp
+++ b/pica-client/audiovideocallcontroller.cpp
@@ -313,6 +313,7 @@ void AudioVideoCallController::start_call(QByteArray peer_id)
connect(remotevideo, SIGNAL(frameReady(QImage)), callwindow, SLOT(showRemoteFrame(QImage)));
#ifdef HAVE_VAAPI
connect(remotevideo, SIGNAL(hwFrameReady(AVFramePtr)), callwindow, SLOT(showRemoteHwFrame(AVFramePtr)));
+ connect(callwindow, SIGNAL(video_rendering_failed()), this, SLOT(video_rendering_failed()));
#endif
callwindow->show();
}
@@ -335,6 +336,7 @@ void AudioVideoCallController::call_from(QByteArray peer_id)
connect(remotevideo, SIGNAL(frameReady(QImage)), callwindow, SLOT(showRemoteFrame(QImage)));
#ifdef HAVE_VAAPI
connect(remotevideo, SIGNAL(hwFrameReady(AVFramePtr)), callwindow, SLOT(showRemoteHwFrame(AVFramePtr)));
+ connect(callwindow, SIGNAL(video_rendering_failed()), this, SLOT(video_rendering_failed()));
#endif
callwindow->show();
@@ -467,6 +469,13 @@ void AudioVideoCallController::incoming_video_params(QByteArray peer_id, QString
bool vaapiDecoding = st.loadValue("video.vaapi_decoding", 0).toBool();
bool vaapiRendering = st.loadValue("video.vaapi_rendering", 0).toBool();
+#ifdef HAVE_VAAPI
+ // A call started after one where drawing GPU frames turned out not to work
+ // would otherwise begin with a blank video area all over again.
+ if (VaapiRenderWidget::renderingKnownBroken())
+ vaapiRendering = false;
+#endif
+
QMetaObject::invokeMethod(remotevideo, "configurePlayback", Qt::QueuedConnection,
Q_ARG(QString, codec), Q_ARG(int, (int)width), Q_ARG(int, (int)height),
Q_ARG(bool, vaapiDecoding), Q_ARG(bool, vaapiRendering));
@@ -489,3 +498,17 @@ void AudioVideoCallController::incoming_video_packet(QByteArray peer_id, quint16
remotevideo->enqueueFrame(frame);
}
+#ifdef HAVE_VAAPI
+void AudioVideoCallController::video_rendering_failed()
+{
+ // The window cannot draw frames that stayed in GPU memory, so stop keeping
+ // them there: the decoder brings them down into system memory instead and
+ // the window's label shows them. Decoding itself is unaffected and the
+ // call carries on.
+ //
+ // Direct call rather than invokeMethod() - same reason as in
+ // incoming_video_packet(): remotevideo's thread is blocked inside Play().
+ remotevideo->disableHardwareRendering();
+}
+#endif
+
diff --git a/pica-client/audiovideocallcontroller.h b/pica-client/audiovideocallcontroller.h
index 21a38f4..7d97fac 100644
--- a/pica-client/audiovideocallcontroller.h
+++ b/pica-client/audiovideocallcontroller.h
@@ -115,6 +115,9 @@ private slots:
void send_video_packet(QByteArray data, bool is_last_fragment);
void incoming_video_params(QByteArray peer_id, QString codec, quint16 width, quint16 height);
void incoming_video_packet(QByteArray peer_id, quint16 seq_num, quint32 timestamp, QByteArray data);
+#ifdef HAVE_VAAPI
+ void video_rendering_failed();
+#endif
};
diff --git a/pica-client/callwindow.cpp b/pica-client/callwindow.cpp
index b2975d5..4aff7bc 100644
--- a/pica-client/callwindow.cpp
+++ b/pica-client/callwindow.cpp
@@ -19,6 +19,7 @@
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QCloseEvent>
+#include <QDebug>
CallWindow::CallWindow(QByteArray peer_id, bool incoming)
: m_peer_id(peer_id), is_incoming(incoming)
@@ -39,9 +40,10 @@ CallWindow::CallWindow(QByteArray peer_id, bool incoming)
lbVideo->setMinimumSize(320, 240);
lbVideo->hide();
#ifdef HAVE_VAAPI
- videoGpu = new VaapiVideoWidget(this);
- videoGpu->setMinimumSize(320, 240);
- videoGpu->hide();
+ videoGpu = VaapiRenderWidget::create(this);
+ videoGpu->widget()->setMinimumSize(320, 240);
+ videoGpu->widget()->hide();
+ connect(videoGpu->widget(), SIGNAL(renderingFailed(QString)), this, SLOT(gpu_rendering_failed(QString)));
#endif
callTimer = new QTimer(this);
callElapsedSeconds = 0;
@@ -49,7 +51,7 @@ CallWindow::CallWindow(QByteArray peer_id, bool incoming)
lv->addWidget(lbTimer);
lv->addWidget(lbVideo);
#ifdef HAVE_VAAPI
- lv->addWidget(videoGpu);
+ lv->addWidget(videoGpu->widget());
#endif
lh->addWidget(pbAccept, Qt::AlignLeft);
@@ -109,16 +111,37 @@ void CallWindow::showRemoteHwFrame(AVFramePtr frame)
if (!frame)
return;
+ // The widget has given up on drawing - ask again for frames the label can
+ // show, and keep the video area with it.
+ if (!videoGpu->isWorking())
+ {
+ emit video_rendering_failed();
+ return;
+ }
+
// These frames hold a GPU surface rather than pixels, so the label cannot
// show them - the GL widget takes over the video area instead.
- if (videoGpu->isHidden())
+ if (videoGpu->widget()->isHidden())
{
lbVideo->hide();
- videoGpu->show();
+ videoGpu->widget()->show();
}
videoGpu->setFrame(frame);
}
+
+void CallWindow::gpu_rendering_failed(QString message)
+{
+ // Nothing will ever appear in the GL widget now, so hand the video area
+ // back to the label and ask for frames it can actually show. Without this
+ // the rest of the call would be spent looking at an empty black rectangle.
+ qWarning() << message;
+
+ videoGpu->widget()->hide();
+ lbVideo->show();
+
+ emit video_rendering_failed();
+}
#endif
void CallWindow::update_call_timer()
diff --git a/pica-client/callwindow.h b/pica-client/callwindow.h
index b517cd4..b5b1d97 100644
--- a/pica-client/callwindow.h
+++ b/pica-client/callwindow.h
@@ -24,7 +24,7 @@
#include <QTimer>
#include <QImage>
#ifdef HAVE_VAAPI
-#include "vaapivideowidget.h"
+#include "vaapi.h"
#endif
class CallWindow : public QWidget
@@ -37,6 +37,12 @@ signals:
void accept_call_pressed();
void hang_call_pressed();
void callwindow_closed(CallWindow *sender_window);
+#ifdef HAVE_VAAPI
+ // Drawing frames straight out of GPU memory did not work on this system.
+ // The call controller answers by having them decoded into system memory
+ // instead, which the label below can show.
+ void video_rendering_failed();
+#endif
private:
QByteArray m_peer_id;
bool is_incoming;
@@ -49,8 +55,9 @@ private:
QLabel *lbVideo;
#ifdef HAVE_VAAPI
// Used instead of lbVideo when frames arrive still living in GPU memory;
- // only one of the two is ever visible.
- VaapiVideoWidget *videoGpu;
+ // only one of the two is ever visible. Which of the two renderers this is
+ // depends on the session - see VaapiRenderWidget::create().
+ VaapiRenderWidget *videoGpu;
#endif
QTimer *callTimer;
int callElapsedSeconds;
@@ -69,6 +76,9 @@ private slots:
void accept();
void hang();
void update_call_timer();
+#ifdef HAVE_VAAPI
+ void gpu_rendering_failed(QString message);
+#endif
};
#endif
diff --git a/pica-client/dialogs/settingsdialog.cpp b/pica-client/dialogs/settingsdialog.cpp
index 6aa7a23..e074a48 100644
--- a/pica-client/dialogs/settingsdialog.cpp
+++ b/pica-client/dialogs/settingsdialog.cpp
@@ -26,6 +26,7 @@
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QLabel>
+#include <QDebug>
#include <QVariant>
#include <QListWidget>
#include <QNetworkInterface>
@@ -249,10 +250,10 @@ SettingsDialog::SettingsDialog(QWidget *parent) :
videoTestStatus->setAlignment(Qt::AlignCenter);
#ifdef HAVE_VAAPI
- videoPreviewGpu = new VaapiVideoWidget(this);
- videoPreviewGpu->setMinimumSize(320, 240);
- videoPreviewGpu->hide();
- connect(videoPreviewGpu, SIGNAL(renderingFailed(QString)), this, SLOT(videoTestRenderFailed(QString)));
+ videoPreviewGpu = VaapiRenderWidget::create(this);
+ videoPreviewGpu->widget()->setMinimumSize(320, 240);
+ videoPreviewGpu->widget()->hide();
+ connect(videoPreviewGpu->widget(), SIGNAL(renderingFailed(QString)), this, SLOT(videoTestRenderFailed(QString)));
#endif
videodevLayout->addWidget(videoDev);
@@ -266,7 +267,7 @@ SettingsDialog::SettingsDialog(QWidget *parent) :
videodevLayout->addWidget(btVideoTest);
videodevLayout->addWidget(videoPreview);
#ifdef HAVE_VAAPI
- videodevLayout->addWidget(videoPreviewGpu);
+ videodevLayout->addWidget(videoPreviewGpu->widget());
#endif
videodevLayout->addWidget(videoTestStatus);
videodevLayout->addStretch(1);
@@ -604,7 +605,10 @@ void SettingsDialog::videoTestCaptureStarted(QString codec, int width, int heigh
bool vaapiRendering = false;
#ifdef HAVE_VAAPI
vaapiDecoding = cbVaapiDecoding->isChecked();
- vaapiRendering = cbVaapiRendering->isChecked();
+ // Asking for frames to be kept in GPU memory once it is known that they
+ // cannot be drawn from there would only mean starting each test with a
+ // blank preview until it failed again.
+ vaapiRendering = cbVaapiRendering->isChecked() && !VaapiRenderWidget::renderingKnownBroken();
#endif
QMetaObject::invokeMethod(testDecoder, "configurePlayback", Qt::QueuedConnection,
@@ -643,7 +647,7 @@ void SettingsDialog::stopVideoTest()
videoTestStatus->clear();
#ifdef HAVE_VAAPI
videoPreviewGpu->clearFrame();
- videoPreviewGpu->hide();
+ videoPreviewGpu->widget()->hide();
videoPreview->show();
#endif
}
@@ -689,12 +693,20 @@ void SettingsDialog::videoTestHwFrame(AVFramePtr frame)
if (!videoTestRunning)
return;
+ // The widget has given up on drawing; leave the preview area with the
+ // label and get the decoder to produce frames it can show.
+ if (!videoPreviewGpu->isWorking())
+ {
+ testDecoder->disableHardwareRendering();
+ return;
+ }
+
// Frames arriving here never went through system memory, so the label has
// nothing to show - the GL widget takes over the preview area.
- if (videoPreviewGpu->isHidden())
+ if (videoPreviewGpu->widget()->isHidden())
{
videoPreview->hide();
- videoPreviewGpu->show();
+ videoPreviewGpu->widget()->show();
}
videoTestStatus->setText(videoTestPathReport.isEmpty()
@@ -707,10 +719,17 @@ void SettingsDialog::videoTestHwFrame(AVFramePtr frame)
void SettingsDialog::videoTestRenderFailed(QString message)
{
// Drawing straight from GPU memory did not work out. The decoder is still
- // running, so say so and leave the test going rather than killing it.
- videoPreviewGpu->hide();
+ // running, so leave the test going rather than killing it: ask it to bring
+ // frames back into system memory, which the label can show. The reason
+ // stands in the label until the first of those frames replaces it.
+ qWarning() << message;
+
+ videoPreviewGpu->widget()->hide();
videoPreview->show();
videoPreview->setText(message);
+
+ // Direct call, for the same reason as in videoTestFragment().
+ testDecoder->disableHardwareRendering();
}
#endif
diff --git a/pica-client/dialogs/settingsdialog.h b/pica-client/dialogs/settingsdialog.h
index e3ebea7..71d3149 100644
--- a/pica-client/dialogs/settingsdialog.h
+++ b/pica-client/dialogs/settingsdialog.h
@@ -34,7 +34,7 @@
#include "../videodevice.h"
#include "../toneplayer/toneplayer.h"
#ifdef HAVE_VAAPI
-#include "../vaapivideowidget.h"
+#include "../vaapi.h"
#endif
class SettingsDialog : public QDialog
@@ -133,7 +133,7 @@ private:
QCheckBox *cbVaapiRendering;
// Shown in place of videoPreview while frames are being drawn straight
// from GPU memory; only one of the two is ever visible.
- VaapiVideoWidget *videoPreviewGpu;
+ VaapiRenderWidget *videoPreviewGpu;
#endif
VideoDevice *testCam;
VideoDevice *testDecoder;
diff --git a/pica-client/main.cpp b/pica-client/main.cpp
index cc3d90b..f10353e 100644
--- a/pica-client/main.cpp
+++ b/pica-client/main.cpp
@@ -499,12 +499,22 @@ static bool create_config_dir()
int main(int argc, char *argv[])
{
+#ifdef HAVE_VAAPI
+ // Before Qt opens its X connection, which is the only time Xlib will
+ // listen - see the comment on the function itself.
+ VaapiContext::initX11Threading();
+#endif
+
QApplication a(argc, argv);
#ifdef HAVE_VAAPI
// Decoded hardware frames travel from the decoding thread to the widget
// drawing them through queued signals, which needs their type registered.
VaapiContext::registerMetaTypes();
+
+ // Settles how a decoded surface will be drawn in this session, which has
+ // to be known before the first one is created.
+ VaapiContext::detectX11Display();
#endif
#ifdef WIN32
diff --git a/pica-client/vaapi.cpp b/pica-client/vaapi.cpp
index 74f036d..d5dd2f5 100644
--- a/pica-client/vaapi.cpp
+++ b/pica-client/vaapi.cpp
@@ -18,9 +18,19 @@
#ifdef HAVE_VAAPI
+#include "vaapivideowidget.h"
+#ifdef HAVE_VAAPI_X11
+#include "vaapix11widget.h"
+#endif
+
#include <QMutex>
#include <QMutexLocker>
#include <QDebug>
+#ifdef HAVE_VAAPI_X11
+#include <QGuiApplication>
+#include <QOffscreenSurface>
+#include <QOpenGLContext>
+#endif
extern "C" {
#include <libavutil/hwcontext.h>
@@ -28,6 +38,26 @@ extern "C" {
#include <libavutil/error.h>
}
+#ifdef HAVE_VAAPI_X11
+// Included after the Qt headers, since Xlib defines a handful of names as
+// macros that Qt also uses as ordinary identifiers.
+#include <X11/Xlib.h>
+#include <GL/glx.h>
+#include <va/va_x11.h>
+#undef Bool
+#undef Status
+#undef None
+#undef Success
+#undef Always
+#undef CursorShape
+#undef KeyPress
+#undef KeyRelease
+#undef FocusIn
+#undef FocusOut
+#undef Expose
+#undef Unsorted
+#endif
+
namespace
{
QMutex g_mutex;
@@ -36,6 +66,104 @@ namespace
// display anyway.
AVBufferRef *g_device = nullptr;
bool g_tried = false;
+ bool g_usesX11 = false;
+
+#ifdef HAVE_VAAPI_X11
+ // Qt's own X connection, found at startup by detectX11Display(), and only
+ // when Qt's OpenGL contexts turned out to be GLX ones. Owned by Qt.
+ //
+ // Using Qt's connection rather than one of our own means the windows the
+ // driver is asked to draw on are already known to the server on the same
+ // connection, with nothing to flush or synchronise first.
+ Display *g_x11Display = nullptr;
+
+ // Hands an already opened VADisplay to FFmpeg. Unlike
+ // av_hwdevice_ctx_create() this leaves the display in our hands rather
+ // than opening one of its own, which is the whole point here: the renderer
+ // has to draw surfaces on the very same display the decoder made them on.
+ AVBufferRef *wrapVaDisplay(VADisplay va_display)
+ {
+ AVBufferRef *ref = av_hwdevice_ctx_alloc(AV_HWDEVICE_TYPE_VAAPI);
+
+ if (!ref)
+ return nullptr;
+
+ AVHWDeviceContext *devctx = (AVHWDeviceContext *)ref->data;
+ AVVAAPIDeviceContext *vactx = (AVVAAPIDeviceContext *)devctx->hwctx;
+
+ vactx->display = va_display;
+
+ if (av_hwdevice_ctx_init(ref) < 0)
+ {
+ av_buffer_unref(&ref);
+ return nullptr;
+ }
+
+ return ref;
+ }
+
+ // Opens the VAAPI device on the X connection, so that decoded surfaces can
+ // later be drawn with vaPutSurface(). Returns null when that is not the way
+ // this session draws - under Wayland, or under X11 with Qt on EGL, where a
+ // surface is drawn through its DMA-BUF handles instead - and on any
+ // failure, leaving the caller to open the device through a DRM render node.
+ AVBufferRef *createX11Device()
+ {
+ if (!g_x11Display)
+ return nullptr;
+
+ // libva's X11 backend prefers DRI3, which gets it a DRM file
+ // descriptor and nothing else. That is all decoding needs, but drawing
+ // is another matter: i965's vaPutSurface() draws into DRI2 buffers and
+ // answers VA_STATUS_ERROR_UNKNOWN, silently and with nothing logged at
+ // any verbosity, for every frame when the display was not opened that
+ // way. So ask libva for DRI2.
+ //
+ // Set for the rest of the process rather than just around the calls
+ // below, and deliberately so: libva reads it in
+ // va_dri_get_rendering_buffer(), which is called while a surface is
+ // being put on a window - restoring the environment after
+ // vaInitialize() would leave the variable unset exactly when it is
+ // consulted. Nothing else in the client opens an X11 VA display, and a
+ // value the user set is left alone.
+ //
+ // Should DRI2 turn out not to be available, opening fails and the
+ // caller falls back to a DRM render node, which never looks at this.
+ if (!qEnvironmentVariableIsSet("LIBVA_DRI3_DISABLE"))
+ qputenv("LIBVA_DRI3_DISABLE", "1");
+
+ VADisplay va_display = vaGetDisplay(g_x11Display);
+
+ if (!va_display)
+ {
+ qWarning() << "VAAPI: this libva build has no X11 support";
+ return nullptr;
+ }
+
+ int major = 0, minor = 0;
+ VAStatus st = vaInitialize(va_display, &major, &minor);
+
+ if (st != VA_STATUS_SUCCESS)
+ {
+ qWarning() << "VAAPI: vaInitialize() on the X display failed:" << vaErrorStr(st);
+ vaTerminate(va_display);
+ return nullptr;
+ }
+
+ AVBufferRef *ref = wrapVaDisplay(va_display);
+
+ if (!ref)
+ {
+ qWarning() << "VAAPI: the X display could not be handed to FFmpeg";
+ vaTerminate(va_display);
+ return nullptr;
+ }
+
+ g_usesX11 = true;
+
+ return ref;
+ }
+#endif
// Must be called with g_mutex held.
void ensureDevice()
@@ -45,6 +173,17 @@ namespace
g_tried = true;
+#ifdef HAVE_VAAPI_X11
+ // Where the widgets will be drawn on by the driver, the display has to
+ // be opened on that same X connection - a surface belongs to the
+ // display it was made on. Encoding and decoding work the same either
+ // way, so nothing is given up by preferring it here.
+ g_device = createX11Device();
+
+ if (g_device)
+ return;
+#endif
+
// A null device name lets FFmpeg find a usable DRM render node
// (/dev/dri/renderD128 and friends) by itself.
int ret = av_hwdevice_ctx_create(&g_device, AV_HWDEVICE_TYPE_VAAPI, nullptr, nullptr, 0);
@@ -93,9 +232,99 @@ bool VaapiContext::isAvailable()
return g_device != nullptr;
}
+bool VaapiContext::usesX11()
+{
+ QMutexLocker locker(&g_mutex);
+ ensureDevice();
+
+ return g_usesX11;
+}
+
+void *VaapiContext::x11Display()
+{
+#ifdef HAVE_VAAPI_X11
+ QMutexLocker locker(&g_mutex);
+ ensureDevice();
+
+ return g_usesX11 ? (void *)g_x11Display : nullptr;
+#else
+ return nullptr;
+#endif
+}
+
void VaapiContext::registerMetaTypes()
{
qRegisterMetaType<AVFramePtr>("AVFramePtr");
}
+void VaapiContext::initX11Threading()
+{
+#ifdef HAVE_VAAPI_X11
+ // Qt's X connection ends up being used from two threads: the GUI thread
+ // drawing, and the decoding thread talking to libva, which talks to the
+ // driver over that same connection. Xlib only handles that if it is told
+ // before the connection is opened - hence being called ahead of
+ // QApplication - and it is harmless when the session turns out not to be
+ // an X11 one at all.
+ XInitThreads();
+#endif
+}
+
+void VaapiContext::detectX11Display()
+{
+#ifdef HAVE_VAAPI_X11
+ QMutexLocker locker(&g_mutex);
+
+ // Nothing to arrange once the device has been opened - it would be too
+ // late to change which display its surfaces live on.
+ if (g_tried || g_x11Display)
+ return;
+
+ if (QGuiApplication::platformName() != QLatin1String("xcb"))
+ return;
+
+ // A throwaway context, made only to see what Qt's OpenGL contexts are:
+ // under X11 Qt uses GLX by default but EGL when asked to, and the two need
+ // entirely different ways of getting a decoded surface onto the screen.
+ // Every context in the process is made on the same X connection, so the
+ // widget that draws video later will be on the one found here.
+ //
+ // A GLX context means the EGL import path is unavailable, and that is what
+ // decides this: the surfaces have to go onto an X window instead.
+ QOffscreenSurface surface;
+ surface.create();
+
+ if (!surface.isValid())
+ return;
+
+ QOpenGLContext ctx;
+
+ if (!ctx.create() || !ctx.makeCurrent(&surface))
+ return;
+
+ Display *dpy = glXGetCurrentDisplay();
+
+ ctx.doneCurrent();
+
+ // Null means an EGL context, where the DMA-BUF path applies and there is
+ // nothing to prepare.
+ if (dpy)
+ g_x11Display = dpy;
+#endif
+}
+
+bool VaapiRenderWidget::s_renderingBroken = false;
+
+VaapiRenderWidget *VaapiRenderWidget::create(QWidget *parent)
+{
+#ifdef HAVE_VAAPI_X11
+ // Only when the display was opened on an X connection, which is also the
+ // only case where a surface can be put onto a window.
+ if (VaapiContext::usesX11())
+ return new VaapiX11Widget(parent);
+#endif
+
+ return new VaapiVideoWidget(parent);
+}
+
#endif // HAVE_VAAPI
diff --git a/pica-client/vaapi.h b/pica-client/vaapi.h
index c422a88..888a9d6 100644
--- a/pica-client/vaapi.h
+++ b/pica-client/vaapi.h
@@ -58,9 +58,82 @@ public:
// back to software rather than each probing for themselves.
static bool isAvailable();
+ // Whether the display was opened on an X11 connection rather than a DRM
+ // render node. That is decided once, when the device is created, and
+ // decides how a decoded surface can be drawn: only an X11 display can be
+ // drawn with vaPutSurface(), which is the only option left when Qt's
+ // OpenGL contexts come from GLX. Always false in a build without X11
+ // rendering support.
+ static bool usesX11();
+
+ // The X connection the display was opened on, as a Display*, or null when
+ // it was not opened on one. Untyped to keep the Xlib headers, and the
+ // names they take over, out of everything that includes this.
+ static void *x11Display();
+
// Registers the metatype for AVFramePtr, so hardware frames can be passed
// through queued signal connections. Call once at startup.
static void registerMetaTypes();
+
+ // Tells Xlib that its connection will be used from more than one thread,
+ // which it only accepts before that connection is opened - so this has to
+ // run before QApplication is constructed. Does nothing in a build without
+ // X11 rendering support.
+ static void initX11Threading();
+
+ // Works out whether this session needs the X11 drawing path - that is,
+ // whether Qt's OpenGL contexts come from GLX, leaving no way to import a
+ // surface as an EGL image - and if so remembers Qt's X connection to open
+ // the VAAPI display on. Call once at startup, after QApplication exists
+ // and before any video starts. Does nothing outside an X11 session, or
+ // when Qt is using EGL there.
+ static void detectX11Display();
+};
+
+class QWidget;
+
+// The common face of the two widgets that can draw a decoded surface: the
+// OpenGL one, which imports it as EGL images, and the X11 one, which has the
+// driver put it on screen. Which of them a session can use is not known until
+// it runs, and nothing outside create() should care which it got.
+class VaapiRenderWidget
+{
+public:
+ virtual ~VaapiRenderWidget() {}
+
+ // The widget to lay out, show and hide, and to connect to: both carry a
+ // renderingFailed(QString) signal.
+ virtual QWidget *widget() = 0;
+
+ // Takes the frame to draw next, replacing any previous one not yet drawn -
+ // for live video the newest frame is the one that matters.
+ virtual void setFrame(AVFramePtr frame) = 0;
+
+ // Drops the current frame and clears the widget.
+ virtual void clearFrame() = 0;
+
+ // Whether frames are still being drawn. False once drawing has failed, so
+ // a caller can fall back to the software path rather than leave a blank
+ // widget.
+ virtual bool isWorking() const = 0;
+
+ // The renderer this session can use. Never null - it falls back to the
+ // OpenGL one, which reports the reason it cannot draw if it cannot.
+ static VaapiRenderWidget *create(QWidget *parent);
+
+ // Whether drawing GPU frames has already been found not to work in this
+ // session. Nothing about that changes while the client runs - it follows
+ // from the kind of OpenGL context Qt provides and what the driver can do
+ // with it - so once one widget has failed, the next will fail the same
+ // way. Callers use this to stop asking for GPU frames at all rather than
+ // to fail again for every window they open.
+ static bool renderingKnownBroken() { return s_renderingBroken; }
+
+protected:
+ static void markRenderingBroken() { s_renderingBroken = true; }
+
+private:
+ static bool s_renderingBroken;
};
Q_DECLARE_METATYPE(AVFramePtr)
diff --git a/pica-client/vaapivideowidget.cpp b/pica-client/vaapivideowidget.cpp
index fa50d10..1f3f3a6 100644
--- a/pica-client/vaapivideowidget.cpp
+++ b/pica-client/vaapivideowidget.cpp
@@ -32,6 +32,7 @@ extern "C" {
#include <va/va_drmcommon.h>
+
namespace
{
// Extension entry points, resolved once at first use: they are not
@@ -109,6 +110,19 @@ VaapiVideoWidget::~VaapiVideoWidget()
doneCurrent();
}
+void VaapiVideoWidget::reportFailure(const QString &message)
+{
+ m_working = false;
+ markRenderingBroken();
+
+ if (m_reportedFailure)
+ return;
+
+ m_reportedFailure = true;
+ qWarning() << message;
+ emit renderingFailed(message);
+}
+
void VaapiVideoWidget::setFrame(AVFramePtr frame)
{
if (!m_working)
@@ -131,16 +145,28 @@ void VaapiVideoWidget::initializeGL()
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glDisable(GL_DEPTH_TEST);
+ // Importing a surface as an EGL image needs an EGL context to import it
+ // into. eglGetCurrentDisplay() is the telling call: under GLX it answers
+ // EGL_NO_DISPLAY, and there is no display to create an image on.
+ if (eglGetCurrentContext() == EGL_NO_CONTEXT || eglGetCurrentDisplay() == EGL_NO_DISPLAY)
+ {
+#ifdef HAVE_VAAPI_X11
+ // An X11 session should have been given the other renderer, so the
+ // display cannot have been opened on an X connection either.
+ reportFailure(tr("The OpenGL context is not an EGL one and the VAAPI display was not "
+ "opened on an X connection, so decoded frames cannot be drawn"));
+#else
+ reportFailure(tr("The OpenGL context is not an EGL one, so decoded frames cannot be "
+ "drawn. An X11 session gives Qt a GLX context unless told otherwise; "
+ "rebuild with --enable-vaapi-x11, or start the client with "
+ "QT_XCB_GL_INTEGRATION=xcb_egl"));
+#endif
+ return;
+ }
+
if (!resolveEglExtensions())
{
- m_working = false;
- if (!m_reportedFailure)
- {
- m_reportedFailure = true;
- QString msg = "EGL does not offer the extensions needed to draw GPU frames";
- qWarning() << msg;
- emit renderingFailed(msg);
- }
+ reportFailure(tr("EGL does not offer the extensions needed to draw GPU frames"));
return;
}
@@ -149,14 +175,7 @@ void VaapiVideoWidget::initializeGL()
!m_program->addShaderFromSourceCode(QOpenGLShader::Fragment, kFragmentShader) ||
!m_program->link())
{
- m_working = false;
- if (!m_reportedFailure)
- {
- m_reportedFailure = true;
- QString msg = QString("Could not build the video shader: %1").arg(m_program->log());
- qWarning() << msg;
- emit renderingFailed(msg);
- }
+ reportFailure(tr("Could not build the video shader: %1").arg(m_program->log()));
return;
}
@@ -298,6 +317,8 @@ bool VaapiVideoWidget::importFrame()
EGL_LINUX_DMA_BUF_EXT, nullptr, attribs);
if (m_images[i] == EGL_NO_IMAGE_KHR)
{
+ qWarning() << QString("eglCreateImageKHR failed for plane %1: 0x%2")
+ .arg(i).arg(eglGetError(), 0, 16);
releaseImports();
return false;
}
@@ -320,14 +341,7 @@ void VaapiVideoWidget::paintGL()
if (!importFrame())
{
- m_working = false;
- if (!m_reportedFailure)
- {
- m_reportedFailure = true;
- QString msg = "Could not hand the decoded GPU frame to OpenGL for drawing";
- qWarning() << msg;
- emit renderingFailed(msg);
- }
+ reportFailure(tr("Could not hand the decoded GPU frame to OpenGL for drawing"));
return;
}
diff --git a/pica-client/vaapivideowidget.h b/pica-client/vaapivideowidget.h
index 0aebef5..9ea7a50 100644
--- a/pica-client/vaapivideowidget.h
+++ b/pica-client/vaapivideowidget.h
@@ -31,33 +31,28 @@
//
// The surface is exported as DMA-BUF file descriptors, imported into EGL as
// images, and bound to OpenGL textures - one for the luma plane and one for
-// the interleaved chroma plane of an NV12 frame - which a fragment shader
-// then converts to RGB while drawing. Nothing copies the picture; the GPU
-// keeps it where the decoder left it.
+// the interleaved chroma plane of an NV12 frame - which a fragment shader then
+// converts to RGB while drawing. Nothing copies the picture; the GPU keeps it
+// where the decoder left it. This needs an EGL context, which is what a
+// Wayland session gives, and what X11 gives when asked
+// (QT_XCB_GL_INTEGRATION=xcb_egl).
//
-// The alternative, vaPutSurface() onto an X11 Drawable, was not an option
-// here: the client runs on Wayland, where there is no such drawable, and
-// Qt5X11Extras is not installed either. EGL works on both Wayland and X11.
-class VaapiVideoWidget : public QOpenGLWidget, protected QOpenGLFunctions
+// An X11 session where Qt uses GLX instead gives a context that cannot import
+// a DMA-BUF at all; VaapiX11Widget covers that case, and VaapiRenderWidget's
+// factory decides between the two.
+class VaapiVideoWidget : public QOpenGLWidget, protected QOpenGLFunctions, public VaapiRenderWidget
{
Q_OBJECT
public:
explicit VaapiVideoWidget(QWidget *parent = nullptr);
~VaapiVideoWidget() override;
- // Whether the last frame could actually be drawn. False means the EGL
- // import failed and nothing is being shown, so a caller can fall back to
- // the software path rather than leave a blank widget.
- bool isWorking() const { return m_working; }
+ virtual QWidget *widget() override { return this; }
+ virtual bool isWorking() const override { return m_working; }
public slots:
- // Takes the frame to draw next, replacing any previous one that has not
- // been drawn yet - for live video the newest frame is the one that
- // matters, which is the same policy the decode queue follows.
- void setFrame(AVFramePtr frame);
-
- // Drops the current frame and clears the widget.
- void clearFrame();
+ virtual void setFrame(AVFramePtr frame) override;
+ virtual void clearFrame() override;
signals:
// Raised once if the frame cannot be imported for drawing, carrying the
@@ -79,6 +74,9 @@ private:
// exhausts the process's descriptors within minutes.
void releaseImports();
+ // Reports a failure that stops the widget drawing, once.
+ void reportFailure(const QString &message);
+
AVFramePtr m_frame;
QOpenGLShaderProgram *m_program;
unsigned int m_textures[2];
diff --git a/pica-client/vaapix11widget.cpp b/pica-client/vaapix11widget.cpp
new file mode 100644
index 0000000..0788577
--- /dev/null
+++ b/pica-client/vaapix11widget.cpp
@@ -0,0 +1,237 @@
+/*
+ (c) Copyright 2012 - 2026 Anton Sviridenko
+ https://picapica.im
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, version 3.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
+*/
+#include "vaapix11widget.h"
+
+#ifdef HAVE_VAAPI_X11
+
+#include <QDebug>
+#include <QPaintEvent>
+#include <QResizeEvent>
+#include <QShowEvent>
+
+// Included after the Qt headers, since Xlib defines a handful of names as
+// macros that Qt also uses as ordinary identifiers.
+#include <X11/Xlib.h>
+#include <va/va_x11.h>
+#undef Bool
+#undef Status
+#undef None
+#undef Success
+#undef Always
+#undef CursorShape
+#undef KeyPress
+#undef KeyRelease
+#undef FocusIn
+#undef FocusOut
+#undef Expose
+#undef Unsorted
+
+VaapiX11Widget::VaapiX11Widget(QWidget *parent)
+ : QWidget(parent), m_working(true), m_reportedFailure(false),
+ m_describedSurface(false), m_everDrew(false), m_failuresInARow(0)
+{
+ // The driver draws onto this window itself, which means it has to be a
+ // window of its own rather than a region of its parent's, and Qt has to
+ // keep out of it: no background filling, no double buffering, no clearing
+ // before a paint event.
+ setAttribute(Qt::WA_NativeWindow);
+ setAttribute(Qt::WA_PaintOnScreen);
+ setAttribute(Qt::WA_NoSystemBackground);
+ setAttribute(Qt::WA_OpaquePaintEvent);
+ setAutoFillBackground(false);
+}
+
+VaapiX11Widget::~VaapiX11Widget()
+{
+}
+
+void VaapiX11Widget::reportFailure(const QString &message)
+{
+ m_working = false;
+ markRenderingBroken();
+
+ if (m_reportedFailure)
+ return;
+
+ m_reportedFailure = true;
+ qWarning() << message;
+ emit renderingFailed(message);
+}
+
+void VaapiX11Widget::setFrame(AVFramePtr frame)
+{
+ if (!m_working)
+ return;
+
+ m_frame = frame;
+
+ // repaint() rather than update(): the frame is only held until the next
+ // one replaces it, and a posted paint event could easily be delivered
+ // after that has happened.
+ repaint();
+}
+
+void VaapiX11Widget::clearFrame()
+{
+ m_frame.clear();
+ clearWindow();
+}
+
+void VaapiX11Widget::clearWindow()
+{
+ Display *dpy = (Display *)VaapiContext::x11Display();
+
+ if (!dpy || !isVisible())
+ return;
+
+ XClearWindow(dpy, (Window)winId());
+ XFlush(dpy);
+}
+
+void VaapiX11Widget::showEvent(QShowEvent *event)
+{
+ QWidget::showEvent(event);
+
+ Display *dpy = (Display *)VaapiContext::x11Display();
+
+ if (!dpy)
+ return;
+
+ // Black, so that the bars beside a letterboxed picture, and the window
+ // before the first frame arrives, are not left showing whatever the
+ // server last had there.
+ XSetWindowBackground(dpy, (Window)winId(), BlackPixel(dpy, DefaultScreen(dpy)));
+ XClearWindow(dpy, (Window)winId());
+ XFlush(dpy);
+}
+
+void VaapiX11Widget::resizeEvent(QResizeEvent *event)
+{
+ QWidget::resizeEvent(event);
+
+ // The picture is about to be drawn at a different size, and what the old
+ // one left outside it would otherwise stay on screen.
+ clearWindow();
+}
+
+void VaapiX11Widget::paintEvent(QPaintEvent *event)
+{
+ Q_UNUSED(event);
+
+ if (!m_working || !m_frame)
+ return;
+
+ // Nothing to draw onto until the window is on screen, and asking the
+ // driver to draw on one that is not would fail for a reason that says
+ // nothing about whether this path works.
+ if (!isVisible())
+ return;
+
+ if (putFrame())
+ {
+ m_everDrew = true;
+ m_failuresInARow = 0;
+ return;
+ }
+
+ m_failuresInARow++;
+
+ // Frames keep arriving, so one failure proves nothing - give the window
+ // time to settle before writing the path off. Once something has been
+ // drawn successfully, a later failure is treated the same way: only a
+ // sustained run of them counts.
+ if (m_failuresInARow < kMaxFailuresInARow)
+ return;
+
+ reportFailure(m_everDrew
+ ? tr("Stopped being able to put decoded GPU frames on screen")
+ : tr("Could not put the decoded GPU frame on screen"));
+}
+
+bool VaapiX11Widget::putFrame()
+{
+ VADisplay va_display = VaapiContext::display();
+
+ if (!va_display || !m_frame)
+ return false;
+
+ int frameWidth = m_frame->width;
+ int frameHeight = m_frame->height;
+
+ if (frameWidth <= 0 || frameHeight <= 0)
+ return false;
+
+ // Letterbox rather than stretch, matching what the software path does with
+ // Qt::KeepAspectRatio. Everything the picture does not cover keeps the
+ // window's black background.
+ int windowWidth = width();
+ int windowHeight = height();
+ int destWidth = windowWidth;
+ int destHeight = (int)((qint64)windowWidth * frameHeight / frameWidth);
+
+ if (destHeight > windowHeight)
+ {
+ destHeight = windowHeight;
+ destWidth = (int)((qint64)windowHeight * frameWidth / frameHeight);
+ }
+
+ int destX = (windowWidth - destWidth) / 2;
+ int destY = (windowHeight - destHeight) / 2;
+
+ // The surface id lives in data[3] for AV_PIX_FMT_VAAPI frames.
+ VASurfaceID surface = (VASurfaceID)(uintptr_t)m_frame->data[3];
+
+ Display *dpy = (Display *)VaapiContext::x11Display();
+
+ // Before the first frame goes out, make sure the server has caught up with
+ // Qt's own requests for this window - it is created and mapped on the same
+ // connection, but not necessarily processed by the time a frame arrives,
+ // and the driver cannot draw on a window the server does not have yet.
+ if (dpy && !m_everDrew)
+ XSync(dpy, False);
+
+ if (!m_describedSurface)
+ {
+ m_describedSurface = true;
+ qDebug() << QString("Putting VAAPI surfaces on an X11 window: %1x%2")
+ .arg(frameWidth).arg(frameHeight);
+ }
+
+ // VA_SRC_BT601 to match the coefficients the software path and the EGL
+ // renderer use for camera video; VA_FRAME_PICTURE because nothing in this
+ // pipeline is interlaced.
+ VAStatus st = vaPutSurface(va_display, surface, (Drawable)winId(),
+ 0, 0, frameWidth, frameHeight,
+ destX, destY, destWidth, destHeight,
+ nullptr, 0,
+ VA_FRAME_PICTURE | VA_SRC_BT601);
+
+ if (st != VA_STATUS_SUCCESS)
+ {
+ // Only the first one, and then only every so often: at video rate a
+ // line per frame would bury everything else in the log.
+ if (m_failuresInARow == 0 || m_failuresInARow == kMaxFailuresInARow - 1)
+ qWarning() << QString("vaPutSurface failed: %1 (0x%2)")
+ .arg(QLatin1String(vaErrorStr(st))).arg((uint)st, 0, 16);
+
+ return false;
+ }
+
+ return true;
+}
+
+#endif // HAVE_VAAPI_X11
diff --git a/pica-client/vaapix11widget.h b/pica-client/vaapix11widget.h
new file mode 100644
index 0000000..53b6135
--- /dev/null
+++ b/pica-client/vaapix11widget.h
@@ -0,0 +1,97 @@
+/*
+ (c) Copyright 2012 - 2026 Anton Sviridenko
+ https://picapica.im
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, version 3.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
+*/
+#ifndef VAAPIX11WIDGET_H
+#define VAAPIX11WIDGET_H
+
+#ifdef HAVE_VAAPI_X11
+
+#include "vaapi.h"
+
+#include <QWidget>
+#include <QString>
+
+// Draws decoded frames by handing the surface to the driver with the widget's
+// own X window as the target - vaPutSurface() - rather than going through
+// OpenGL at all. The picture never leaves the GPU; the driver does the colour
+// conversion and the scaling.
+//
+// This is the path for an X11 session, where Qt's OpenGL contexts come from
+// GLX and cannot import the DMA-BUF handles a surface is exported as. Since it
+// touches no OpenGL, it does not care which of the two Qt picked.
+//
+// The cost of drawing outside Qt is that Qt must be kept away from this
+// widget's area: it is given a native window of its own, Qt is told not to
+// paint or clear it (WA_PaintOnScreen, WA_NoSystemBackground, a null paint
+// engine), and anything drawn over it - a menu, a tooltip - will fight with
+// the video underneath.
+class VaapiX11Widget : public QWidget, public VaapiRenderWidget
+{
+ Q_OBJECT
+public:
+ explicit VaapiX11Widget(QWidget *parent = nullptr);
+ ~VaapiX11Widget() override;
+
+ virtual QWidget *widget() override { return this; }
+ virtual bool isWorking() const override { return m_working; }
+
+public slots:
+ virtual void setFrame(AVFramePtr frame) override;
+ virtual void clearFrame() override;
+
+signals:
+ // Raised once if a frame cannot be put on screen, carrying the reason.
+ // The widget stops trying after that.
+ void renderingFailed(QString message);
+
+protected:
+ // Nothing about this widget is painted by Qt, so it has no paint engine to
+ // offer. Returning one would have Qt draw over the video.
+ QPaintEngine *paintEngine() const override { return nullptr; }
+
+ void paintEvent(QPaintEvent *event) override;
+ void resizeEvent(QResizeEvent *event) override;
+ void showEvent(QShowEvent *event) override;
+
+private:
+ // Puts the current frame on the window, letterboxed to keep its aspect
+ // ratio. Returns false if the driver would not draw it.
+ bool putFrame();
+
+ // Paints the whole window black, so that the bars beside a letterboxed
+ // picture are not left holding whatever was there before.
+ void clearWindow();
+
+ void reportFailure(const QString &message);
+
+ AVFramePtr m_frame;
+ bool m_working;
+ bool m_reportedFailure;
+ bool m_describedSurface;
+ bool m_everDrew;
+
+ // Putting a surface on a window can fail for reasons that pass - the
+ // window not being mapped yet at the moment the first frame arrives, most
+ // obviously - so unlike an EGL import, which either works or never will,
+ // this one is worth retrying. Only a long run of failures means the path
+ // is really unusable.
+ int m_failuresInARow;
+ static const int kMaxFailuresInARow = 30;
+};
+
+#endif // HAVE_VAAPI_X11
+
+#endif // VAAPIX11WIDGET_H
diff --git a/pica-client/videodevice.cpp b/pica-client/videodevice.cpp
index e9f71e0..4fd03d6 100644
--- a/pica-client/videodevice.cpp
+++ b/pica-client/videodevice.cpp
@@ -215,6 +215,14 @@ void VideoDevice::configurePlayback(QString codec, int width, int height,
// place, so asking for GPU rendering turns on GPU decoding regardless.
m_useVaapi = useVaapi || useVaapiRender;
m_useVaapiRender = useVaapiRender;
+ // A renderer that failed during an earlier call says nothing about this
+ // one - it may well be a different window.
+ m_hwRenderDisabled.storeRelaxed(0);
+}
+
+void VideoDevice::disableHardwareRendering()
+{
+ m_hwRenderDisabled.storeRelaxed(1);
}
void VideoDevice::enqueueFrame(QByteArray encodedFrame)
@@ -806,7 +814,7 @@ void VideoDevice::Play()
#ifdef HAVE_VAAPI
AVFrame *sw_frame = nullptr;
- if (decodedOnGpu && m_useVaapiRender)
+ if (decodedOnGpu && m_useVaapiRender && !m_hwRenderDisabled.loadRelaxed())
{
// Zero copy: hand the surface itself over, holding a
// reference so it stays alive until the renderer is done.
diff --git a/pica-client/videodevice.h b/pica-client/videodevice.h
index 49d86a9..320d55a 100644
--- a/pica-client/videodevice.h
+++ b/pica-client/videodevice.h
@@ -102,6 +102,13 @@ public:
// video, showing the newest frame matters more than showing every frame.
void enqueueFrame(QByteArray encodedFrame);
+ // Stops keeping decoded frames in GPU memory, for when the renderer that
+ // was to draw them turns out not to be able to: decoding carries on, but
+ // frames come back through system memory and are emitted by frameReady()
+ // from then on. Safe to call from any thread, and called directly rather
+ // than queued for the same reason enqueueFrame() is.
+ void disableHardwareRendering();
+
public slots:
// Blocking capture+encode loop: opens the configured camera, encodes
// captured frames, and emits packetReady() for each encoded frame, split
@@ -172,6 +179,10 @@ private:
bool m_useVaapiRender;
QAtomicInt m_abort;
+ // Set from another thread by disableHardwareRendering() while the decode
+ // loop is running, so it has to be read atomically rather than as a plain
+ // bool like the settings above, which are fixed before the loop starts.
+ QAtomicInt m_hwRenderDisabled;
QMutex m_queueMutex;
QWaitCondition m_queueCond;