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
qvideoframeconverter.cpp
Go to the documentation of this file.
1// Copyright (C) 2022 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:critical reason:data-parser
4
11#include "qcachedvalue_p.h"
12
13#include <QtCore/qcoreapplication.h>
14#include <QtCore/qsize.h>
15#include <QtCore/qhash.h>
16#include <QtCore/qfile.h>
17#include <QtGui/qimage.h>
18#include <QtCore/qloggingcategory.h>
19
20#include <QtMultimedia/private/qaudio_qspan_support_p.h>
21#include <QtMultimedia/private/qmultimedia_ranges_p.h>
22#include <QtMultimedia/private/qvideotexturehelper_p.h>
23
24#include <rhi/qrhi.h>
25
26#ifdef Q_OS_DARWIN
27#include <QtCore/private/qcore_mac_p.h>
28#endif
29
31
32namespace ranges = QtMultimediaPrivate::ranges;
33
34Q_STATIC_LOGGING_CATEGORY(qLcVideoFrameConverter, "qt.multimedia.video.frameconverter")
35
36// clang-format off
37static constexpr float g_quad[] = {
38 // Rotation 0 CW
39 1.f, -1.f, 1.f, 1.f,
40 1.f, 1.f, 1.f, 0.f,
41 -1.f, -1.f, 0.f, 1.f,
42 -1.f, 1.f, 0.f, 0.f,
43 // Rotation 90 CW
44 1.f, -1.f, 1.f, 0.f,
45 1.f, 1.f, 0.f, 0.f,
46 -1.f, -1.f, 1.f, 1.f,
47 -1.f, 1.f, 0.f, 1.f,
48 // Rotation 180 CW
49 1.f, -1.f, 0.f, 0.f,
50 1.f, 1.f, 0.f, 1.f,
51 -1.f, -1.f, 1.f, 0.f,
52 -1.f, 1.f, 1.f, 1.f,
53 // Rotation 270 CW
54 1.f, -1.f, 0.f, 1.f,
55 1.f, 1.f, 1.f, 1.f,
56 -1.f, -1.f, 0.f, 0.f,
57 -1.f, 1.f, 1.f, 0.f,
58};
59// clang-format on
60
61static bool pixelFormatHasAlpha(QVideoFrameFormat::PixelFormat format)
62{
63 switch (format) {
64 case QVideoFrameFormat::Format_ARGB8888:
65 case QVideoFrameFormat::Format_ARGB8888_Premultiplied:
66 case QVideoFrameFormat::Format_BGRA8888:
67 case QVideoFrameFormat::Format_BGRA8888_Premultiplied:
68 case QVideoFrameFormat::Format_ABGR8888:
69 case QVideoFrameFormat::Format_RGBA8888:
70 case QVideoFrameFormat::Format_AYUV:
71 case QVideoFrameFormat::Format_AYUV_Premultiplied:
72 return true;
73 default:
74 return false;
75 }
76};
77
78static QShader ensureShader(const QString &name)
79{
80 static QCachedValueMap<QString, QShader> shaderCache;
81
82 return shaderCache.ensure(name, [&name]() {
83 QFile f(name);
84 return f.open(QIODevice::ReadOnly) ? QShader::fromSerialized(f.readAll()) : QShader();
85 });
86}
87
88static void rasterTransform(QImage &image, VideoTransformation transformation)
89{
90 QTransform t;
91 if (transformation.rotation != QtVideo::Rotation::None)
92 t.rotate(qreal(transformation.rotation));
93 if (transformation.mirroredHorizontallyAfterRotation)
94 t.scale(-1., 1);
95 if (!t.isIdentity())
96 image = image.transformed(t);
97}
98
99static void imageCleanupHandler(void *info)
100{
101 QByteArray *imageData = reinterpret_cast<QByteArray *>(info);
102 delete imageData;
103}
104
105static bool updateTextures(QRhi *rhi,
106 std::unique_ptr<QRhiBuffer> &uniformBuffer,
107 std::unique_ptr<QRhiSampler> &textureSampler,
108 std::unique_ptr<QRhiShaderResourceBindings> &shaderResourceBindings,
109 std::unique_ptr<QRhiGraphicsPipeline> &graphicsPipeline,
110 std::unique_ptr<QRhiRenderPassDescriptor> &renderPass,
111 QVideoFrame &frame,
112 const QVideoFrameTexturesUPtr &videoFrameTextures)
113{
114 auto format = frame.surfaceFormat();
115 auto pixelFormat = format.pixelFormat();
116
117 auto textureDesc = QVideoTextureHelper::textureDescription(pixelFormat);
118
119 QRhiShaderResourceBinding bindings[4];
120 auto *b = bindings;
121 *b++ = QRhiShaderResourceBinding::uniformBuffer(0, QRhiShaderResourceBinding::VertexStage | QRhiShaderResourceBinding::FragmentStage,
122 uniformBuffer.get());
123 for (int i = 0; i < textureDesc->nplanes; ++i)
124 *b++ = QRhiShaderResourceBinding::sampledTexture(i + 1, QRhiShaderResourceBinding::FragmentStage,
125 videoFrameTextures->texture(i), textureSampler.get());
126 shaderResourceBindings->setBindings(bindings, b);
127 if (!shaderResourceBindings->create()) {
128 qCDebug(qLcVideoFrameConverter)
129 << Q_FUNC_INFO << ": failed to create shader resource bindings";
130 return false;
131 }
132
133 graphicsPipeline.reset(rhi->newGraphicsPipeline());
134 graphicsPipeline->setTopology(QRhiGraphicsPipeline::TriangleStrip);
135
136 QShader vs = ensureShader(QVideoTextureHelper::vertexShaderFileName(format));
137 if (!vs.isValid())
138 return false;
139
140 QShader fs = ensureShader(QVideoTextureHelper::fragmentShaderFileName(format, rhi));
141 if (!fs.isValid())
142 return false;
143
144 graphicsPipeline->setShaderStages({
145 { QRhiShaderStage::Vertex, vs },
146 { QRhiShaderStage::Fragment, fs }
147 });
148
149 QRhiVertexInputLayout inputLayout;
150 inputLayout.setBindings({
151 { 4 * sizeof(float) }
152 });
153 inputLayout.setAttributes({
154 { 0, 0, QRhiVertexInputAttribute::Float2, 0 },
155 { 0, 1, QRhiVertexInputAttribute::Float2, 2 * sizeof(float) }
156 });
157
158 graphicsPipeline->setVertexInputLayout(inputLayout);
159 graphicsPipeline->setShaderResourceBindings(shaderResourceBindings.get());
160 graphicsPipeline->setRenderPassDescriptor(renderPass.get());
161 if (!graphicsPipeline->create()) {
162 qCDebug(qLcVideoFrameConverter) << Q_FUNC_INFO << ": failed to create graphics pipeline";
163 return false;
164 }
165
166 return true;
167}
168
169QSpan<const uchar> jpegDataFromMappedVideoFrame(const QVideoFrame &mappedFrame)
170{
171 Q_ASSERT(mappedFrame.isReadable());
172 Q_ASSERT(mappedFrame.pixelFormat() == QVideoFrameFormat::PixelFormat::Format_Jpeg);
173
174 QSpan<const uchar> jpegData{
175 mappedFrame.bits(0),
176 mappedFrame.mappedBytes(0),
177 };
178
179 using namespace QtMultimediaPrivate;
180
181 constexpr std::array<uchar, 2> soiMarker{ uchar(0xff), uchar(0xd8) };
182 if (!ranges::equal(take(jpegData, 2), soiMarker, std::equal_to<void>{})) {
183 qCDebug(qLcVideoFrameConverter)
184 << Q_FUNC_INFO << ": JPEG data does not start with SOI marker";
185 return {};
186 }
187
188 constexpr std::array<uchar, 2> eoiMarker{ uchar(0xff), uchar(0xd9) };
189
190 // some JPEG cameras contain extra data after the JPEG marker. If so, we drop it to make
191 // libjpeg happy.
192 if (!ranges::equal(jpegData.last(2), eoiMarker, std::equal_to<void>{})) {
193 qCDebug(qLcVideoFrameConverter)
194 << Q_FUNC_INFO << ": JPEG data does not end with EOI marker";
195
196 auto eoi_it = std::find_end(jpegData.begin(), jpegData.end(), std::begin(eoiMarker),
197 std::end(eoiMarker));
198 if (eoi_it == jpegData.end()) {
199 qCWarning(qLcVideoFrameConverter)
200 << Q_FUNC_INFO << ": JPEG data does not contain EOI marker";
201 return {};
202 };
203
204 const size_t newSize = std::distance(jpegData.begin(), eoi_it) + std::size(eoiMarker);
205 jpegData = jpegData.first(newSize);
206 }
207
208 return jpegData;
209}
210
211static QImage convertJPEG(const QVideoFrame &frame, const VideoTransformation &transform)
212{
213 QVideoFrame varFrame = frame;
214 if (!varFrame.map(QVideoFrame::ReadOnly)) {
215 qCDebug(qLcVideoFrameConverter) << Q_FUNC_INFO << ": frame mapping failed";
216 return {};
217 }
218
219 auto unmap = std::optional(QScopeGuard([&] {
220 varFrame.unmap();
221 }));
222
223 const QSpan<const uchar> jpegData = jpegDataFromMappedVideoFrame(varFrame);
224 if (jpegData.isEmpty())
225 return QImage{};
226
227 QImage image = QImage::fromData(jpegData, "JPG");
228 unmap = std::nullopt; // Release unmap guard
229 rasterTransform(image, transform);
230 return image;
231}
232
233static QImage convertCPU(const QVideoFrame &frame, const VideoTransformation &transform)
234{
235 VideoFrameConvertFunc convert = qConverterForFormat(frame.pixelFormat());
236 if (!convert) {
237 qCDebug(qLcVideoFrameConverter) << Q_FUNC_INFO << ": unsupported pixel format" << frame.pixelFormat();
238 return {};
239 } else {
240 QVideoFrame varFrame = frame;
241 if (!varFrame.map(QVideoFrame::ReadOnly)) {
242 qCDebug(qLcVideoFrameConverter) << Q_FUNC_INFO << ": frame mapping failed";
243 return {};
244 }
245 auto format = pixelFormatHasAlpha(varFrame.pixelFormat()) ? QImage::Format_ARGB32_Premultiplied : QImage::Format_RGB32;
246 QImage image = QImage(varFrame.width(), varFrame.height(), format);
247 convert(varFrame, image.bits());
248 varFrame.unmap();
249 rasterTransform(image, transform);
250 return image;
251 }
252}
253
254QImage qImageFromVideoFrame(const QVideoFrame &frame, bool forceCpu)
255{
256 // by default, surface transformation is applied, as full transformation is used for presentation only
257 return qImageFromVideoFrame(frame, qNormalizedSurfaceTransformation(frame.surfaceFormat()),
258 forceCpu);
259}
260
261QImage qImageFromVideoFrame(const QVideoFrame &frame, const VideoTransformation &transformation,
262 bool forceCpu)
263{
264#ifdef Q_OS_DARWIN
265 QMacAutoReleasePool releasePool;
266#endif
267
268 std::unique_ptr<QRhiRenderPassDescriptor> renderPass;
269 std::unique_ptr<QRhiBuffer> vertexBuffer;
270 std::unique_ptr<QRhiBuffer> uniformBuffer;
271 std::unique_ptr<QRhiTexture> targetTexture;
272 std::unique_ptr<QRhiTextureRenderTarget> renderTarget;
273 std::unique_ptr<QRhiSampler> textureSampler;
274 std::unique_ptr<QRhiShaderResourceBindings> shaderResourceBindings;
275 std::unique_ptr<QRhiGraphicsPipeline> graphicsPipeline;
276
277 if (frame.size().isEmpty() || frame.pixelFormat() == QVideoFrameFormat::Format_Invalid)
278 return {};
279
280 if (frame.pixelFormat() == QVideoFrameFormat::Format_Jpeg)
281 return convertJPEG(frame, transformation);
282
283 if (forceCpu) // For test purposes
284 return convertCPU(frame, transformation);
285
286 QRhi *rhi = nullptr;
287
288 if (QHwVideoBuffer *buffer = QVideoFramePrivate::hwBuffer(frame))
289 rhi = buffer->associatedCurrentThreadRhi();
290
291 if (!rhi) {
292 // TODO: if a case with more the one available preferred backends appears,
293 // e.g. vulkan vs opengl, then we should:
294 // 1. Implement QHwVideoBuffer::preferredRhiBackend
295 // 2. Implement a map backend=>rhi inside qEnsureThreadLocalRhi
296 rhi = qEnsureThreadLocalRhi(/*buffer->preferredRhiBackend()*/);
297 }
298
299 if (!rhi || rhi->isRecordingFrame())
300 return convertCPU(frame, transformation);
301
302 Q_ASSERT(rhi->thread()->isCurrentThread());
303
304 // Do conversion using shaders
305
306 const QSize frameSize = qRotatedFrameSize(frame.size(), frame.surfaceFormat().rotation());
307
308 vertexBuffer.reset(rhi->newBuffer(QRhiBuffer::Immutable, QRhiBuffer::VertexBuffer, sizeof(g_quad)));
309 if (!vertexBuffer->create()) {
310 qCDebug(qLcVideoFrameConverter) << "Failed to create vertex buffer. Using CPU conversion.";
311 return convertCPU(frame, transformation);
312 }
313
314 uniformBuffer.reset(rhi->newBuffer(QRhiBuffer::Dynamic, QRhiBuffer::UniformBuffer, sizeof(QVideoTextureHelper::UniformData)));
315 if (!uniformBuffer->create()) {
316 qCDebug(qLcVideoFrameConverter) << "Failed to create uniform buffer. Using CPU conversion.";
317 return convertCPU(frame, transformation);
318 }
319
320 textureSampler.reset(rhi->newSampler(QRhiSampler::Linear, QRhiSampler::Linear, QRhiSampler::None,
321 QRhiSampler::ClampToEdge, QRhiSampler::ClampToEdge));
322 if (!textureSampler->create()) {
323 qCDebug(qLcVideoFrameConverter)
324 << "Failed to create texture sampler. Using CPU conversion.";
325 return convertCPU(frame, transformation);
326 }
327
328 shaderResourceBindings.reset(rhi->newShaderResourceBindings());
329
330 targetTexture.reset(rhi->newTexture(QRhiTexture::RGBA8, frameSize, 1, QRhiTexture::RenderTarget));
331 if (!targetTexture->create()) {
332 qCDebug(qLcVideoFrameConverter) << "Failed to create target texture. Using CPU conversion.";
333 return convertCPU(frame, transformation);
334 }
335
336 renderTarget.reset(rhi->newTextureRenderTarget({ { targetTexture.get() } }));
337 renderPass.reset(renderTarget->newCompatibleRenderPassDescriptor());
338 renderTarget->setRenderPassDescriptor(renderPass.get());
339 if (!renderTarget->create()) {
340 qCDebug(qLcVideoFrameConverter) << "Failed to create render target. Using CPU conversion.";
341 return convertCPU(frame, transformation);
342 }
343
344 QRhiCommandBuffer *cb = nullptr;
345 QRhi::FrameOpResult r = rhi->beginOffscreenFrame(&cb);
346 if (r != QRhi::FrameOpSuccess) {
347 qCDebug(qLcVideoFrameConverter) << "Failed to set up offscreen frame. Using CPU conversion.";
348 return convertCPU(frame, transformation);
349 }
350
351 QRhiResourceUpdateBatch *rub = rhi->nextResourceUpdateBatch();
352 Q_ASSERT(rub);
353
354 rub->uploadStaticBuffer(vertexBuffer.get(), g_quad);
355
356 QVideoFrame frameTmp = frame;
357 QVideoFrameTexturesUPtr texturesTmp;
358 auto videoFrameTextures = QVideoTextureHelper::createTextures(frameTmp, *rhi, *rub, texturesTmp);
359 if (!videoFrameTextures) {
360 qCDebug(qLcVideoFrameConverter) << "Failed obtain textures. Using CPU conversion.";
361 return convertCPU(frame, transformation);
362 }
363
364 if (!updateTextures(rhi, uniformBuffer, textureSampler, shaderResourceBindings,
365 graphicsPipeline, renderPass, frameTmp, videoFrameTextures)) {
366 qCDebug(qLcVideoFrameConverter) << "Failed to update textures. Using CPU conversion.";
367 return convertCPU(frame, transformation);
368 }
369
370 float xScale = transformation.mirroredHorizontallyAfterRotation ? -1.0 : 1.0;
371 float yScale = 1.f;
372
373 if (rhi->isYUpInFramebuffer())
374 yScale = -yScale;
375
376 QMatrix4x4 transform;
377 transform.scale(xScale, yScale);
378
379 QByteArray uniformData(sizeof(QVideoTextureHelper::UniformData), Qt::Uninitialized);
380 QVideoTextureHelper::updateUniformData(&uniformData, rhi, frame.surfaceFormat(), frame,
381 transform, 1.f);
382 rub->updateDynamicBuffer(uniformBuffer.get(), 0, uniformData.size(), uniformData.constData());
383
384 cb->beginPass(renderTarget.get(), Qt::black, { 1.0f, 0 }, rub);
385 cb->setGraphicsPipeline(graphicsPipeline.get());
386
387 cb->setViewport({ 0, 0, float(frameSize.width()), float(frameSize.height()) });
388 cb->setShaderResources(shaderResourceBindings.get());
389
390 const quint32 vertexOffset = quint32(sizeof(float)) * 16 * transformation.rotationIndex();
391 const QRhiCommandBuffer::VertexInput vbufBinding(vertexBuffer.get(), vertexOffset);
392 cb->setVertexInput(0, 1, &vbufBinding);
393 cb->draw(4);
394
395 QRhiReadbackDescription readDesc(targetTexture.get());
396 QRhiReadbackResult readResult;
397 bool readCompleted = false;
398
399 readResult.completed = [&readCompleted] { readCompleted = true; };
400
401 rub = rhi->nextResourceUpdateBatch();
402 rub->readBackTexture(readDesc, &readResult);
403
404 cb->endPass(rub);
405
406 rhi->endOffscreenFrame();
407
408 if (!readCompleted) {
409 qCDebug(qLcVideoFrameConverter) << "Failed to read back texture. Using CPU conversion.";
410 return convertCPU(frame, transformation);
411 }
412
413 QByteArray *imageData = new QByteArray(readResult.data);
414
415 return QImage(reinterpret_cast<const uchar *>(imageData->constData()),
416 readResult.pixelSize.width(), readResult.pixelSize.height(),
417 QImage::Format_RGBA8888_Premultiplied, imageCleanupHandler, imageData);
418}
419
420QImage videoFramePlaneAsImage(QVideoFrame &frame, int plane, QImage::Format targetFormat,
421 QSize targetSize)
422{
423 if (plane >= frame.planeCount())
424 return {};
425
426 if (!frame.map(QVideoFrame::ReadOnly)) {
427 qWarning() << "Cannot map a video frame in ReadOnly mode!";
428 return {};
429 }
430
431 auto frameHandle = QVideoFramePrivate::handle(frame);
432
433 // With incrementing the reference counter, we share the mapped QVideoFrame
434 // with the target QImage. The function imageCleanupFunction is going to adopt
435 // the frameHandle by QVideoFrame and dereference it upon the destruction.
436 frameHandle->ref.ref();
437
438 auto imageCleanupFunction = [](void *data) {
439 QVideoFrame frame = reinterpret_cast<QVideoFramePrivate *>(data)->adoptThisByVideoFrame();
440 Q_ASSERT(frame.isMapped());
441 frame.unmap();
442 };
443
444 const auto bytesPerLine = frame.bytesPerLine(plane);
445 const auto height =
446 bytesPerLine ? qMin(targetSize.height(), frame.mappedBytes(plane) / bytesPerLine) : 0;
447
448 return QImage(reinterpret_cast<const uchar *>(frame.bits(plane)), targetSize.width(), height,
449 bytesPerLine, targetFormat, imageCleanupFunction, frameHandle);
450}
451
452QT_END_NAMESPACE
\inmodule QtGui
Definition qimage.h:38
\inmodule QtGuiPrivate \inheaderfile rhi/qrhi.h
Definition qrhi.h:787
\inmodule QtGuiPrivate \inheaderfile rhi/qrhi.h
Definition qrhi.h:441
\inmodule QtGuiPrivate \inheaderfile rhi/qrhi.h
Definition qrhi.h:323
\inmodule QtGui
Definition qshader.h:81
static QVideoFramePrivate * handle(QVideoFrame &frame)
Combined button and popup list for selecting options.
QT_BEGIN_NAMESPACE Q_STATIC_LOGGING_CATEGORY(lcSynthesizedIterableAccess, "qt.iterable.synthesized", QtWarningMsg)
QSpan< const uchar > jpegDataFromMappedVideoFrame(const QVideoFrame &mappedFrame)
static bool updateTextures(QRhi *rhi, std::unique_ptr< QRhiBuffer > &uniformBuffer, std::unique_ptr< QRhiSampler > &textureSampler, std::unique_ptr< QRhiShaderResourceBindings > &shaderResourceBindings, std::unique_ptr< QRhiGraphicsPipeline > &graphicsPipeline, std::unique_ptr< QRhiRenderPassDescriptor > &renderPass, QVideoFrame &frame, const QVideoFrameTexturesUPtr &videoFrameTextures)
static QImage convertJPEG(const QVideoFrame &frame, const VideoTransformation &transform)
static QT_BEGIN_NAMESPACE constexpr float g_quad[]
QImage qImageFromVideoFrame(const QVideoFrame &frame, const VideoTransformation &transformation, bool forceCpu)
QImage qImageFromVideoFrame(const QVideoFrame &frame, bool forceCpu)
static QShader ensureShader(const QString &name)
static bool pixelFormatHasAlpha(QVideoFrameFormat::PixelFormat format)
static QImage convertCPU(const QVideoFrame &frame, const VideoTransformation &transform)
static void rasterTransform(QImage &image, VideoTransformation transformation)
QImage videoFramePlaneAsImage(QVideoFrame &frame, int plane, QImage::Format targetFormat, QSize targetSize)
Maps the video frame and returns an image having a shared ownership for the video frame and referenci...
static void imageCleanupHandler(void *info)