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
qohosvideooutput.cpp
Go to the documentation of this file.
1// Copyright (C) 2026 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
5
8
9#include <private/qhwvideobuffer_p.h>
10#include <private/qplatformvideosink_p.h>
11#include <private/qvideoframe_p.h>
12#include <private/qvideoframeconverter_p.h>
13
14#include <rhi/qrhi.h>
15#include <rhi/qrhi_platform.h>
16
17#include <QtMultimedia/qvideoframe.h>
18#include <QtMultimedia/qvideoframeformat.h>
19#include <QtMultimedia/qvideosink.h>
20#include <QtMultimedia/qtvideo.h>
21
22#include <QtGui/qmatrix4x4.h>
23#include <QtGui/qopenglcontext.h>
24#include <QtGui/qoffscreensurface.h>
25#include <QtGui/qguiapplication.h>
26#include <QtGui/qscreen.h>
27
28#include <QtCore/qfile.h>
29#include <QtCore/qloggingcategory.h>
30
31#include <atomic>
32#include <QtCore/qpointer.h>
33#include <QtCore/qthread.h>
34
36
37namespace {
38
39const float g_quad[] = {
40 -1.f, -1.f, 0.f, 0.f,
41 -1.f, 1.f, 0.f, 1.f,
42 1.f, 1.f, 1.f, 1.f,
43 1.f, -1.f, 1.f, 0.f
44};
45
47{
48public:
49 QOhosVideoFrameTextures(QRhi *rhi, QSize size, quint64 handle)
50 {
51 m_tex.reset(rhi->newTexture(QRhiTexture::RGBA8, size, 1));
52 m_tex->createFrom({ handle, 0 });
53 }
54 QRhiTexture *texture(uint plane) const override { return plane == 0 ? m_tex.get() : nullptr; }
55
56private:
57 std::unique_ptr<QRhiTexture> m_tex;
58};
59
60class QOhosTextureVideoBuffer final : public QHwVideoBuffer
61{
62public:
63 QOhosTextureVideoBuffer(std::unique_ptr<QRhiTexture> tex, const QSize &size,
64 std::weak_ptr<QRhi> producerRhi, QPointer<QObject> producer,
65 QPointer<QOpenGLContext> producerContext)
66 : m_size(size)
67 , m_tex(std::move(tex))
71 {
72 }
73
74 MapData map(QVideoFrame::MapMode mode) override
75 {
76 MapData data;
77 if (m_mapMode != QVideoFrame::NotMapped || mode != QVideoFrame::ReadOnly)
78 return data;
79 m_mapMode = QVideoFrame::ReadOnly;
80 if (m_image.isNull())
81 m_image = readbackOnProducerThread();
82 if (m_image.isNull()) {
83 m_mapMode = QVideoFrame::NotMapped;
84 return data;
85 }
86 data.planeCount = 1;
87 data.bytesPerLine[0] = m_image.bytesPerLine();
88 data.dataSize[0] = static_cast<int>(m_image.sizeInBytes());
89 data.data[0] = m_image.bits();
90 return data;
91 }
92
94 {
95 m_image = {};
96 m_mapMode = QVideoFrame::NotMapped;
97 }
98
100 {
101 // The texture lives in the producer (texture-thread) GL context. Sampling
102 // requires the caller's RHI to share that GL context's resources. The main
103 // window RHI does (we created the producer with shareContext = main rhi
104 // context). A worker thread's QThreadLocal RHI does not — so report no
105 // textures and let qImageFromVideoFrame fall back to CPU mapping.
106 if (!isCompatibleRhi(rhi))
107 return {};
108 return std::make_unique<QOhosVideoFrameTextures>(&rhi, m_size,
109 m_tex->nativeTexture().object);
110 }
111
112private:
113 bool isCompatibleRhi(QRhi &rhi) const
114 {
115 if (rhi.backend() != QRhi::OpenGLES2)
116 return false;
117 if (!m_producerContext)
118 return false;
119 const auto *handles =
120 static_cast<const QRhiGles2NativeHandles *>(rhi.nativeHandles());
121 if (!handles || !handles->context)
122 return false;
123 return handles->context->shareGroup() == m_producerContext->shareGroup();
124 }
125
126 QImage readbackOnProducerThread() const
127 {
128 auto producerRhi = m_producerRhi.lock();
129 if (!producerRhi || !m_producer)
130 return {};
131 QImage out;
132 QRhi *rhi = producerRhi.get();
133 QRhiTexture *tex = m_tex.get();
134 QMetaObject::invokeMethod(
135 m_producer.data(),
136 [rhi, tex, &out]() {
137 QRhiReadbackResult result;
138 bool done = false;
139 result.completed = [&done] { done = true; };
140 QRhiCommandBuffer *cb = nullptr;
141 if (rhi->beginOffscreenFrame(&cb) != QRhi::FrameOpSuccess)
142 return;
143 QRhiResourceUpdateBatch *rub = rhi->nextResourceUpdateBatch();
144 rub->readBackTexture({ tex }, &result);
145 cb->resourceUpdate(rub);
146 rhi->endOffscreenFrame();
147 if (!done || result.data.isEmpty())
148 return;
149 QImage img(reinterpret_cast<const uchar *>(result.data.constData()),
150 result.pixelSize.width(), result.pixelSize.height(),
151 result.pixelSize.width() * 4, QImage::Format_RGBA8888);
152 out = img.copy();
153 },
154 Qt::BlockingQueuedConnection);
155 return out;
156 }
157
158 QSize m_size;
159 std::unique_ptr<QRhiTexture> m_tex;
160 QImage m_image;
161 QVideoFrame::MapMode m_mapMode = QVideoFrame::NotMapped;
162 std::weak_ptr<QRhi> m_producerRhi;
163 QPointer<QObject> m_producer;
164 QPointer<QOpenGLContext> m_producerContext;
165};
166
168{
169public:
170 TextureCopy(QRhi *rhi, QRhiTexture *externalTex) : m_rhi(rhi)
171 {
172 m_vertexBuffer.reset(m_rhi->newBuffer(QRhiBuffer::Immutable, QRhiBuffer::VertexBuffer,
173 sizeof(g_quad)));
174 m_vertexBuffer->create();
175
176 m_uniformBuffer.reset(m_rhi->newBuffer(QRhiBuffer::Dynamic,
177 QRhiBuffer::UniformBuffer, 160));
178 m_uniformBuffer->create();
179
180 m_sampler.reset(m_rhi->newSampler(QRhiSampler::Nearest, QRhiSampler::Nearest,
181 QRhiSampler::None, QRhiSampler::ClampToEdge,
182 QRhiSampler::ClampToEdge));
183 m_sampler->create();
184
185 m_srb.reset(m_rhi->newShaderResourceBindings());
186 m_srb->setBindings({
187 QRhiShaderResourceBinding::uniformBuffer(
188 0,
189 QRhiShaderResourceBinding::VertexStage
190 | QRhiShaderResourceBinding::FragmentStage,
191 m_uniformBuffer.get()),
192 QRhiShaderResourceBinding::sampledTexture(
193 1, QRhiShaderResourceBinding::FragmentStage, externalTex, m_sampler.get())
194 });
195 m_srb->create();
196
197 m_vertexShader = loadShader(
198 QStringLiteral(":/qt-project.org/multimedia/shaders/externalsampler.vert.qsb"));
199 m_fragmentShader = loadShader(
200 QStringLiteral(":/qt-project.org/multimedia/shaders/externalsampler.frag.qsb"));
201 }
202
203 std::unique_ptr<QRhiTexture> copyExternalTexture(QSize size, const QMatrix4x4 &externalTexMatrix);
204
205private:
206 static QShader loadShader(const QString &name)
207 {
208 QFile f(name);
209 if (f.open(QIODevice::ReadOnly))
210 return QShader::fromSerialized(f.readAll());
211 return {};
212 }
213
214 QRhi *m_rhi{ nullptr };
215 std::unique_ptr<QRhiBuffer> m_vertexBuffer;
216 std::unique_ptr<QRhiBuffer> m_uniformBuffer;
217 std::unique_ptr<QRhiSampler> m_sampler;
218 std::unique_ptr<QRhiShaderResourceBindings> m_srb;
219 QShader m_vertexShader;
220 QShader m_fragmentShader;
221};
222
224 QRhiShaderResourceBindings *srb,
225 QRhiRenderPassDescriptor *rpd,
226 QShader vs, QShader fs)
227{
228 std::unique_ptr<QRhiGraphicsPipeline> gp(rhi->newGraphicsPipeline());
229 gp->setTopology(QRhiGraphicsPipeline::TriangleFan);
230 gp->setShaderStages({
231 { QRhiShaderStage::Vertex, vs },
232 { QRhiShaderStage::Fragment, fs }
233 });
235 layout.setBindings({ { 4 * sizeof(float) } });
236 layout.setAttributes({
237 { 0, 0, QRhiVertexInputAttribute::Float2, 0 },
238 { 0, 1, QRhiVertexInputAttribute::Float2, 2 * sizeof(float) }
239 });
240 gp->setVertexInputLayout(layout);
241 gp->setShaderResourceBindings(srb);
242 gp->setRenderPassDescriptor(rpd);
243 gp->create();
244 return gp;
245}
246
248TextureCopy::copyExternalTexture(QSize size, const QMatrix4x4 &externalTexMatrix)
249{
250 std::unique_ptr<QRhiTexture> tex(
251 m_rhi->newTexture(QRhiTexture::RGBA8, size, 1, QRhiTexture::RenderTarget));
252 if (!tex->create()) {
253 qCWarning(qLcOhosMediaPlugin) << "Failed to create frame texture";
254 return {};
255 }
256
257 std::unique_ptr<QRhiTextureRenderTarget> renderTarget(
258 m_rhi->newTextureRenderTarget({ { tex.get() } }));
259 std::unique_ptr<QRhiRenderPassDescriptor> rpd(
260 renderTarget->newCompatibleRenderPassDescriptor());
261 renderTarget->setRenderPassDescriptor(rpd.get());
262 renderTarget->create();
263
264 QRhiResourceUpdateBatch *rub = m_rhi->nextResourceUpdateBatch();
265 rub->uploadStaticBuffer(m_vertexBuffer.get(), g_quad);
266
267 const QMatrix4x4 identity;
268 char *p = m_uniformBuffer->beginFullDynamicBufferUpdateForCurrentFrame();
269 memcpy(p, identity.constData(), 64);
270 memcpy(p + 64, externalTexMatrix.constData(), 64);
271 const float opacity = 1.0f;
272 memcpy(p + 64 + 64, &opacity, 4);
273 m_uniformBuffer->endFullDynamicBufferUpdateForCurrentFrame();
274
275 auto pipeline = newGraphicsPipeline(m_rhi, m_srb.get(), rpd.get(), m_vertexShader,
276 m_fragmentShader);
277
278 const QRhiCommandBuffer::VertexInput vbufBinding(m_vertexBuffer.get(), 0);
279 QRhiCommandBuffer *cb = nullptr;
280 if (m_rhi->beginOffscreenFrame(&cb) != QRhi::FrameOpSuccess)
281 return {};
282
283 cb->beginPass(renderTarget.get(), Qt::transparent, { 1.0f, 0 }, rub);
284 cb->setGraphicsPipeline(pipeline.get());
285 cb->setViewport({ 0, 0, float(size.width()), float(size.height()) });
286 cb->setShaderResources(m_srb.get());
287 cb->setVertexInput(0, 1, &vbufBinding);
288 cb->draw(4);
289 cb->endPass();
290 m_rhi->endOffscreenFrame();
291
292 return tex;
293}
294
295} // namespace
296
298{
300public:
302
309
310 void launch()
311 {
312 QThread::start();
313 moveToThread(this);
314 }
315
323
325 {
328 this,
329 [&]() {
331 if (m_surfaceImage)
333 },
335 return id;
336 }
337
343
344public Q_SLOTS:
345 void tearDown()
346 {
350 m_rhi.reset();
351 m_shareContext = nullptr;
352 }
353
354 // Sampled on the GUI thread; QScreen must not be touched from this thread.
359
361 {
363 return;
365 return;
366 if (!m_textureCopy)
367 return;
368 // GL bottom-left to top-left origin flip.
369 static const QMatrix4x4 flipV(1.0f, 0.0f, 0.0f, 0.0f,
370 0.0f, -1.0f, 0.0f, 1.0f,
371 0.0f, 0.0f, 1.0f, 0.0f,
372 0.0f, 0.0f, 0.0f, 1.0f);
374 // The sensor transform swaps x/y on 90/270; transpose the target to match aspect.
375 const bool axesSwapped = std::abs(matrix(0, 0)) < std::abs(matrix(0, 1));
378 matrix *= flipV;
380 if (!rgba)
381 return;
383 if (const auto *handles =
384 static_cast<const QRhiGles2NativeHandles *>(m_rhi->nativeHandles()))
388 QPointer<QObject>(this), ctx);
393 }
394
397
398private:
399 OHNativeWindow *ensureSurface(QRhi *rhi)
400 {
401 const auto *nativeHandles =
402 rhi ? static_cast<const QRhiGles2NativeHandles *>(rhi->nativeHandles())
403 : nullptr;
404 QOpenGLContext *shareContext = nativeHandles ? nativeHandles->context : nullptr;
405
406 // Re-use the existing surface only while it still shares the caller's
407 // GL context. For headless camera (rhi == nullptr) we accept any prior
408 // standalone surface.
409 const bool reuse = m_surfaceImage && m_surfaceImage->isValid()
410 && (rhi ? !m_isHeadless && m_shareContext == shareContext : m_isHeadless);
411 if (reuse)
412 return m_surfaceImage->nativeWindow();
413
414 // Order matters: the texture and the copy pipeline outlive m_rhi otherwise.
415 tearDown();
416
417 // Share with the main RHI's GL context so consumers can sample the
418 // texture. For headless mode we create a standalone offscreen GLES2
419 // RHI without a share context — frames are produced but consumers
420 // (cameras, recorders) only need the native surface handle.
421 QRhiGles2InitParams params;
422 params.shareContext = shareContext;
423 params.fallbackSurface = QRhiGles2InitParams::newFallbackSurface();
424 m_isHeadless = (rhi == nullptr);
425 m_shareContext = shareContext;
426 m_rhi.reset(QRhi::create(QRhi::OpenGLES2, &params));
427 if (!m_rhi) {
428 qCWarning(qLcOhosMediaPlugin) << "Failed to create offscreen GLES2 RHI";
429 return nullptr;
430 }
431
432 m_externalTexture.reset(
433 m_rhi->newTexture(QRhiTexture::RGBA8, m_size.isEmpty() ? QSize{ 1, 1 } : m_size, 1,
434 QRhiTexture::ExternalOES));
435 if (!m_externalTexture->create()) {
436 qCWarning(qLcOhosMediaPlugin) << "External OES texture create failed";
437 m_externalTexture.reset();
438 m_rhi.reset();
439 return nullptr;
440 }
441
442 const auto nativeTex = m_externalTexture->nativeTexture();
443 m_surfaceImage = std::make_unique<QOhosSurfaceImage>(uint32_t(nativeTex.object));
444 if (!m_surfaceImage->isValid()) {
445 m_surfaceImage.reset();
446 m_externalTexture.reset();
447 m_rhi.reset();
448 return nullptr;
449 }
450
451 const quint64 index = m_surfaceImage->index();
452 connect(m_surfaceImage.get(), &QOhosSurfaceImage::frameAvailable, this,
453 [this, index]() { onFrameAvailable(index); }, Qt::QueuedConnection);
454
455 m_textureCopy = std::make_unique<TextureCopy>(m_rhi.get(), m_externalTexture.get());
456 return m_surfaceImage->nativeWindow();
457 }
458
459 std::shared_ptr<QRhi> m_rhi;
460 std::unique_ptr<QRhiTexture> m_externalTexture;
461 std::unique_ptr<QOhosSurfaceImage> m_surfaceImage;
462 std::unique_ptr<TextureCopy> m_textureCopy;
463 QSize m_size{ 1, 1 };
464 std::atomic<QtVideo::Rotation> m_displayRotation{ QtVideo::Rotation::None };
465 QPointer<QOpenGLContext> m_shareContext;
466 bool m_isHeadless{ false };
467};
468
469QOhosVideoOutput::QOhosVideoOutput(QVideoSink *sink, ContentSource contentSource,
470 QObject *parent)
472{
473 m_textureThread = std::make_shared<QOhosTextureThread>();
474 connect(m_textureThread.get(), &QOhosTextureThread::newFrame, this,
475 &QOhosVideoOutput::onNewFrame, Qt::QueuedConnection);
476 m_textureThread->launch();
477
478 if (auto *p = sink ? sink->platformVideoSink() : nullptr) {
479 connect(p, &QPlatformVideoSink::rhiChanged, this, &QOhosVideoOutput::onRhiChanged);
480 }
481
482 if (m_contentSource == ContentSource::Camera) {
483 if (QScreen *screen = QGuiApplication::primaryScreen()) {
484 connect(screen, &QScreen::orientationChanged, this,
485 &QOhosVideoOutput::updateDisplayRotation);
486 }
487 updateDisplayRotation();
488 }
489}
490
491void QOhosVideoOutput::updateDisplayRotation()
492{
493 QtVideo::Rotation rotation = QtVideo::Rotation::None;
494 if (const QScreen *screen = QGuiApplication::primaryScreen()) {
495 switch (screen->angleBetween(screen->orientation(), screen->nativeOrientation())) {
496 case 90:
497 rotation = QtVideo::Rotation::Clockwise90;
498 break;
499 case 180:
500 rotation = QtVideo::Rotation::Clockwise180;
501 break;
502 case 270:
503 rotation = QtVideo::Rotation::Clockwise270;
504 break;
505 default:
506 break;
507 }
508 }
509 m_textureThread->setDisplayRotation(rotation);
510}
511
512void QOhosVideoOutput::onRhiChanged()
513{
514 if (!m_sink || !m_sink->rhi())
515 return;
516 if (m_surfaceCreatedWithoutRhi) {
517 tearDownTextureThread();
518 m_surfaceCreatedWithoutRhi = false;
519 }
520 Q_EMIT surfaceReady();
521}
522
524{
525 tearDownTextureThread();
526}
527
528void QOhosVideoOutput::tearDownTextureThread()
529{
530 // Delivered frames own textures from the RHI that is about to go away.
531 if (m_sink)
532 m_sink->setVideoFrame({});
533 QMetaObject::invokeMethod(m_textureThread.get(), &QOhosTextureThread::tearDown,
534 Qt::BlockingQueuedConnection);
535}
536
538{
539 auto *rhi = m_sink ? m_sink->rhi() : nullptr;
540 if (!rhi) {
541 m_surfaceCreatedWithoutRhi = true;
542 } else if (m_surfaceCreatedWithoutRhi) {
543 tearDownTextureThread();
544 m_surfaceCreatedWithoutRhi = false;
545 }
546 return m_textureThread->nativeWindowBlocking(rhi);
547}
548
550{
551 // The camera framework needs a surface even when there's no sink or the
552 // sink isn't bound to a window yet. Spin up an offscreen RHI internally so
553 // capture can proceed headless; surfaceReady will reattach once the sink
554 // gets a real RHI.
555 auto *rhi = m_sink ? m_sink->rhi() : nullptr;
556 if (!rhi)
557 m_surfaceCreatedWithoutRhi = true;
558 else if (m_surfaceCreatedWithoutRhi) {
559 tearDownTextureThread();
560 m_surfaceCreatedWithoutRhi = false;
561 }
562 return m_textureThread->surfaceIdBlocking(rhi);
563}
564
565void QOhosVideoOutput::setVideoSize(const QSize &size)
566{
567 if (m_videoSize == size || !size.isValid())
568 return;
569 m_videoSize = size;
570 m_textureThread->setFrameSizeBlocking(size);
571 if (m_sink) {
572 if (auto *p = m_sink->platformVideoSink())
573 p->setNativeSize(size);
574 }
575}
576
577void QOhosVideoOutput::onNewFrame(const QVideoFrame &frame)
578{
579 if (m_sink)
580 m_sink->setVideoFrame(frame);
581}
582
583QT_END_NAMESPACE
584
585#include "qohosvideooutput.moc"
586#include "moc_qohosvideooutput_p.cpp"
void setVideoSize(const QSize &size)
QOhosVideoOutput(QVideoSink *sink, ContentSource contentSource, QObject *parent=nullptr)
OHNativeWindow * nativeWindow()
\inmodule QtGuiPrivate \inheaderfile rhi/qrhi.h
Definition qrhi.h:325
QOhosTextureVideoBuffer(std::unique_ptr< QRhiTexture > tex, const QSize &size, std::weak_ptr< QRhi > producerRhi, QPointer< QObject > producer, QPointer< QOpenGLContext > producerContext)
QVideoFrameTexturesUPtr mapTextures(QRhi &rhi) override
void unmap() override
Releases the memory mapped by the map() function.
MapData map(QVideoFrame::MapMode mode) override
Maps the planes of a video buffer to memory.
QRhiTexture * texture(uint plane) const override
QOhosVideoFrameTextures(QRhi *rhi, QSize size, quint64 handle)
std::unique_ptr< QRhiTexture > copyExternalTexture(QSize size, const QMatrix4x4 &externalTexMatrix)
TextureCopy(QRhi *rhi, QRhiTexture *externalTex)
Combined button and popup list for selecting options.
std::unique_ptr< QRhiGraphicsPipeline > newGraphicsPipeline(QRhi *rhi, QRhiShaderResourceBindings *srb, QRhiRenderPassDescriptor *rpd, QShader vs, QShader fs)