4#include <gst/video/video-info.h>
5#include <gst/video/video.h>
10#include <QtCore/QRect>
11#include <QtCore/QSize>
12#include <QtMultimedia/QVideoFrame>
13#include <QtMultimedia/QVideoFrameFormat>
14#include <QtMultimedia/QVideoSink>
31#define GST_CAT_DEFAULT gst_qgc_debug
42 std::atomic<bool> active{
true};
44 bool gpu_zerocopy =
false;
47 bool square_pixels =
true;
50 GstCaps* offered_caps =
nullptr;
53 GstVideoInfo video_info = {};
54 QVideoFrameFormat format;
58 QVideoFrameFormat frame_format;
60 std::atomic<int> picture_width{0};
61 std::atomic<int> picture_height{0};
66 bool gpu_caps =
false;
68 std::atomic<int> stream_orientation{GST_VIDEO_ORIENTATION_IDENTITY};
73 GstCaps* cached_caps{
nullptr};
89inline PrivState* priv_of(GstQgcQVideoSink* self)
98 GST_OBJECT_LOCK(self);
99 hwOut = priv_of(self)->hw_context;
100 GST_OBJECT_UNLOCK(self);
101 return priv_of(self)->delivery.sink() !=
nullptr;
115 const ImportState& imports)
119 return {.gpuZeroCopy = p->gpu_zerocopy,
120 .gpuBin = p->gpu_bin,
122 .dmaBufDisplay = followsRenderer ? imports.dmaBufDisplay :
nullptr,
123 .d3d11OpensD3D12 = followsRenderer && imports.d3d11OpensD3D12,
124 .squarePixels = p->square_pixels};
128GstCaps* offered_caps(GstQgcQVideoSink* self)
130 PrivState*
const p = priv_of(self);
132 const ImportState imports;
133 GST_OBJECT_LOCK(self);
135 if (p->offered_caps && (p->offered_policy == policy)) {
136 GstCaps*
const cached = gst_caps_ref(p->offered_caps);
137 GST_OBJECT_UNLOCK(self);
140 GST_OBJECT_UNLOCK(self);
144 GST_ERROR_OBJECT(self,
"sink caps did not parse");
145 return gst_caps_new_empty();
148 self,
"offering %" GST_PTR_FORMAT
" for render backend %s (EGL %d, DMABuf import %d, D3D12 import %d)", caps,
150 GST_OBJECT_LOCK(self);
151 gst_caps_replace(&p->offered_caps, caps);
152 p->offered_policy = policy;
153 GST_OBJECT_UNLOCK(self);
163 PrivState*
const p = priv_of(self);
165 const ImportState imports;
166 GST_OBJECT_LOCK(self);
168 const bool changed = p->offered_caps && (p->offered_policy != policy);
171 gst_clear_caps(&p->offered_caps);
173 GST_OBJECT_UNLOCK(self);
175 GST_INFO_OBJECT(self,
176 "render backend now %s (EGL %d), DMABuf import %d, D3D12 import %d; asking upstream to "
180 (void) gst_pad_push_event(GST_BASE_SINK_PAD(self), gst_event_new_reconfigure());
186bool caps_carry_gpu_memory(GstCaps* caps)
188 const GstCapsFeatures*
const features = gst_caps_get_features(caps, 0);
189 if (!features || gst_caps_features_is_any(features)) {
192 for (guint i = 0; i < gst_caps_features_get_size(features); ++i) {
193 const gchar*
const feature = gst_caps_features_get_nth(features, i);
194 if (g_str_has_prefix(feature,
"memory:") && (g_strcmp0(feature, GST_CAPS_FEATURE_MEMORY_SYSTEM_MEMORY) != 0)) {
202bool nothing_to_import(GstBuffer* buf)
204 if (gst_buffer_n_memory(buf) == 0) {
207 GstMemory*
const mem = gst_buffer_peek_memory(buf, 0);
208 return mem && gst_memory_is_type(mem, GST_ALLOCATOR_SYSMEM);
212const char* map_failure_stage(
const MappedFrame& mapped)
215 return "tiled layout that no GPU path imported";
217 return mapped.
demoted ?
"CPU fallback from a GPU path" :
"CPU path";
224 GST_STATIC_PAD_TEMPLATE(
"sink", GST_PAD_SINK, GST_PAD_ALWAYS, GST_STATIC_CAPS(
"video/x-raw(ANY)"));
245 new (&self->state) PrivState();
246 gst_video_info_init(&self->state.video_info);
249 gst_base_sink_set_sync(GST_BASE_SINK(self), FALSE);
250 gst_base_sink_set_async_enabled(GST_BASE_SINK(self), FALSE);
252 gst_base_sink_set_last_sample_enabled(GST_BASE_SINK(self), FALSE);
260 G_OBJECT_CLASS(gst_qgc_q_video_sink_parent_class)->constructed(obj);
261 g_object_set(obj,
"show-preroll-frame", FALSE,
nullptr);
266 GstQgcQVideoSink* self = GST_QGC_Q_VIDEO_SINK(obj);
267 gst_clear_caps(&priv_of(self)->cached_caps);
268 gst_clear_caps(&priv_of(self)->offered_caps);
269 self->state.~PrivState();
270 G_OBJECT_CLASS(gst_qgc_q_video_sink_parent_class)->finalize(obj);
275 GstQgcQVideoSink* self = GST_QGC_Q_VIDEO_SINK(obj);
276 PrivState* p = priv_of(self);
278 p->delivery.
setSink(
static_cast<QVideoSink*
>(g_value_get_pointer(val)));
281 GST_OBJECT_LOCK(self);
284 p->active.store(g_value_get_boolean(val), std::memory_order_relaxed);
287 p->gpu_zerocopy = g_value_get_boolean(val);
290 G_OBJECT_WARN_INVALID_PROPERTY_ID(obj,
id, pspec);
293 GST_OBJECT_UNLOCK(self);
298 GstQgcQVideoSink* self = GST_QGC_Q_VIDEO_SINK(obj);
299 GST_OBJECT_LOCK(self);
302 g_value_set_pointer(val, priv_of(self)->delivery.sink());
305 g_value_set_boolean(val, priv_of(self)->active.load(std::memory_order_relaxed));
308 g_value_set_boolean(val, priv_of(self)->gpu_zerocopy);
311 g_value_set_uint64(val, priv_of(self)->counters.input());
314 g_value_set_uint64(val, priv_of(self)->counters.dropped());
317 g_value_set_uint64(val, priv_of(self)->counters.delivered());
320 g_value_take_boxed(val, priv_of(self)->counters.frameStats());
323 g_value_set_int(val, priv_of(self)->picture_width.load(std::memory_order_relaxed));
326 g_value_set_int(val, priv_of(self)->picture_height.load(std::memory_order_relaxed));
329 G_OBJECT_WARN_INVALID_PROPERTY_ID(obj,
id, pspec);
332 GST_OBJECT_UNLOCK(self);
337 GstCaps* caps = offered_caps(GST_QGC_Q_VIDEO_SINK(bsink));
339 GstCaps*
const filtered = gst_caps_intersect_full(filter, caps, GST_CAPS_INTERSECT_FIRST);
340 gst_caps_unref(caps);
348 GstQgcQVideoSink* self = GST_QGC_Q_VIDEO_SINK(bsink);
349 PrivState* p = priv_of(self);
351 GstVideoInfo parsedInfo = {};
353 qCWarning(GstQgcQVideoSinkLog) <<
"set_caps: failed to parse video info from caps";
357 const QVideoFrameFormat::PixelFormat pixelFormat =
toQtPixelFormat(GST_VIDEO_INFO_FORMAT(&parsedInfo));
358 if (pixelFormat == QVideoFrameFormat::Format_Invalid) {
359 qCWarning(GstQgcQVideoSinkLog) <<
"set_caps: unsupported video format"
360 << gst_video_format_to_string(GST_VIDEO_INFO_FORMAT(&parsedInfo));
364 const int w = GST_VIDEO_INFO_WIDTH(&parsedInfo);
365 const int h = GST_VIDEO_INFO_HEIGHT(&parsedInfo);
366 if (w <= 0 || h <= 0) {
367 qCWarning(GstQgcQVideoSinkLog) <<
"set_caps: invalid dimensions" << w <<
"x" << h;
371 QVideoFrameFormat fmt(QSize(w, h), pixelFormat);
373 const int fpsN = GST_VIDEO_INFO_FPS_N(&parsedInfo);
374 const int fpsD = GST_VIDEO_INFO_FPS_D(&parsedInfo);
375 if (fpsN > 0 && fpsD > 0) {
376 fmt.setStreamFrameRate(
static_cast<qreal
>(fpsN) /
static_cast<qreal
>(fpsD));
379 p->video_info = parsedInfo;
380 p->format = std::move(fmt);
381 p->frame_geometry = {.frameSize = QSize(w, h), .picture = QRect(0, 0, w, h), .pictureSize = QSize(w, h)};
382 p->picture_width.store(w, std::memory_order_relaxed);
383 p->picture_height.store(h, std::memory_order_relaxed);
384 p->frame_format = p->format;
385 gst_clear_caps(&p->cached_caps);
388 p->cached_caps = gst_caps_ref(caps);
389 p->gpu_caps = caps_carry_gpu_memory(caps);
392 qCInfo(GstQgcQVideoSinkLog).noquote()
393 <<
"set_caps: format=" << gst_video_format_to_string(GST_VIDEO_INFO_FORMAT(&parsedInfo)) << w <<
"x" << h
394 <<
"pixfmt=" << int(pixelFormat);
400 GstQgcQVideoSink* self = GST_QGC_Q_VIDEO_SINK(vsink);
401 PrivState* p = priv_of(self);
406 if (!p->cached_caps) {
408 return GST_FLOW_NOT_NEGOTIATED;
410 if (!p->active.load(std::memory_order_relaxed)) {
416 if (!snapshot_sink(self, hwCtx)) {
426 p->frame_geometry = geometry;
428 p->picture_width.store(geometry.pictureSize.width(), std::memory_order_relaxed);
429 p->picture_height.store(geometry.pictureSize.height(), std::memory_order_relaxed);
432 p->pinned_cpu_frames, p->path_session.
pathCache());
433 if (!mapped.
frame.isValid()) {
437 const char*
const format = gst_video_format_to_string(GST_VIDEO_INFO_FORMAT(&p->video_info));
439 GST_ELEMENT_ERROR(self, STREAM, FAILED, (
"Video frames could not be mapped for display"),
440 (
"%" G_GUINT64_FORMAT
" consecutive map failures (%s, format %s)",
441 static_cast<guint64
>(failures), map_failure_stage(mapped), format ? format :
"unknown"));
442 return GST_FLOW_ERROR;
451 const QSize frameSize = mapped.
frame.size();
460 if (delivered == 1) {
461 qCInfo(GstQgcQVideoSinkLog).noquote()
463 << QStringLiteral(
"%1x%2").arg(frameSize.width()).arg(frameSize.height());
464 }
else if ((delivered % 300) == 0) {
465 qCDebug(GstQgcQVideoSinkLog).noquote()
467 <<
"input=" << p->counters.
input() <<
"dropped=" << p->counters.
dropped()
476 GstQgcQVideoSink* self = GST_QGC_Q_VIDEO_SINK(bsink);
477 switch (GST_EVENT_TYPE(event)) {
478 case GST_EVENT_TAG: {
480 GstTagList* tags =
nullptr;
481 gst_event_parse_tag(event, &tags);
482 GstVideoOrientationMethod method = GST_VIDEO_ORIENTATION_IDENTITY;
483 if (tags && gst_video_orientation_from_tag(tags, &method)) {
484 priv_of(self)->stream_orientation.store(method, std::memory_order_relaxed);
488 case GST_EVENT_FLUSH_START:
489 priv_of(self)->delivery.dropPending();
491 case GST_EVENT_STREAM_START:
493 priv_of(self)->stream_orientation.store(GST_VIDEO_ORIENTATION_IDENTITY, std::memory_order_relaxed);
498 return GST_BASE_SINK_CLASS(gst_qgc_q_video_sink_parent_class)->event(bsink, event);
504 GstQgcQVideoSink* self = GST_QGC_Q_VIDEO_SINK(bsink);
506 GST_OBJECT_LOCK(self);
507 priv_of(self)->hw_context = hwContext;
508 GST_OBJECT_UNLOCK(self);
510 GstBaseSinkClass* parentClass = GST_BASE_SINK_CLASS(gst_qgc_q_video_sink_parent_class);
511 return parentClass->start ? parentClass->start(bsink) : TRUE;
518 GstQgcQVideoSink* self = GST_QGC_Q_VIDEO_SINK(bsink);
519 PrivState* p = priv_of(self);
520 gst_clear_caps(&p->cached_caps);
522 p->path_session.
stop();
523 p->stream_orientation.store(GST_VIDEO_ORIENTATION_IDENTITY, std::memory_order_relaxed);
526 GstBaseSinkClass* parentClass = GST_BASE_SINK_CLASS(gst_qgc_q_video_sink_parent_class);
527 return parentClass->stop ? parentClass->stop(bsink) : TRUE;
539 GstBaseSinkClass* parentClass = GST_BASE_SINK_CLASS(gst_qgc_q_video_sink_parent_class);
540 if (parentClass->propose_allocation) {
541 return parentClass->propose_allocation(bsink, query);
550 if ((GST_QUERY_TYPE(query) == GST_QUERY_CONTEXT) &&
554 if (GST_QUERY_TYPE(query) == GST_QUERY_ACCEPT_CAPS) {
556 GstCaps* caps =
nullptr;
557 gst_query_parse_accept_caps(query, &caps);
558 GstCaps*
const offered = offered_caps(GST_QGC_Q_VIDEO_SINK(bsink));
559 gst_query_set_accept_caps_result(query, caps && gst_caps_can_intersect(caps, offered));
560 gst_caps_unref(offered);
563 return GST_BASE_SINK_CLASS(gst_qgc_q_video_sink_parent_class)->query(bsink, query);
568 GObjectClass* gobject_class = G_OBJECT_CLASS(klass);
569 GstElementClass* element_class = GST_ELEMENT_CLASS(klass);
570 GstBaseSinkClass* basesink_class = GST_BASE_SINK_CLASS(klass);
571 GstVideoSinkClass* videosink_class = GST_VIDEO_SINK_CLASS(klass);
578 g_object_class_install_property(
580 g_param_spec_pointer(
"qvideosink",
"QVideoSink target",
581 "QVideoSink* to push frames into. Caller-owned; element never unrefs.",
582 (GParamFlags) (G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS)));
584 g_object_class_install_property(
586 g_param_spec_boolean(
"active",
"Active",
587 "When FALSE, show_frame drops buffers instead of pushing to the QVideoSink.", TRUE,
588 (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
590 g_object_class_install_property(
592 g_param_spec_boolean(
"gpu-zerocopy",
"GPU zero-copy",
593 "Import frames in GPU memory without a copy when a zero-copy path supports them; "
594 "FALSE maps every frame through the CPU.",
596 (GParamFlags) (G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS)));
598 g_object_class_install_property(
600 g_param_spec_uint64(
"frames-input",
"Frames input",
"Total buffers seen by show_frame, including drops.", 0,
601 G_MAXUINT64, 0, (GParamFlags) (G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)));
603 g_object_class_install_property(
605 g_param_spec_uint64(
"frames-dropped",
"Frames dropped",
606 "Buffers rejected by show_frame (inactive sink, missing QVideoSink, or map failure). "
607 "Detailed map failures are tracked separately in GstHwPathTelemetry.",
608 0, G_MAXUINT64, 0, (GParamFlags) (G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)));
610 g_object_class_install_property(
612 g_param_spec_uint64(
"frames-delivered",
"Frames delivered",
613 "Buffers that survived every drop check and were handed to the QVideoSink. Delivery keeps "
614 "only the latest frame, so frames superseded before the GUI thread ran are counted too. "
615 "Per-element — the GUI controller reads this for the QML frameCount.",
616 0, G_MAXUINT64, 0, (GParamFlags) (G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)));
619 g_object_class_install_property(
621 g_param_spec_boxed(
"frame-stats",
"Frame statistics",
622 "This sink's own frame accounting, as a qgc-video-sink-stats structure of guint64 fields: "
623 "frames-<path> per delivery path (frames-cpu, frames-dmabuf, frames-gl, frames-d3d11, "
624 "frames-d3d12, frames-iosurface, frames-ahwbuf, frames-vulkan); gpu-fallbacks (frames a GPU "
625 "path was tried for but the CPU delivered), stream-demotions (caps epochs that fell back "
626 "from a GPU path), tiled-drops (frames in a tiled DMA_DRM layout that no GPU path "
627 "imported and the CPU can't read) and superseded-frames (delivered frames a newer one "
628 "replaced before the QVideoSink took them).",
629 GST_TYPE_STRUCTURE, (GParamFlags) (G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)));
632 g_object_class_install_property(
634 g_param_spec_int(
"picture-width",
"Picture width",
635 "Width of the picture in the last buffer, before its orientation: the crop meta's, else the "
636 "caps'. 0 before caps.",
637 0, G_MAXINT, 0, (GParamFlags) (G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)));
638 g_object_class_install_property(
640 g_param_spec_int(
"picture-height",
"Picture height",
"Height of that picture.", 0, G_MAXINT, 0,
641 (GParamFlags) (G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)));
643 gst_element_class_set_static_metadata(element_class,
"QGC QVideoSink",
"Sink/Video",
644 "Pushes decoded GstVideoFrames into a Qt QVideoSink",
645 "QGroundControl <https://qgroundcontrol.com/>");
646 gst_element_class_add_static_pad_template(element_class, &
sink_template);
662 if (!sink || !GST_IS_QGC_Q_VIDEO_SINK(sink)) {
665 GstQgcQVideoSink*
const self = GST_QGC_Q_VIDEO_SINK(sink);
666 GST_OBJECT_LOCK(self);
667 priv_of(self)->gpu_bin = gpuBin;
668 priv_of(self)->square_pixels = squarePixels;
669 gst_clear_caps(&priv_of(self)->offered_caps);
670 GST_OBJECT_UNLOCK(self);
QVideoFrameFormat::PixelFormat toQtPixelFormat(GstVideoFormat fmt)
void applyColorimetry(QVideoFrameFormat &format, const GstVideoInfo &info, GstCaps *caps)
FrameGeometry frameGeometry(GstBuffer *buffer, const GstVideoInfo &capsInfo)
QVideoFrameFormat withFrameGeometry(QVideoFrameFormat format, const FrameGeometry &geometry)
format for frames of geometry: its frame size, with the picture as the viewport.
void applyFlips(QVideoFrame &frame, const FrameGeometry &geometry)
Flips frame's picture as geometry tells, ahead of the rotation and mirroring the frame already has.
void applyOrientationAndTiming(QVideoFrame &frame, GstBuffer *buffer, int streamOrientation)
The stream's orientation + PTS/duration timing; streamOrientation is GstVideoOrientationMethod cast t...
MappedFrame mapSampleToFrame(GstBuffer *buffer, GstCaps *caps, const GstVideoInfo &info, const QVideoFrameFormat &format, const HwVideoBufferContext &hwContext, const CpuVideoFramePool::PinnedFrameCounter &pinnedCpuFrames, HwResolvedPathCache *pathCache)
struct _GstElement GstElement
#define QGC_LOGGING_CATEGORY(name, categoryStr)
std::shared_ptr< std::atomic< int > > PinnedFrameCounter
Live zero-copy frames of one sink; shared so frames Qt still holds after the sink is gone can release...
qgcqvideosink's latest-frame-only hand-off to a QVideoSink, on the QVideoSink's thread.
void setSink(QVideoSink *sink)
Result deliver(QVideoFrame &&frame)
Hands frame over as the newest.
void dropPending()
Drops an undelivered frame, releasing the decoder buffer it pins.
What qgcqvideosink keeps about the path its frames take through one caps epoch, from set_caps to the ...
void stop()
The sink stopped: as startEpoch(), and a run of map failures ends.
Verdict onMapFailed(const MappedFrame &mapped, SinkCounters &counters)
void onMapped()
The frame mapped: a run of failures ends.
void onDelivered(const MappedFrame &mapped, SinkCounters &counters)
HwResolvedPathCache * pathCache()
For mapSampleToFrame(), which caches the path it resolves in the epoch.
quint64 consecutiveMapFailures() const
void startEpoch()
New caps: the path is resolved anew, and the once-per-epoch bookkeeping starts over.
qgcqvideosink's frame accounting: what its frames-input, frames-dropped and frames-delivered properti...
quint64 noteDelivered(HwVideoBufferPath path, bool superseded)
quint64 pathFrames(HwVideoBufferPath path) const
static gboolean gst_qgc_q_video_sink_start(GstBaseSink *bsink)
static gboolean gst_qgc_q_video_sink_set_caps(GstBaseSink *bsink, GstCaps *caps)
static void gst_qgc_q_video_sink_constructed(GObject *obj)
static GstCaps * gst_qgc_q_video_sink_get_caps(GstBaseSink *bsink, GstCaps *filter)
static void gst_qgc_q_video_sink_get_property(GObject *obj, guint id, GValue *val, GParamSpec *pspec)
static void gst_qgc_q_video_sink_set_property(GObject *obj, guint id, const GValue *val, GParamSpec *pspec)
static GstStaticPadTemplate sink_template
get_caps narrows this to the formats and memory the sink takes for its render target.
static void gst_qgc_q_video_sink_finalize(GObject *obj)
static gboolean gst_qgc_q_video_sink_propose_allocation(GstBaseSink *bsink, GstQuery *query)
static GstFlowReturn gst_qgc_q_video_sink_show_frame(GstVideoSink *vsink, GstBuffer *buf)
static void gst_qgc_q_video_sink_init(GstQgcQVideoSink *self)
static void gst_qgc_q_video_sink_class_init(GstQgcQVideoSinkClass *klass)
static gboolean gst_qgc_q_video_sink_query(GstBaseSink *bsink, GstQuery *query)
static gboolean gst_qgc_q_video_sink_stop(GstBaseSink *bsink)
static gboolean gst_qgc_q_video_sink_event(GstBaseSink *bsink, GstEvent *event)
#define GST_TYPE_QGC_Q_VIDEO_SINK
G_DEFINE_FINAL_TYPE(GstQgcVideoSinkBin, gst_qgc_video_sink_bin, GST_TYPE_BIN)
bool dmaDrmAwareVideoInfo(GstCaps *caps, GstVideoInfo *info)
constexpr const char * toString(HwVideoBufferPath path) noexcept
GstVideoSink that pushes decoded frames into a Qt QVideoSink; sole sink in qgcvideosinkbin....
RenderTarget currentRenderTarget()
bool populateAllocationQuery(GstQuery *query)
void configureSinkCaps(GstElement *sink, GpuBinMode gpuBin, bool squarePixels)
const char * toString(RenderBackend backend) noexcept
@ GlUpload
glupload → glcolorconvert → GLMemory 2D; gst-gl imports LINEAR and vendor-tiled DMABuf.
@ Passthrough
Every compiled native memory straight into qgcqvideosink (Windows, Apple, ...).
std::string buildSinkCaps(const SinkCapsPolicy &policy)
bool d3d11OpensD3D12() noexcept
void * dmaBufImportDisplay() noexcept
bool answerSinkBinContextQuery(GstQuery *query, GstElement *sink) noexcept
HwVideoBufferContext makeAdapterContext(bool gpuEnabled) noexcept
bool superseded
It replaced a frame the QVideoSink hadn't taken yet.
bool delivered
False when no QVideoSink is bound.
Everything qgcqvideosink's caps depend on.
bool d3d11OpensD3D12
Qt's Direct3D 11 device opens a Direct3D 12 device's resources (HwBuffers::d3d11OpensD3D12()).
HwVideoBufferPath gpuPath
None for a CPU frame, and for one that failed to map.
bool demoted
A GPU path was requested for this stream but this frame fell back to CPU.
bool noCpuLayout
Dropped instead of read as linear rows, which would show it scrambled.