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
qgstvideorenderersink.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 Jolla Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3
5
6#include <QtMultimedia/qvideoframe.h>
7#include <QtMultimedia/qvideosink.h>
8#include <QtMultimedia/private/qvideoframe_p.h>
9#include <QtGui/rhi/qrhi.h>
10#include <QtGui/qguiapplication.h>
11#include <QtGui/qopenglcontext.h>
12#include <QtCore/qcoreapplication.h>
13#include <QtCore/qdebug.h>
14#include <QtCore/qloggingcategory.h>
15#include <QtCore/private/qfactoryloader_p.h>
16#include <QtCore/private/quniquehandle_p.h>
17
18#include <common/qgst_debug_p.h>
19#include <common/qgstreamermetadata_p.h>
20#include <common/qgstreamervideosink_p.h>
21#include <common/qgstutils_p.h>
22#include <common/qgstvideobuffer_p.h>
23
24#include <gst/video/video.h>
25#include <gst/video/gstvideometa.h>
26
27
28#if QT_CONFIG(gstreamer_gl)
29#include <gst/gl/gl.h>
30#endif // #if QT_CONFIG(gstreamer_gl)
31
32// DMA support
33#if QT_CONFIG(gstreamer_gl_egl) && QT_CONFIG(linux_dmabuf)
34# include <common/qgstreameregldisplay_p.h>
35# include <gst/allocators/gstdmabuf.h>
36#endif
37
38// NOLINTBEGIN(readability-convert-member-functions-to-static)
39
40Q_STATIC_LOGGING_CATEGORY(qLcGstVideoRenderer, "qt.multimedia.gstvideorenderer");
41
42QT_BEGIN_NAMESPACE
43
44QGstVideoRenderer::QGstVideoRenderer(QGstreamerRelayVideoSink *sink)
45 : m_sink(sink), m_surfaceCaps(createSurfaceCaps(sink))
46{
47 QObject::connect(
48 sink, &QGstreamerRelayVideoSink::aboutToBeDestroyed, this,
49 [this] {
50 QMutexLocker locker(&m_sinkMutex);
51 m_sink = nullptr;
52 },
53 Qt::DirectConnection);
54}
55
57
58QGstCaps QGstVideoRenderer::createSurfaceCaps([[maybe_unused]] QGstreamerRelayVideoSink *sink)
59{
61
62 // All the formats that both we and gstreamer support
63 auto formats = QList<QVideoFrameFormat::PixelFormat>()
64 << QVideoFrameFormat::Format_YUV420P
65 << QVideoFrameFormat::Format_YUV422P
66 << QVideoFrameFormat::Format_YV12
67 << QVideoFrameFormat::Format_UYVY
68 << QVideoFrameFormat::Format_YUYV
69 << QVideoFrameFormat::Format_NV12
70 << QVideoFrameFormat::Format_NV21
71 << QVideoFrameFormat::Format_AYUV
72 << QVideoFrameFormat::Format_P010
73 << QVideoFrameFormat::Format_XRGB8888
74 << QVideoFrameFormat::Format_XBGR8888
75 << QVideoFrameFormat::Format_RGBX8888
76 << QVideoFrameFormat::Format_BGRX8888
77 << QVideoFrameFormat::Format_ARGB8888
78 << QVideoFrameFormat::Format_ABGR8888
79 << QVideoFrameFormat::Format_RGBA8888
80 << QVideoFrameFormat::Format_BGRA8888
81 << QVideoFrameFormat::Format_Y8
82 << QVideoFrameFormat::Format_Y16
83 ;
84 caps.addPixelFormats(formats);
85#if QT_CONFIG(gstreamer_gl)
86 QRhi *rhi = sink->rhi();
87 if (rhi && rhi->backend() == QRhi::OpenGLES2) {
88 caps.addPixelFormats(formats, GST_CAPS_FEATURE_MEMORY_GL_MEMORY);
89# if QT_CONFIG(gstreamer_gl_egl) && QT_CONFIG(linux_dmabuf)
90 if (qGstEglCanMapDmaBuf(rhi)) {
91 caps.addPixelFormats(formats, GST_CAPS_FEATURE_MEMORY_DMABUF);
92 }
93# endif
94 }
95#endif
96 return caps;
97}
98
99void QGstVideoRenderer::customEvent(QEvent *event)
100{
101QT_WARNING_PUSH
102QT_WARNING_DISABLE_GCC("-Wswitch") // case value not in enumerated type ‘QEvent::Type’
103
104 switch (event->type()) {
105 case renderFramesEvent: {
106 // LATER: we currently show every frame. however it may be reasonable to drop frames
107 // here if the queue contains more than one frame
108 while (std::optional<RenderBufferState> nextState = m_bufferQueue.dequeue())
109 handleNewBuffer(std::move(*nextState));
110 return;
111 }
112 case stopEvent: {
113 m_currentPipelineFrame = {};
114 updateCurrentVideoFrame(m_currentVideoFrame);
115 return;
116 }
117
118 default:
119 return;
120 }
121QT_WARNING_POP
122}
123
124
125void QGstVideoRenderer::handleNewBuffer(RenderBufferState state)
126{
127 QVideoFrame frame =
128 qCreateFrameFromGstBuffer(state.buffer, state.videoInfo, state.format);
129 QGstUtils::setFrameTimeStampsFromBuffer(&frame, state.buffer.get());
130 m_currentPipelineFrame = std::move(frame);
131
132 if (!m_isActive) {
133 qCDebug(qLcGstVideoRenderer) << " showing empty video frame";
134 updateCurrentVideoFrame({});
135 return;
136 }
137
138 updateCurrentVideoFrame(m_currentPipelineFrame);
139}
140
142{
143 return m_surfaceCaps;
144}
145
147{
148 qCDebug(qLcGstVideoRenderer) << "QGstVideoRenderer::start" << caps;
149
150 auto optionalVideoInfo = caps.videoInfo();
151 if (optionalVideoInfo) {
152 m_videoInfo = std::move(*optionalVideoInfo);
153 m_format = qVideoFrameFormatFromGstVideoInfo(m_videoInfo);
154 } else {
155 m_format = {};
156 m_videoInfo = {};
157 }
158 m_capsMemoryFormat = caps.memoryFormat();
159
160 // NOTE: m_format will not be fully populated until GST_EVENT_TAG is processed
161
162 return true;
163}
164
166{
167 qCDebug(qLcGstVideoRenderer) << "QGstVideoRenderer::stop";
168
169 m_bufferQueue.clear();
170 QCoreApplication::postEvent(this, new QEvent(stopEvent));
171}
172
174{
175 qCDebug(qLcGstVideoRenderer) << "QGstVideoRenderer::unlock";
176}
177
179{
180 if (!query || GST_QUERY_TYPE(query) != GST_QUERY_ALLOCATION)
181 return false;
182
183 GstCaps *queryCaps = nullptr;
184 gboolean needPool = false;
185 gst_query_parse_allocation(query, &queryCaps, &needPool);
186 GstVideoInfo info;
187 int size = 0;
188 if (queryCaps && gst_video_info_from_caps(&info, queryCaps)) {
189 size = info.size;
190 } else {
191 qWarning(qLcGstVideoRenderer) << "QGstVideoRenderer::proposeAllocation failed to "
192 "get size from query caps";
193 return true;
194 }
195
196 constexpr int defaultMinBuffers = 3;
197 static const int env
198 = qEnvironmentVariableIntValue("QT_GSTREAMER_PROPOSE_ALLOCATION_MIN_BUFFERS");
199 static const int minBuffers = env ? env : defaultMinBuffers;
200 qCDebug(qLcGstVideoRenderer) << "QGstVideoRenderer::proposeAllocation: "
201 "needPool:" << needPool
202 << "size:" << size
203 << "minBuffers:" << minBuffers;
204
205 // This call is needed to avoid enabling of copy threshold by v4l2 decoders, which can result
206 // in a mix of dmabuf and system memory buffers. The query sender should use its own buffer
207 // pool, and will only take the size value and our suggested minimum buffers into account.
208 // The driver can force a higher minimum if minBuffers is set too low, making 3 sufficient.
209 gst_query_add_allocation_pool(query, nullptr, size, minBuffers, 0);
210
211 // Advertise GstVideoMeta support, often needed for DMA buffer negotiation.
212 gst_query_add_allocation_meta(query, GST_VIDEO_META_API_TYPE, nullptr);
213
214 return true;
215}
216
218{
219 qCDebug(qLcGstVideoRenderer) << "QGstVideoRenderer::render";
220
221 if (m_flushing) {
222 qCDebug(qLcGstVideoRenderer)
223 << " buffer received while flushing the sink ... discarding buffer";
224 return GST_FLOW_FLUSHING;
225 }
226
227 GstVideoCropMeta *meta = gst_buffer_get_video_crop_meta(buffer);
228 if (meta) {
229 QRect vp(meta->x, meta->y, meta->width, meta->height);
230 if (m_format.viewport() != vp) {
231 qCDebug(qLcGstVideoRenderer)
232 << Q_FUNC_INFO << " Update viewport on Metadata: [" << meta->height << "x"
233 << meta->width << " | " << meta->x << "x" << meta->y << "]";
234 // Update viewport if data is not the same
235 m_format.setViewport(vp);
236 }
237 }
238
239 // Some gst elements, like v4l2h264dec, can provide Direct Memory Access buffers (DMA-BUF)
240 // without specifying it in their caps. So we check the memory format manually:
241 QGstCaps::MemoryFormat bufferMemoryFormat = [&] {
242 if (m_capsMemoryFormat != QGstCaps::CpuMemory)
243 return m_capsMemoryFormat;
244
245 return qMemoryFormatFromGstBuffer(buffer);
246 }();
247
248 qCDebug(qLcGstVideoRenderer) << "m_capsMemoryFormat" << m_capsMemoryFormat
249 << "bufferMemoryFormat" << bufferMemoryFormat;
250
251 QVideoFrameFormat bufferVideoFrameFormat = m_format;
252
253 // When rendering DMAbuf frames with OpenGLES, EGL seems to do implicit YUV->RGB conversion for
254 // UYVY and YUYV (YUY2), so we need to change the pixel format to Format_RGBA8888 to select the
255 // correct shader.
256 const bool setFormat_RGBA8888 = [&] {
257#if QT_CONFIG(gstreamer_gl_egl) && QT_CONFIG(linux_dmabuf)
258 QRhi *rhi = m_sink ? m_sink->rhi() : nullptr;
259 if ((m_format.pixelFormat() == QVideoFrameFormat::Format_UYVY
260 || m_format.pixelFormat() == QVideoFrameFormat::Format_YUYV)
261 && bufferMemoryFormat == QGstCaps::DMABuf && qGstEglCanMapDmaBuf(rhi)) {
262
263 if (!rhi || rhi->backend() != QRhi::OpenGLES2)
264 return false;
265
266 auto *nativeHandles = static_cast<const QRhiGles2NativeHandles *>(rhi->nativeHandles());
267 QOpenGLContext *glContext = nativeHandles ? nativeHandles->context : nullptr;
268 return glContext && glContext->isOpenGLES();
269 }
270#endif
271 return false;
272 }();
273 if (setFormat_RGBA8888) {
274 // TODO: Replace with new private setter of pixel format.
275 qCDebug(qLcGstVideoRenderer) << "Setting pixel format to Format_RGBA8888";
276 bufferVideoFrameFormat = QVideoFrameFormat(m_format.frameSize(),
277 QVideoFrameFormat::Format_RGBA8888);
278 bufferVideoFrameFormat.setStreamFrameRate(m_format.streamFrameRate());
279 bufferVideoFrameFormat.setColorRange(m_format.colorRange());
280 bufferVideoFrameFormat.setColorTransfer(m_format.colorTransfer());
281 bufferVideoFrameFormat.setColorSpace(m_format.colorSpace());
282 }
283
284 RenderBufferState state{
285 QGstBufferHandle{ buffer, QGstBufferHandle::NeedsRef },
286 bufferVideoFrameFormat,
287 m_videoInfo,
288 bufferMemoryFormat,
289 };
290
291 qCDebug(qLcGstVideoRenderer) << " sending video frame";
292
293 qsizetype sizeOfQueue = m_bufferQueue.enqueue(std::move(state));
294 if (sizeOfQueue == 1)
295 // we only need to wake up, if we don't have a pending frame
296 QCoreApplication::postEvent(this, new QEvent(renderFramesEvent));
297
298 return GST_FLOW_OK;
299}
300
301bool QGstVideoRenderer::query(GstQuery *query)
302{
303#if QT_CONFIG(gstreamer_gl)
304 if (GST_QUERY_TYPE(query) == GST_QUERY_CONTEXT) {
305 const gchar *type = nullptr;
306 gst_query_parse_context_type(query, &type);
307
308 QLatin1StringView typeStr(type);
309 if (typeStr != QLatin1StringView("gst.gl.GLDisplay")
310 && typeStr != QLatin1StringView("gst.gl.local_context")) {
311 return false;
312 }
313
314 QMutexLocker locker(&m_sinkMutex);
315 if (!m_sink)
316 return false;
317
318 auto *gstGlContext = typeStr == QLatin1StringView("gst.gl.GLDisplay")
319 ? m_sink->gstGlDisplayContext() : m_sink->gstGlLocalContext();
320 if (!gstGlContext)
321 return false;
322
323 gst_query_set_context(query, gstGlContext);
324
325 return true;
326 }
327#else
328 Q_UNUSED(query);
329#endif
330 return false;
331}
332
333void QGstVideoRenderer::gstEvent(GstEvent *event)
334{
335 qCDebug(qLcGstVideoRenderer) << "QGstVideoRenderer::gstEvent:" << event;
336
337 switch (GST_EVENT_TYPE(event)) {
338 case GST_EVENT_TAG:
339 return gstEventHandleTag(event);
340 case GST_EVENT_EOS:
341 return gstEventHandleEOS(event);
342 case GST_EVENT_FLUSH_START:
343 return gstEventHandleFlushStart(event);
344 case GST_EVENT_FLUSH_STOP:
345 return gstEventHandleFlushStop(event);
346
347 default:
348 return;
349 }
350}
351
352void QGstVideoRenderer::setActive(bool isActive)
353{
354 if (isActive == m_isActive)
355 return;
356
357 m_isActive = isActive;
358 if (isActive)
359 updateCurrentVideoFrame(m_currentPipelineFrame);
360 else
361 updateCurrentVideoFrame({});
362}
363
364void QGstVideoRenderer::updateCurrentVideoFrame(QVideoFrame frame)
365{
366 m_currentVideoFrame = std::move(frame);
367 if (m_sink)
368 m_sink->setVideoFrame(m_currentVideoFrame);
369}
370
371void QGstVideoRenderer::gstEventHandleTag(GstEvent *event)
372{
373 GstTagList *taglist = nullptr;
374 gst_event_parse_tag(event, &taglist);
375 if (!taglist)
376 return;
377
378 qCDebug(qLcGstVideoRenderer) << "QGstVideoRenderer::gstEventHandleTag:" << taglist;
379
380 QGString value;
381 if (!gst_tag_list_get_string(taglist, GST_TAG_IMAGE_ORIENTATION, &value))
382 return;
383
384 RotationResult parsed = parseRotationTag(value.get());
385
386 m_format.setMirrored(parsed.flip);
387 m_format.setRotation(parsed.rotation);
388}
389
390void QGstVideoRenderer::gstEventHandleEOS(GstEvent *)
391{
392 stop();
393}
394
395void QGstVideoRenderer::gstEventHandleFlushStart(GstEvent *)
396{
397 // "data is to be discarded"
398 m_flushing = true;
399 m_bufferQueue.clear();
400}
401
402void QGstVideoRenderer::gstEventHandleFlushStop(GstEvent *)
403{
404 // "data is allowed again"
405 m_flushing = false;
406}
407
410
411#define VO_SINK(s) QGstVideoRendererSink *sink(reinterpret_cast<QGstVideoRendererSink *>(s))
412
414{
415 setSink(sink);
416 QGstVideoRendererSink *gstSink = reinterpret_cast<QGstVideoRendererSink *>(
417 g_object_new(QGstVideoRendererSink::get_type(), nullptr));
418
419 return QGstVideoRendererSinkElement{
420 gstSink,
421 QGstElement::NeedsRef,
422 };
423}
424
426{
427 gvrs_current_sink = sink;
428}
429
430GType QGstVideoRendererSink::get_type()
431{
432 static const GTypeInfo info =
433 {
434 sizeof(QGstVideoRendererSinkClass), // class_size
435 base_init, // base_init
436 nullptr, // base_finalize
437 class_init, // class_init
438 nullptr, // class_finalize
439 nullptr, // class_data
440 sizeof(QGstVideoRendererSink), // instance_size
441 0, // n_preallocs
442 instance_init, // instance_init
443 nullptr // value_table
444 };
445
446 static const GType type = g_type_register_static(GST_TYPE_VIDEO_SINK, "QGstVideoRendererSink",
447 &info, GTypeFlags(0));
448
449 return type;
450}
451
452void QGstVideoRendererSink::class_init(gpointer g_class, gpointer class_data)
453{
454 Q_UNUSED(class_data);
455
456 gvrs_sink_parent_class = reinterpret_cast<GstVideoSinkClass *>(g_type_class_peek_parent(g_class));
457
458 GstVideoSinkClass *video_sink_class = reinterpret_cast<GstVideoSinkClass *>(g_class);
459 video_sink_class->show_frame = QGstVideoRendererSink::show_frame;
460
461 GstBaseSinkClass *base_sink_class = reinterpret_cast<GstBaseSinkClass *>(g_class);
462 base_sink_class->get_caps = QGstVideoRendererSink::get_caps;
463 base_sink_class->set_caps = QGstVideoRendererSink::set_caps;
464 base_sink_class->propose_allocation = QGstVideoRendererSink::propose_allocation;
465 base_sink_class->stop = QGstVideoRendererSink::stop;
466 base_sink_class->unlock = QGstVideoRendererSink::unlock;
467 base_sink_class->query = QGstVideoRendererSink::query;
468 base_sink_class->event = QGstVideoRendererSink::event;
469
470 GstElementClass *element_class = reinterpret_cast<GstElementClass *>(g_class);
471 element_class->change_state = QGstVideoRendererSink::change_state;
472 gst_element_class_set_metadata(element_class,
473 "Qt built-in video renderer sink",
474 "Sink/Video",
475 "Qt default built-in video renderer sink",
476 "The Qt Company");
477
478 GObjectClass *object_class = reinterpret_cast<GObjectClass *>(g_class);
479 object_class->finalize = QGstVideoRendererSink::finalize;
480}
481
482void QGstVideoRendererSink::base_init(gpointer g_class)
483{
484 static GstStaticPadTemplate sink_pad_template = GST_STATIC_PAD_TEMPLATE(
485 "sink", GST_PAD_SINK, GST_PAD_ALWAYS, GST_STATIC_CAPS(
486 "video/x-raw, "
487 "framerate = (fraction) [ 0, MAX ], "
488 "width = (int) [ 1, MAX ], "
489 "height = (int) [ 1, MAX ]"));
490
491 gst_element_class_add_pad_template(
492 GST_ELEMENT_CLASS(g_class), gst_static_pad_template_get(&sink_pad_template));
493}
494
495void QGstVideoRendererSink::instance_init(GTypeInstance *instance, gpointer g_class)
496{
497 Q_UNUSED(g_class);
498 VO_SINK(instance);
499
500 Q_ASSERT(gvrs_current_sink);
501
502 sink->renderer = new QGstVideoRenderer(gvrs_current_sink);
503 sink->renderer->moveToThread(gvrs_current_sink->thread());
504 gvrs_current_sink = nullptr;
505}
506
507void QGstVideoRendererSink::finalize(GObject *object)
508{
509 VO_SINK(object);
510
511 delete sink->renderer;
512
513 // Chain up
514 G_OBJECT_CLASS(gvrs_sink_parent_class)->finalize(object);
515}
516
517GstStateChangeReturn QGstVideoRendererSink::change_state(
518 GstElement *element, GstStateChange transition)
519{
520 GstStateChangeReturn ret =
521 GST_ELEMENT_CLASS(gvrs_sink_parent_class)->change_state(element, transition);
522 qCDebug(qLcGstVideoRenderer) << "QGstVideoRenderer::change_state:" << transition << ret;
523 return ret;
524}
525
526GstCaps *QGstVideoRendererSink::get_caps(GstBaseSink *base, GstCaps *filter)
527{
528 VO_SINK(base);
529
530 QGstCaps caps = sink->renderer->caps();
531 if (filter)
532 caps = QGstCaps(gst_caps_intersect(caps.caps(), filter), QGstCaps::HasRef);
533
534 return caps.release();
535}
536
537gboolean QGstVideoRendererSink::set_caps(GstBaseSink *base, GstCaps *gcaps)
538{
539 VO_SINK(base);
540 auto caps = QGstCaps(gcaps, QGstCaps::NeedsRef);
541
542 qCDebug(qLcGstVideoRenderer) << "set_caps:" << caps;
543
544 if (!caps) {
545 sink->renderer->stop();
546 return TRUE;
547 }
548
549 return sink->renderer->start(caps);
550}
551
552gboolean QGstVideoRendererSink::propose_allocation(GstBaseSink *base, GstQuery *query)
553{
554 VO_SINK(base);
555 return sink->renderer->proposeAllocation(query);
556}
557
558gboolean QGstVideoRendererSink::stop(GstBaseSink *base)
559{
560 VO_SINK(base);
561 sink->renderer->stop();
562 return TRUE;
563}
564
565gboolean QGstVideoRendererSink::unlock(GstBaseSink *base)
566{
567 VO_SINK(base);
568 sink->renderer->unlock();
569 return TRUE;
570}
571
572GstFlowReturn QGstVideoRendererSink::show_frame(GstVideoSink *base, GstBuffer *buffer)
573{
574 VO_SINK(base);
575 return sink->renderer->render(buffer);
576}
577
578gboolean QGstVideoRendererSink::query(GstBaseSink *base, GstQuery *query)
579{
580 VO_SINK(base);
581 if (sink->renderer->query(query))
582 return TRUE;
583
584 return GST_BASE_SINK_CLASS(gvrs_sink_parent_class)->query(base, query);
585}
586
587gboolean QGstVideoRendererSink::event(GstBaseSink *base, GstEvent * event)
588{
589 VO_SINK(base);
590 sink->renderer->gstEvent(event);
591 return GST_BASE_SINK_CLASS(gvrs_sink_parent_class)->event(base, event);
592}
593
602
604{
605 qGstVideoRendererSink()->renderer->setActive(isActive);
606}
607
609{
610 return reinterpret_cast<QGstVideoRendererSink *>(element());
611}
612
613QT_END_NAMESPACE
MemoryFormat memoryFormat() const
Definition qgst.cpp:610
static QGstCaps create()
Definition qgst.cpp:637
MemoryFormat
Definition qgst_p.h:394
@ CpuMemory
Definition qgst_p.h:394
QGstVideoRendererSinkElement(QGstVideoRendererSink *, RefMode)
QGstVideoRendererSink * qGstVideoRendererSink() const
static QGstVideoRendererSinkElement createSink(QGstreamerRelayVideoSink *surface)
GstFlowReturn render(GstBuffer *)
~QGstVideoRenderer() override
void customEvent(QEvent *) override
This event handler can be reimplemented in a subclass to receive custom events.
bool start(const QGstCaps &)
QGstVideoRenderer(QGstreamerRelayVideoSink *)
bool proposeAllocation(GstQuery *)
void setFrameTimeStampsFromBuffer(QVideoFrame *frame, GstBuffer *buffer)
typedefQT_BEGIN_NAMESPACE struct _GstBuffer GstBuffer
#define VO_SINK(s)
static GstVideoSinkClass * gvrs_sink_parent_class
static QGstreamerRelayVideoSink * gvrs_current_sink
QT_BEGIN_NAMESPACE Q_STATIC_LOGGING_CATEGORY(lcSynthesizedIterableAccess, "qt.iterable.synthesized", QtWarningMsg)