QGroundControl
Ground Control Station for MAVLink Drones
Loading...
Searching...
No Matches
gstqgcqvideosink.cc
Go to the documentation of this file.
1#include "gstqgcqvideosink.h"
2
3#include <atomic>
4#include <gst/video/video-info.h>
5#include <gst/video/video.h>
6#include <memory>
7#include <new>
8#include <utility>
9
10#include <QtCore/QRect>
11#include <QtCore/QSize>
12#include <QtMultimedia/QVideoFrame>
13#include <QtMultimedia/QVideoFrameFormat>
14#include <QtMultimedia/QVideoSink>
15
16#include "GstQgcAllocation.h"
17#include "GstQgcCaps.h"
18#include "GstQgcFrameDelivery.h"
19#include "GstQgcFrameMap.h"
20#include "GstQgcPathSession.h"
21#include "GstQgcSinkCounters.h"
22#include "GstQgcSinkStats.h"
23#include "HwBuffers/HwBuffers.h"
25#include "QGCLoggingCategory.h"
26#include "gstqgcelements.h"
27#include "gstqgcvideosinkbin.h"
28
29QGC_LOGGING_CATEGORY(GstQgcQVideoSinkLog, "Video.GStreamer.QgcQVideoSink")
30
31#define GST_CAT_DEFAULT gst_qgc_debug
32
33namespace {
34
36struct PrivState
37{
38 // The QVideoSink frames go to, set by the controller on the GUI thread.
39 GstQgc::FrameDelivery delivery;
40 GstQgc::SinkCounters counters;
41 // Read lock-free by show_frame.
42 std::atomic<bool> active{true};
43 // start() derives hw_context from it.
44 bool gpu_zerocopy = false;
45 // Set by qgcvideosinkbin before linking (configureSinkCaps); with gpu_zerocopy, they decide what get_caps offers.
47 bool square_pixels = true;
48 // What get_caps last offered, and for which policy; under GST_OBJECT_LOCK. Rebuilt when the policy changes, e.g.
49 // the render target or the DMABuf import state: building may query EGL.
50 GstCaps* offered_caps = nullptr;
51 GstQgc::SinkCapsPolicy offered_policy;
52 // Negotiated state: set_caps/stop write it and show_frame reads it, all serialised by GstBaseSink.
53 GstVideoInfo video_info = {};
54 QVideoFrameFormat format;
55 // The geometry of the last buffer and format for frames of it. Buffers of one stream share theirs, so show_frame
56 // rebuilds the format only when a buffer's differs; set_caps starts from the caps' own.
57 FrameGeometry frame_geometry;
58 QVideoFrameFormat frame_format;
59 // frame_geometry's pictureSize, for the "picture-width" and "picture-height" properties.
60 std::atomic<int> picture_width{0};
61 std::atomic<int> picture_height{0};
62 // Written by start() under GST_OBJECT_LOCK and snapshotted by show_frame, which adds the current DMABuf display.
63 HwVideoBufferContext hw_context = {};
64 // Whether the negotiated caps carry a GPU memory feature. Without one, show_frame skips path selection for frames
65 // in plain system memory.
66 bool gpu_caps = false;
67 // GstVideoOrientationMethod from the stream's image-orientation tag.
68 std::atomic<int> stream_orientation{GST_VIDEO_ORIENTATION_IDENTITY};
69 // Live zero-copy CPU frames pinning this sink's decoder buffers; shared because Qt may hold frames past finalize.
70 CpuVideoFramePool::PinnedFrameCounter pinned_cpu_frames = std::make_shared<std::atomic<int>>(0);
71 // Negotiated caps held from set_caps, null before it and after stop; avoids per-frame allocation and preserves
72 // DRM modifiers.
73 GstCaps* cached_caps{nullptr};
74 // The path frames take through the caps epoch; set_caps starts a new one, so a format change re-runs path
75 // selection.
76 GstQgc::PathSession path_session;
77};
78
79} // namespace
80
82{
83 GstVideoSink parent;
84 PrivState state;
85};
86
87namespace {
88
89inline PrivState* priv_of(GstQgcQVideoSink* self)
90{
91 return &self->state;
92}
93
96bool snapshot_sink(GstQgcQVideoSink* self, HwVideoBufferContext& hwOut)
97{
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;
102}
103
105struct ImportState
106{
107 void* dmaBufDisplay = HwBuffers::dmaBufImportDisplay();
108 bool d3d11OpensD3D12 = HwBuffers::d3d11OpensD3D12();
109};
110
114GstQgc::SinkCapsPolicy caps_policy_locked(const PrivState* p, const GstQgc::RenderTarget& target,
115 const ImportState& imports)
116{
117 const bool followsRenderer = p->gpu_zerocopy && (p->gpu_bin != GstQgc::GpuBinMode::GlUpload) &&
118 (p->gpu_bin != GstQgc::GpuBinMode::D3D12Convert);
119 return {.gpuZeroCopy = p->gpu_zerocopy,
120 .gpuBin = p->gpu_bin,
121 .target = followsRenderer ? target : GstQgc::RenderTarget{},
122 .dmaBufDisplay = followsRenderer ? imports.dmaBufDisplay : nullptr,
123 .d3d11OpensD3D12 = followsRenderer && imports.d3d11OpensD3D12,
124 .squarePixels = p->square_pixels};
125}
126
128GstCaps* offered_caps(GstQgcQVideoSink* self)
129{
130 PrivState* const p = priv_of(self);
132 const ImportState imports;
133 GST_OBJECT_LOCK(self);
134 const GstQgc::SinkCapsPolicy policy = caps_policy_locked(p, target, imports);
135 if (p->offered_caps && (p->offered_policy == policy)) {
136 GstCaps* const cached = gst_caps_ref(p->offered_caps);
137 GST_OBJECT_UNLOCK(self);
138 return cached;
139 }
140 GST_OBJECT_UNLOCK(self);
141
142 GstCaps* caps = gst_caps_from_string(GstQgc::buildSinkCaps(policy).c_str());
143 if (!caps) {
144 GST_ERROR_OBJECT(self, "sink caps did not parse");
145 return gst_caps_new_empty();
146 }
147 GST_DEBUG_OBJECT(
148 self, "offering %" GST_PTR_FORMAT " for render backend %s (EGL %d, DMABuf import %d, D3D12 import %d)", caps,
149 GstQgc::toString(target.backend), target.egl, policy.dmaBufDisplay != nullptr, policy.d3d11OpensD3D12);
150 GST_OBJECT_LOCK(self);
151 gst_caps_replace(&p->offered_caps, caps);
152 p->offered_policy = policy;
153 GST_OBJECT_UNLOCK(self);
154 return caps;
155}
156
161GstQgc::SinkCapsPolicy reconfigure_on_policy_change(GstQgcQVideoSink* self)
162{
163 PrivState* const p = priv_of(self);
165 const ImportState imports;
166 GST_OBJECT_LOCK(self);
167 const GstQgc::SinkCapsPolicy policy = caps_policy_locked(p, target, imports);
168 const bool changed = p->offered_caps && (p->offered_policy != policy);
169 if (changed) {
170 // Rebuilt by the next get_caps, which also re-arms this check.
171 gst_clear_caps(&p->offered_caps);
172 }
173 GST_OBJECT_UNLOCK(self);
174 if (changed) {
175 GST_INFO_OBJECT(self,
176 "render backend now %s (EGL %d), DMABuf import %d, D3D12 import %d; asking upstream to "
177 "renegotiate",
178 GstQgc::toString(target.backend), target.egl, policy.dmaBufDisplay != nullptr,
179 policy.d3d11OpensD3D12);
180 (void) gst_pad_push_event(GST_BASE_SINK_PAD(self), gst_event_new_reconfigure());
181 }
182 return policy;
183}
184
186bool caps_carry_gpu_memory(GstCaps* caps)
187{
188 const GstCapsFeatures* const features = gst_caps_get_features(caps, 0);
189 if (!features || gst_caps_features_is_any(features)) {
190 return false;
191 }
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)) {
195 return true;
196 }
197 }
198 return false;
199}
200
202bool nothing_to_import(GstBuffer* buf)
203{
204 if (gst_buffer_n_memory(buf) == 0) {
205 return true;
206 }
207 GstMemory* const mem = gst_buffer_peek_memory(buf, 0);
208 return mem && gst_memory_is_type(mem, GST_ALLOCATOR_SYSMEM);
209}
210
212const char* map_failure_stage(const MappedFrame& mapped)
213{
214 if (mapped.noCpuLayout) {
215 return "tiled layout that no GPU path imported";
216 }
217 return mapped.demoted ? "CPU fallback from a GPU path" : "CPU path";
218}
219
220} // namespace
221
223static GstStaticPadTemplate sink_template =
224 GST_STATIC_PAD_TEMPLATE("sink", GST_PAD_SINK, GST_PAD_ALWAYS, GST_STATIC_CAPS("video/x-raw(ANY)"));
225
226enum
227{
238};
239
240G_DEFINE_FINAL_TYPE(GstQgcQVideoSink, gst_qgc_q_video_sink, GST_TYPE_VIDEO_SINK)
241GST_ELEMENT_REGISTER_DEFINE(qgcqvideosink, "qgcqvideosink", GST_RANK_NONE, GST_TYPE_QGC_Q_VIDEO_SINK)
242
243static void gst_qgc_q_video_sink_init(GstQgcQVideoSink* self)
244{
245 new (&self->state) PrivState();
246 gst_video_info_init(&self->state.video_info);
247 // sync=FALSE: drone video is "as fast as decoded"; GstBaseSink clock-sync would
248 // stall on live RTSP. async=FALSE skips preroll wait so caps changes don't stall.
249 gst_base_sink_set_sync(GST_BASE_SINK(self), FALSE);
250 gst_base_sink_set_async_enabled(GST_BASE_SINK(self), FALSE);
251 // Don't retain the last buffer: it would pin an upstream pool slot for the stream's lifetime.
252 gst_base_sink_set_last_sample_enabled(GST_BASE_SINK(self), FALSE);
253}
254
255// GstVideoSink shows a preroll buffer and then renders the same buffer, so the first buffer after each preroll would
256// be mapped and delivered twice. QGC drives pipelines straight to PLAYING, where render follows preroll at once, so
257// the preroll frame adds nothing. show-preroll-frame is a construct property: override it once construction is done.
258static void gst_qgc_q_video_sink_constructed(GObject* obj)
259{
260 G_OBJECT_CLASS(gst_qgc_q_video_sink_parent_class)->constructed(obj);
261 g_object_set(obj, "show-preroll-frame", FALSE, nullptr);
262}
263
264static void gst_qgc_q_video_sink_finalize(GObject* obj)
265{
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);
271}
272
273static void gst_qgc_q_video_sink_set_property(GObject* obj, guint id, const GValue* val, GParamSpec* pspec)
274{
275 GstQgcQVideoSink* self = GST_QGC_Q_VIDEO_SINK(obj);
276 PrivState* p = priv_of(self);
277 if (id == PROP_QVIDEOSINK) {
278 p->delivery.setSink(static_cast<QVideoSink*>(g_value_get_pointer(val)));
279 return;
280 }
281 GST_OBJECT_LOCK(self);
282 switch (id) {
283 case PROP_ACTIVE:
284 p->active.store(g_value_get_boolean(val), std::memory_order_relaxed);
285 break;
287 p->gpu_zerocopy = g_value_get_boolean(val);
288 break;
289 default:
290 G_OBJECT_WARN_INVALID_PROPERTY_ID(obj, id, pspec);
291 break;
292 }
293 GST_OBJECT_UNLOCK(self);
294}
295
296static void gst_qgc_q_video_sink_get_property(GObject* obj, guint id, GValue* val, GParamSpec* pspec)
297{
298 GstQgcQVideoSink* self = GST_QGC_Q_VIDEO_SINK(obj);
299 GST_OBJECT_LOCK(self);
300 switch (id) {
301 case PROP_QVIDEOSINK:
302 g_value_set_pointer(val, priv_of(self)->delivery.sink());
303 break;
304 case PROP_ACTIVE:
305 g_value_set_boolean(val, priv_of(self)->active.load(std::memory_order_relaxed));
306 break;
308 g_value_set_boolean(val, priv_of(self)->gpu_zerocopy);
309 break;
311 g_value_set_uint64(val, priv_of(self)->counters.input());
312 break;
314 g_value_set_uint64(val, priv_of(self)->counters.dropped());
315 break;
317 g_value_set_uint64(val, priv_of(self)->counters.delivered());
318 break;
319 case PROP_FRAME_STATS:
320 g_value_take_boxed(val, priv_of(self)->counters.frameStats());
321 break;
323 g_value_set_int(val, priv_of(self)->picture_width.load(std::memory_order_relaxed));
324 break;
326 g_value_set_int(val, priv_of(self)->picture_height.load(std::memory_order_relaxed));
327 break;
328 default:
329 G_OBJECT_WARN_INVALID_PROPERTY_ID(obj, id, pspec);
330 break;
331 }
332 GST_OBJECT_UNLOCK(self);
333}
334
335static GstCaps* gst_qgc_q_video_sink_get_caps(GstBaseSink* bsink, GstCaps* filter)
336{
337 GstCaps* caps = offered_caps(GST_QGC_Q_VIDEO_SINK(bsink));
338 if (filter) {
339 GstCaps* const filtered = gst_caps_intersect_full(filter, caps, GST_CAPS_INTERSECT_FIRST);
340 gst_caps_unref(caps);
341 caps = filtered;
342 }
343 return caps;
344}
345
346static gboolean gst_qgc_q_video_sink_set_caps(GstBaseSink* bsink, GstCaps* caps)
347{
348 GstQgcQVideoSink* self = GST_QGC_Q_VIDEO_SINK(bsink);
349 PrivState* p = priv_of(self);
350
351 GstVideoInfo parsedInfo = {};
352 if (!GstHw::dmaDrmAwareVideoInfo(caps, &parsedInfo)) {
353 qCWarning(GstQgcQVideoSinkLog) << "set_caps: failed to parse video info from caps";
354 return FALSE;
355 }
356
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));
361 return FALSE;
362 }
363
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;
368 return FALSE;
369 }
370
371 QVideoFrameFormat fmt(QSize(w, h), pixelFormat);
372 applyColorimetry(fmt, parsedInfo, caps);
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));
377 }
378
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);
386 // Hold the negotiated caps verbatim: rebuilding from video_info drops DRM modifiers and other
387 // negotiated fields the downstream frame mapping relies on.
388 p->cached_caps = gst_caps_ref(caps);
389 p->gpu_caps = caps_carry_gpu_memory(caps);
390 p->path_session.startEpoch();
391
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);
395 return TRUE;
396}
397
398static GstFlowReturn gst_qgc_q_video_sink_show_frame(GstVideoSink* vsink, GstBuffer* buf)
399{
400 GstQgcQVideoSink* self = GST_QGC_Q_VIDEO_SINK(vsink);
401 PrivState* p = priv_of(self);
402
403 p->counters.noteInput();
404 const GstQgc::SinkCapsPolicy policy = reconfigure_on_policy_change(self);
405
406 if (!p->cached_caps) {
407 // Should never happen — GstBaseSink calls set_caps before show_frame.
408 return GST_FLOW_NOT_NEGOTIATED;
409 }
410 if (!p->active.load(std::memory_order_relaxed)) {
411 p->counters.noteDropped();
412 return GST_FLOW_OK; // drop silently — controller drives the active flag
413 }
414
416 if (!snapshot_sink(self, hwCtx)) {
417 p->counters.noteDropped();
418 return GST_FLOW_OK; // no destination yet; drop
419 }
420 hwCtx.dmaBufImporter = policy.dmaBufDisplay;
421 // Software-decoded frames skip GPU selection. Caps alone can't tell: GPU memory also arrives under plain
422 // video/x-raw (vtdec's CoreVideo/IOSurface buffers, V4L2 dmabuf export), so frames in other memory still try it.
423 hwCtx.gpuEnabled = hwCtx.gpuEnabled && (p->gpu_caps || !nothing_to_import(buf));
424
425 if (const FrameGeometry geometry = frameGeometry(buf, p->video_info); geometry != p->frame_geometry) {
426 p->frame_geometry = geometry;
427 p->frame_format = withFrameGeometry(p->format, 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);
430 }
431 MappedFrame mapped = mapSampleToFrame(buf, p->cached_caps, p->video_info, p->frame_format, hwCtx,
432 p->pinned_cpu_frames, p->path_session.pathCache());
433 if (!mapped.frame.isValid()) {
434 p->counters.noteDropped();
435 if (p->path_session.onMapFailed(mapped, p->counters) == GstQgc::PathSession::Verdict::Error) {
436 const quint64 failures = p->path_session.consecutiveMapFailures();
437 const char* const format = gst_video_format_to_string(GST_VIDEO_INFO_FORMAT(&p->video_info));
438 // Without an element error upstream reports only a generic "Internal data stream error".
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;
443 }
444 return GST_FLOW_OK; // drop transient failure, keep the stream alive
445 }
446 p->path_session.onMapped();
447
448 applyOrientationAndTiming(mapped.frame, buf, p->stream_orientation.load(std::memory_order_relaxed));
449 applyFlips(mapped.frame, p->frame_geometry);
450
451 const QSize frameSize = mapped.frame.size();
452 const GstQgc::FrameDelivery::Result delivery = p->delivery.deliver(std::move(mapped.frame));
453 if (!delivery.delivered) {
454 p->counters.noteDropped();
455 return GST_FLOW_OK; // QVideoSink unbound while mapping
456 }
457 const quint64 delivered = p->counters.noteDelivered(mapped.gpuPath, delivery.superseded);
458 p->path_session.onDelivered(mapped, p->counters);
459
460 if (delivered == 1) {
461 qCInfo(GstQgcQVideoSinkLog).noquote()
462 << "first frame delivered via" << GstHw::toString(mapped.gpuPath) << "path"
463 << QStringLiteral("%1x%2").arg(frameSize.width()).arg(frameSize.height());
464 } else if ((delivered % 300) == 0) {
465 qCDebug(GstQgcQVideoSinkLog).noquote()
466 << "frame flow:" << GstHw::toString(mapped.gpuPath) << "delivered=" << delivered
467 << "input=" << p->counters.input() << "dropped=" << p->counters.dropped()
468 << "cpuFrames=" << p->counters.pathFrames(HwVideoBufferPath::None);
469 }
470 return GST_FLOW_OK;
471}
472
473// Tracks the stream's orientation tag and releases an undelivered frame on flush.
474static gboolean gst_qgc_q_video_sink_event(GstBaseSink* bsink, GstEvent* event)
475{
476 GstQgcQVideoSink* self = GST_QGC_Q_VIDEO_SINK(bsink);
477 switch (GST_EVENT_TYPE(event)) {
478 case GST_EVENT_TAG: {
479 // A camera mounted sideways tags the stream (e.g. "rotate-90") instead of rotating every frame.
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);
485 }
486 break;
487 }
488 case GST_EVENT_FLUSH_START:
489 priv_of(self)->delivery.dropPending();
490 break;
491 case GST_EVENT_STREAM_START:
492 // A new stream starts untagged; its tags follow this event.
493 priv_of(self)->stream_orientation.store(GST_VIDEO_ORIENTATION_IDENTITY, std::memory_order_relaxed);
494 break;
495 default:
496 break;
497 }
498 return GST_BASE_SINK_CLASS(gst_qgc_q_video_sink_parent_class)->event(bsink, event);
499}
500
501// NULL->READY: build the GPU context from gpu-zerocopy, so the element maps GPU memory without any controller glue.
502static gboolean gst_qgc_q_video_sink_start(GstBaseSink* bsink)
503{
504 GstQgcQVideoSink* self = GST_QGC_Q_VIDEO_SINK(bsink);
505 const HwVideoBufferContext hwContext = HwBuffers::makeAdapterContext(priv_of(self)->gpu_zerocopy);
506 GST_OBJECT_LOCK(self);
507 priv_of(self)->hw_context = hwContext;
508 GST_OBJECT_UNLOCK(self);
509
510 GstBaseSinkClass* parentClass = GST_BASE_SINK_CLASS(gst_qgc_q_video_sink_parent_class);
511 return parentClass->start ? parentClass->start(bsink) : TRUE;
512}
513
514// READY->NULL: streaming has stopped, so drop all negotiated and per-stream state; a restart renegotiates from scratch
515// and no undelivered frame keeps a decoder buffer alive.
516static gboolean gst_qgc_q_video_sink_stop(GstBaseSink* bsink)
517{
518 GstQgcQVideoSink* self = GST_QGC_Q_VIDEO_SINK(bsink);
519 PrivState* p = priv_of(self);
520 gst_clear_caps(&p->cached_caps);
521 p->gpu_caps = false;
522 p->path_session.stop();
523 p->stream_orientation.store(GST_VIDEO_ORIENTATION_IDENTITY, std::memory_order_relaxed);
524 p->delivery.dropPending();
525
526 GstBaseSinkClass* parentClass = GST_BASE_SINK_CLASS(gst_qgc_q_video_sink_parent_class);
527 return parentClass->stop ? parentClass->stop(bsink) : TRUE;
528}
529
530// Add qgcqvideosink's consumed metas + min-buffer pool hint, then chain so GstBaseSink's default
531// allocation bookkeeping still runs. A query without video caps fails, as in upstream's sinks.
532static gboolean gst_qgc_q_video_sink_propose_allocation(GstBaseSink* bsink, GstQuery* query)
533{
535 return FALSE;
536 }
537 // GstBaseSink/GstVideoSink install no default propose_allocation vmethod, so the parent pointer
538 // is NULL for a direct subclass; chaining unconditionally would call 0x0 on the first ALLOCATION query.
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);
542 }
543 return TRUE;
544}
545
546// Answer CONTEXT (gst.gl.GLDisplay/app_context, Vulkan, D3D devices) synchronously so upstream GPU elements share Qt's
547// RHI device; the bus NEED_CONTEXT fallback races state changes. ALLOCATION reaches propose_allocation via the parent.
548static gboolean gst_qgc_q_video_sink_query(GstBaseSink* bsink, GstQuery* query)
549{
550 if ((GST_QUERY_TYPE(query) == GST_QUERY_CONTEXT) &&
551 HwBuffers::answerSinkBinContextQuery(query, GST_ELEMENT(bsink))) {
552 return TRUE;
553 }
554 if (GST_QUERY_TYPE(query) == GST_QUERY_ACCEPT_CAPS) {
555 // GstBaseSink wants a subset of get_caps, which rejects caps without a pixel-aspect-ratio (square pixels).
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);
561 return TRUE;
562 }
563 return GST_BASE_SINK_CLASS(gst_qgc_q_video_sink_parent_class)->query(bsink, query);
564}
565
566static void gst_qgc_q_video_sink_class_init(GstQgcQVideoSinkClass* klass)
567{
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);
572
573 gobject_class->set_property = gst_qgc_q_video_sink_set_property;
574 gobject_class->get_property = gst_qgc_q_video_sink_get_property;
575 gobject_class->constructed = gst_qgc_q_video_sink_constructed;
576 gobject_class->finalize = gst_qgc_q_video_sink_finalize;
577
578 g_object_class_install_property(
579 gobject_class, PROP_QVIDEOSINK,
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)));
583
584 g_object_class_install_property(
585 gobject_class, PROP_ACTIVE,
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)));
589
590 g_object_class_install_property(
591 gobject_class, PROP_GPU_ZEROCOPY,
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.",
595 FALSE,
596 (GParamFlags) (G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS)));
597
598 g_object_class_install_property(
599 gobject_class, PROP_FRAMES_INPUT,
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)));
602
603 g_object_class_install_property(
604 gobject_class, PROP_FRAMES_DROPPED,
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)));
609
610 g_object_class_install_property(
611 gobject_class, PROP_FRAMES_DELIVERED,
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)));
617
618 // Not "stats": that is GstBaseSink's own property (average-rate, dropped, rendered), which generic tools read.
619 g_object_class_install_property(
620 gobject_class, PROP_FRAME_STATS,
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)));
630
631 // A frame's viewport is smaller where a transformation meta leaves out the padding of a squeezed texture.
632 g_object_class_install_property(
633 gobject_class, PROP_PICTURE_WIDTH,
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(
639 gobject_class, PROP_PICTURE_HEIGHT,
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)));
642
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);
647
648 basesink_class->get_caps = gst_qgc_q_video_sink_get_caps;
649 basesink_class->set_caps = gst_qgc_q_video_sink_set_caps;
650 basesink_class->event = gst_qgc_q_video_sink_event;
651 basesink_class->start = gst_qgc_q_video_sink_start;
652 basesink_class->stop = gst_qgc_q_video_sink_stop;
653 basesink_class->propose_allocation = gst_qgc_q_video_sink_propose_allocation;
654 basesink_class->query = gst_qgc_q_video_sink_query;
655 videosink_class->show_frame = gst_qgc_q_video_sink_show_frame;
656}
657
658namespace GstQgc {
659
660void configureSinkCaps(GstElement* sink, GpuBinMode gpuBin, bool squarePixels)
661{
662 if (!sink || !GST_IS_QGC_Q_VIDEO_SINK(sink)) {
663 return;
664 }
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);
671}
672
673} // namespace GstQgc
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)
@ PROP_FRAMES_INPUT
@ PROP_FRAMES_DELIVERED
@ PROP_FRAME_STATS
@ PROP_QVIDEOSINK
@ PROP_GPU_ZEROCOPY
@ PROP_FRAMES_DROPPED
@ PROP_ACTIVE
@ PROP_PICTURE_HEIGHT
@ PROP_PICTURE_WIDTH
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
Definition GstHwTypes.h:37
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
Definition HwBuffers.cc:247
void * dmaBufImportDisplay() noexcept
Definition HwBuffers.cc:206
bool answerSinkBinContextQuery(GstQuery *query, GstElement *sink) noexcept
Definition HwBuffers.cc:261
HwVideoBufferContext makeAdapterContext(bool gpuEnabled) noexcept
Definition HwBuffers.cc:182
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.
Definition GstQgcCaps.h:15
bool d3d11OpensD3D12
Qt's Direct3D 11 device opens a Direct3D 12 device's resources (HwBuffers::d3d11OpensD3D12()).
Definition GstQgcCaps.h:24
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.
QVideoFrame frame
bool noCpuLayout
Dropped instead of read as linear rows, which would show it scrambled.