QGroundControl
Ground Control Station for MAVLink Drones
Loading...
Searching...
No Matches
GstQgcFrameMap.cc
Go to the documentation of this file.
1#include "GstQgcFrameMap.h"
2
3#include <algorithm>
4#include <atomic>
5#include <cmath>
6#include <gst/gst.h>
7#include <gst/video/gstvideoaffinetransformationmeta.h>
8#include <gst/video/gstvideometa.h>
9#include <gst/video/video-hdr.h>
10#include <utility>
11
12#include <QtCore/QtNumeric>
13#include <QtMultimedia/QAbstractVideoBuffer>
14#include <QtMultimedia/QVideoFrame>
15
16#include "GstQgcVideoFormats.h"
19#include "QGCLoggingCategory.h"
20
21#if defined(QGC_HAS_ANY_GPU_PATH)
22#include <private/qhwvideobuffer_p.h>
23#endif
24
25QGC_LOGGING_CATEGORY(GstQgcFrameMapLog, "Video.GStreamer.FrameMap")
26
27QVideoFrameFormat::ColorSpace toQtColorSpace(GstVideoColorMatrix matrix)
28{
29 switch (matrix) {
30 case GST_VIDEO_COLOR_MATRIX_BT601:
31 return QVideoFrameFormat::ColorSpace_BT601;
32 case GST_VIDEO_COLOR_MATRIX_BT709:
33 return QVideoFrameFormat::ColorSpace_BT709;
34 case GST_VIDEO_COLOR_MATRIX_BT2020:
35 return QVideoFrameFormat::ColorSpace_BT2020;
36 case GST_VIDEO_COLOR_MATRIX_SMPTE240M:
37 // Matches Qt qgst.cpp convention (shared D65 white point), not full colorimetric equivalence.
38 return QVideoFrameFormat::ColorSpace_AdobeRgb;
39 // Qt groups FCC with UNKNOWN/RGB and leaves it Undefined (qgst.cpp); the
40 // resolution heuristic below then picks BT601/BT709.
41 default:
42 return QVideoFrameFormat::ColorSpace_Undefined;
43 }
44}
45
46QVideoFrameFormat::ColorTransfer toQtColorTransfer(GstVideoTransferFunction transfer)
47{
48 // Mirrors Qt's qgst.cpp QGstCaps::formatAndVideoInfo() (cross-checked Qt 6.12.0).
49 switch (transfer) {
50 case GST_VIDEO_TRANSFER_BT601:
51 return QVideoFrameFormat::ColorTransfer_BT601;
52 case GST_VIDEO_TRANSFER_BT2020_10:
53 case GST_VIDEO_TRANSFER_BT2020_12:
54 case GST_VIDEO_TRANSFER_BT709:
55 return QVideoFrameFormat::ColorTransfer_BT709;
56 case GST_VIDEO_TRANSFER_GAMMA20:
57 return QVideoFrameFormat::ColorTransfer_BT709; // best fit per Qt
58 // SMPTE 240M uses a ~2.2 power curve, not BT.709 piecewise-linear; Qt groups it with Gamma22.
59 case GST_VIDEO_TRANSFER_SMPTE240M:
60 case GST_VIDEO_TRANSFER_GAMMA22:
61 case GST_VIDEO_TRANSFER_SRGB:
62 case GST_VIDEO_TRANSFER_ADOBERGB:
63 return QVideoFrameFormat::ColorTransfer_Gamma22;
64 case GST_VIDEO_TRANSFER_GAMMA18:
65 return QVideoFrameFormat::ColorTransfer_BT709; // matches Qt qgst.cpp GAMMA18 mapping
66 case GST_VIDEO_TRANSFER_GAMMA28:
67 return QVideoFrameFormat::ColorTransfer_Gamma28;
68 case GST_VIDEO_TRANSFER_GAMMA10:
69 return QVideoFrameFormat::ColorTransfer_Linear;
70 case GST_VIDEO_TRANSFER_SMPTE2084:
71 return QVideoFrameFormat::ColorTransfer_ST2084;
72 case GST_VIDEO_TRANSFER_ARIB_STD_B67:
73 return QVideoFrameFormat::ColorTransfer_STD_B67;
74 // GST_VIDEO_TRANSFER_LOG100 / LOG316 have no Qt equivalent — leave as Unknown
75 default:
76 return QVideoFrameFormat::ColorTransfer_Unknown;
77 }
78}
79
80QVideoFrameFormat::PixelFormat toQtPixelFormat(GstVideoFormat fmt)
81{
82 for (const auto& e : GstQgc::kVideoFormatTable) {
83 if (e.gst == fmt) {
84 return e.qt;
85 }
86 }
87 return QVideoFrameFormat::Format_Invalid;
88}
89
90QVideoFrameFormat::ColorRange toQtColorRange(GstVideoColorRange range)
91{
92 switch (range) {
93 case GST_VIDEO_COLOR_RANGE_0_255:
94 return QVideoFrameFormat::ColorRange_Full;
95 case GST_VIDEO_COLOR_RANGE_16_235:
96 return QVideoFrameFormat::ColorRange_Video;
97 default:
98 return QVideoFrameFormat::ColorRange_Unknown;
99 }
100}
101
102void applyOrientationToFrame(QVideoFrame& frame, GstVideoOrientationMethod method)
103{
104 struct Orientation
105 {
106 GstVideoOrientationMethod method;
107 QtVideo::Rotation rotation;
108 bool mirrored;
109 };
110
111 static constexpr Orientation kOrientations[] = {
112 {GST_VIDEO_ORIENTATION_IDENTITY, QtVideo::Rotation::None, false},
113 {GST_VIDEO_ORIENTATION_90R, QtVideo::Rotation::Clockwise90, false},
114 {GST_VIDEO_ORIENTATION_180, QtVideo::Rotation::Clockwise180, false},
115 {GST_VIDEO_ORIENTATION_90L, QtVideo::Rotation::Clockwise270, false},
116 {GST_VIDEO_ORIENTATION_HORIZ, QtVideo::Rotation::None, true},
117 {GST_VIDEO_ORIENTATION_VERT, QtVideo::Rotation::Clockwise180, true},
118 {GST_VIDEO_ORIENTATION_UL_LR, QtVideo::Rotation::Clockwise90, true},
119 {GST_VIDEO_ORIENTATION_UR_LL, QtVideo::Rotation::Clockwise270, true},
120 };
121 const Orientation* known = std::ranges::find(kOrientations, method, &Orientation::method);
122 if (known == std::end(kOrientations)) {
123 static std::atomic<bool> s_warnedUnhandled{false};
124 if (!s_warnedUnhandled.exchange(true, std::memory_order_relaxed)) {
125 qCWarning(GstQgcFrameMapLog) << "Unhandled GstVideoOrientationMethod" << method << "— treating as identity";
126 }
127 known = std::begin(kOrientations);
128 }
129 frame.setRotation(known->rotation);
130 frame.setMirrored(known->mirrored);
131}
132
133void applyOrientationAndTiming(QVideoFrame& frame, GstBuffer* buffer, int streamOrientation)
134{
135 if (streamOrientation != static_cast<int>(GST_VIDEO_ORIENTATION_IDENTITY)) {
136 applyOrientationToFrame(frame, static_cast<GstVideoOrientationMethod>(streamOrientation));
137 }
138 if (GST_BUFFER_PTS_IS_VALID(buffer)) {
139 // GstClockTime is ns; QVideoFrame timestamps are µs.
140 frame.setStartTime(GST_BUFFER_PTS(buffer) / GST_USECOND);
141 if (GST_BUFFER_DURATION_IS_VALID(buffer)) {
142 frame.setEndTime((GST_BUFFER_PTS(buffer) + GST_BUFFER_DURATION(buffer)) / GST_USECOND);
143 }
144 }
145}
146
147void applyColorimetry(QVideoFrameFormat& format, const GstVideoInfo& info, GstCaps* caps)
148{
149 const GstVideoColorimetry& colorimetry = GST_VIDEO_INFO_COLORIMETRY(&info);
150 QVideoFrameFormat::ColorSpace colorSpace = toQtColorSpace(colorimetry.matrix);
151 // Live RTSP sources often omit colorimetry caps; match Qt's renderer fallback
152 // (qvideotexturehelper.cpp): height > 576 is HD/BT.709, otherwise SD/BT.601.
153 if (colorSpace == QVideoFrameFormat::ColorSpace_Undefined) {
154 const int height = GST_VIDEO_INFO_HEIGHT(&info);
155 if (height > 0) {
156 colorSpace = (height > 576) ? QVideoFrameFormat::ColorSpace_BT709 : QVideoFrameFormat::ColorSpace_BT601;
157 }
158 }
159 format.setColorSpace(colorSpace);
160 format.setColorTransfer(toQtColorTransfer(colorimetry.transfer));
161 QVideoFrameFormat::ColorRange range = toQtColorRange(colorimetry.range);
162 // H.264/H.265 omit VUI range but encode limited per spec — else Qt skips its limited->full offset.
163 // Only infer for a known YUV matrix: an UNKNOWN matrix tells us nothing, and RGB is always full-range.
164 const bool knownYuvMatrix =
165 (colorimetry.matrix == GST_VIDEO_COLOR_MATRIX_BT601) || (colorimetry.matrix == GST_VIDEO_COLOR_MATRIX_BT709) ||
166 (colorimetry.matrix == GST_VIDEO_COLOR_MATRIX_BT2020) ||
167 (colorimetry.matrix == GST_VIDEO_COLOR_MATRIX_SMPTE240M) || (colorimetry.matrix == GST_VIDEO_COLOR_MATRIX_FCC);
168 if (range == QVideoFrameFormat::ColorRange_Unknown && knownYuvMatrix) {
169 range = QVideoFrameFormat::ColorRange_Video;
170 }
171 format.setColorRange(range);
172
173 // Prefer MaxCLL (tighter tone-mapping target) over mastering-display max-luminance.
174 GstVideoContentLightLevel cll;
175 bool clipApplied = false;
176 if (caps && gst_video_content_light_level_from_caps(&cll, caps) && cll.max_content_light_level > 0) {
177 format.setMaxLuminance(static_cast<float>(cll.max_content_light_level));
178 clipApplied = true;
179 }
180 if (!clipApplied) {
181 GstVideoMasteringDisplayInfo masteringInfo;
182 if (caps && gst_video_mastering_display_info_from_caps(&masteringInfo, caps)) {
183 // GstVideoMasteringDisplayColorVolume max_luma is in 0.0001 cd/m².
184 const double maxLuminance = static_cast<double>(masteringInfo.max_display_mastering_luminance) / 10000.0;
185 if (maxLuminance > 0.0) {
186 format.setMaxLuminance(static_cast<float>(maxLuminance));
187 }
188 }
189 }
190}
191
192namespace {
193
198bool applyAffineMatrix(FrameGeometry& geometry, const gfloat* matrix)
199{
200 if (!qFuzzyIsNull(matrix[1]) || !qFuzzyIsNull(matrix[4]) || !qFuzzyIsNull(matrix[3]) || !qFuzzyIsNull(matrix[7]) ||
201 !qFuzzyCompare(matrix[15], 1.0F) || qFuzzyIsNull(matrix[0]) || qFuzzyIsNull(matrix[5])) {
202 return false;
203 }
204 const double scaleX = matrix[0];
205 const double scaleY = matrix[5];
206 const double ax = 1.0 / scaleX;
207 const double bx = -matrix[12] / scaleX;
208 const double ay = 1.0 / scaleY;
209 const double by = 1.0 - ((1.0 - matrix[13]) / scaleY);
210
211 // Whole pixels, outwards: SurfaceTexture's matrix already keeps half a texel or more off the crop's edges. The
212 // margin absorbs rounding in the matrix.
213 constexpr double kMargin = 1e-3;
214 const QRect picture = geometry.picture;
215 const auto span = [](double from, double to, int origin, int extent) {
216 const int first = origin + static_cast<int>(std::floor((std::min(from, to) * extent) + kMargin));
217 const int end = origin + static_cast<int>(std::ceil((std::max(from, to) * extent) - kMargin));
218 return std::pair(std::clamp(first, origin, origin + extent), std::clamp(end, origin, origin + extent));
219 };
220 const auto [left, right] = span(bx, bx + ax, picture.x(), picture.width());
221 const auto [top, bottom] = span(by, by + ay, picture.y(), picture.height());
222 if ((right <= left) || (bottom <= top)) {
223 return false;
224 }
225 geometry.picture = QRect(left, top, right - left, bottom - top);
226 geometry.flipHorizontally = ax < 0.0;
227 geometry.flipVertically = ay < 0.0;
228 return true;
229}
230
231} // namespace
232
233FrameGeometry frameGeometry(GstBuffer* buffer, const GstVideoInfo& capsInfo)
234{
235 const QSize capsSize(GST_VIDEO_INFO_WIDTH(&capsInfo), GST_VIDEO_INFO_HEIGHT(&capsInfo));
236 FrameGeometry geometry{.frameSize = capsSize, .picture = QRect(QPoint(0, 0), capsSize), .pictureSize = capsSize};
237 // A meta smaller than the caps is no frame gst_video_frame_map() maps: left to fail there.
238 if (const GstVideoMeta* const meta = gst_buffer_get_video_meta(buffer);
239 meta && (meta->width >= static_cast<guint>(capsSize.width())) &&
240 (meta->height >= static_cast<guint>(capsSize.height()))) {
241 geometry.frameSize = QSize(static_cast<int>(meta->width), static_cast<int>(meta->height));
242 }
243 if (const GstVideoCropMeta* const crop = gst_buffer_get_video_crop_meta(buffer)) {
244 geometry.picture = QRect(static_cast<int>(crop->x), static_cast<int>(crop->y), static_cast<int>(crop->width),
245 static_cast<int>(crop->height));
246 geometry.pictureSize = geometry.picture.size();
247 }
248 if (const GstVideoAffineTransformationMeta* const affine = gst_buffer_get_video_affine_transformation_meta(buffer);
249 affine && !applyAffineMatrix(geometry, affine->matrix)) {
250 static std::atomic<bool> s_warnedUnapplied{false};
251 if (!s_warnedUnapplied.exchange(true, std::memory_order_relaxed)) {
252 qCWarning(GstQgcFrameMapLog) << "GstVideoAffineTransformationMeta is no viewport with flips (a scale, a "
253 "translation, mirroring) — not applied";
254 }
255 }
256 return geometry;
257}
258
259void applyFlips(QVideoFrame& frame, const FrameGeometry& geometry)
260{
261 if (!geometry.flipHorizontally && !geometry.flipVertically) {
262 return;
263 }
264 // Qt turns a frame clockwise, then mirrors it left to right. A left-to-right flip ahead of a turn is the opposite
265 // turn, mirrored; a top-to-bottom flip is a left-to-right one after half a turn.
266 int degrees = static_cast<int>(frame.rotation());
267 bool mirrored = frame.mirrored();
268 if (geometry.flipHorizontally != geometry.flipVertically) {
269 degrees = (geometry.flipVertically ? 540 : 360) - degrees;
270 mirrored = !mirrored;
271 } else {
272 degrees += 180;
273 }
274 frame.setRotation(static_cast<QtVideo::Rotation>(degrees % 360));
275 frame.setMirrored(mirrored);
276}
277
278// QQuickVideoOutput computes sample rect as viewport/frameSize (QQuickVideoOutput::updateGeometry());
279// externalTextureMatrix is only used for Format_SamplerExternalOES, so can't crop standard formats.
280QVideoFrameFormat withFrameGeometry(QVideoFrameFormat format, const FrameGeometry& geometry)
281{
282 // Resets the viewport to the whole frame.
283 format.setFrameSize(geometry.frameSize);
284 format.setViewport(geometry.picture);
285 return format;
286}
287
288MappedFrame mapSampleToFrame(GstBuffer* buffer, GstCaps* caps, const GstVideoInfo& info,
289 const QVideoFrameFormat& format, [[maybe_unused]] const HwVideoBufferContext& hwContext,
290 const CpuVideoFramePool::PinnedFrameCounter& pinnedCpuFrames,
291 [[maybe_unused]] HwResolvedPathCache* pathCache)
292{
293 MappedFrame out;
294#if defined(QGC_HAS_ANY_GPU_PATH)
296 if (hwContext.gpuEnabled) {
297 if (auto hwBuf = makeHwVideoBuffer(buffer, caps, info, format, hwContext, matchedPath, pathCache)) {
298 out.frame = QVideoFrame(std::move(hwBuf));
299 out.gpuPath = matchedPath;
300 return out;
301 }
302 // HW selection failed though GPU was requested: signal the demotion. show_frame owns the
303 // once-per-epoch latch and the counters.
304 out.demoted = true;
305 }
306#endif
307 if (!GstHw::hasCpuLayout(caps)) {
308 out.noCpuLayout = true;
309 return out;
310 }
311 if (auto cpuBuf = CpuVideoFramePool::wrapZeroCopy(buffer, info, format, pinnedCpuFrames)) {
312 out.frame = QVideoFrame(std::move(cpuBuf));
313 } else {
314 out.frame = CpuVideoFramePool::copyFromBuffer(buffer, info, format);
315 }
316 return out;
317}
HwVideoBufferPath
GPU zero-copy path a frame is imported through; None means the frame takes the CPU path.
Definition GstHwTypes.h:7
std::unique_ptr< QHwVideoBuffer > makeHwVideoBuffer(GstBuffer *buffer, GstCaps *caps, const GstVideoInfo &info, QVideoFrameFormat format, const HwVideoBufferContext &context, HwVideoBufferPath &matchedPath, HwResolvedPathCache *cache)
QVideoFrameFormat::PixelFormat toQtPixelFormat(GstVideoFormat fmt)
QVideoFrameFormat::ColorTransfer toQtColorTransfer(GstVideoTransferFunction transfer)
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.
QVideoFrameFormat::ColorSpace toQtColorSpace(GstVideoColorMatrix matrix)
Sample-to-frame helpers for qgcqvideosink's show_frame; pure functions, streaming-thread safe.
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)
void applyOrientationToFrame(QVideoFrame &frame, GstVideoOrientationMethod method)
Apply rotation + mirror flags derived from GstVideoOrientationMethod.
QVideoFrameFormat::ColorRange toQtColorRange(GstVideoColorRange range)
#define QGC_LOGGING_CATEGORY(name, categoryStr)
static std::unique_ptr< QAbstractVideoBuffer > wrapZeroCopy(GstBuffer *buffer, const GstVideoInfo &info, const QVideoFrameFormat &format, const PinnedFrameCounter &pinned)
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...
static QVideoFrame copyFromBuffer(GstBuffer *buffer, const GstVideoInfo &videoInfo, const QVideoFrameFormat &format)
bool hasCpuLayout(GstCaps *caps)
constexpr VideoFormatEntry kVideoFormatTable[]
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.