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
qandroidvideooutput.cpp
Go to the documentation of this file.
1// Copyright (C) 2021 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#include "wrappers/jni/androidsurfacetexture_p.h"
6
7#include <rhi/qrhi.h>
8#if QT_CONFIG(opengl)
9#include <QtGui/private/qopenglextensions_p.h>
10#include <qopenglcontext.h>
11#include <qopenglfunctions.h>
12#endif
13#include <private/qhwvideobuffer_p.h>
14#include <private/qvideoframeconverter_p.h>
15#include <QtMultimedia/private/qplatformvideosink_p.h>
16#include <private/qvideoframe_p.h>
17#include <qvideosink.h>
18#include <qvideoframeformat.h>
19#include <qpointer.h>
20#include <qthread.h>
21#include <qfile.h>
22
24
26{
27public:
28 QAndroidVideoFrameTextures(QRhi *rhi, QSize size, quint64 handle)
29 {
30 m_tex.reset(rhi->newTexture(QRhiTexture::RGBA8, size, 1));
31 m_tex->createFrom({quint64(handle), 0});
32 }
33
34 QRhiTexture *texture(uint plane) const override
35 {
36 return plane == 0 ? m_tex.get() : nullptr;
37 }
38
39private:
40 std::unique_ptr<QRhiTexture> m_tex;
41};
42
43#if QT_CONFIG(opengl)
44static QOpenGLContextGroup *shareGroup(QRhi &rhi)
45{
46 if (rhi.backend() != QRhi::OpenGLES2)
47 return nullptr;
48 auto *context = static_cast<const QRhiGles2NativeHandles *>(rhi.nativeHandles())->context;
49 return context ? context->shareGroup() : nullptr;
50}
51
52class AndroidTextureThread;
53
54class AndroidTextureVideoBuffer final : public QHwVideoBuffer
55{
56public:
57 AndroidTextureVideoBuffer(std::weak_ptr<AndroidTextureThread> thread,
58 std::unique_ptr<QRhiTexture> tex, QOpenGLContextGroup *shareGroup,
59 const QSize &size)
60 : m_thread(std::move(thread)),
61 m_shareGroup(shareGroup),
62 m_size(size),
63 m_tex(std::move(tex))
64 {}
65
66 MapData map(QVideoFrame::MapMode mode) override;
67
68 void unmap() override
69 {
70 m_image = {};
71 m_mapMode = QVideoFrame::NotMapped;
72 }
73
74 QVideoFrameTexturesUPtr mapTextures(QRhi &rhi) override
75 {
76 // The texture can only be used in contexts sharing with the one it has been created in.
77 // Otherwise, returning nullptr makes the caller fall back to map().
78 if (!m_shareGroup || m_shareGroup != shareGroup(rhi))
79 return nullptr;
80 return std::make_unique<QAndroidVideoFrameTextures>(&rhi, m_size, m_tex->nativeTexture().object);
81 }
82
83 QSize size() const { return m_size; }
84
85private:
86 std::weak_ptr<AndroidTextureThread> m_thread;
87 QPointer<QOpenGLContextGroup> m_shareGroup;
88 QSize m_size;
89 std::unique_ptr<QRhiTexture> m_tex;
90 QImage m_image;
91 QVideoFrame::MapMode m_mapMode = QVideoFrame::NotMapped;
92};
93
94class ImageFromVideoFrameHelper final : public QHwVideoBuffer
95{
96public:
97 ImageFromVideoFrameHelper(AndroidTextureVideoBuffer &atvb, QRhi *rhi)
98 : m_atvb(atvb), m_rhi(rhi)
99 {}
100 QVideoFrameTexturesUPtr mapTextures(QRhi &rhi) override
101 {
102 return m_atvb.mapTextures(rhi);
103 }
104
105 QRhi *associatedCurrentThreadRhi() const override { return m_rhi; }
106
107 MapData map(QVideoFrame::MapMode) override { return {}; }
108 void unmap() override {}
109
110private:
111 AndroidTextureVideoBuffer &m_atvb;
112 QRhi *m_rhi;
113};
114#endif
115
116static const float g_quad[] = {
117 -1.f, -1.f, 0.f, 0.f,
118 -1.f, 1.f, 0.f, 1.f,
119 1.f, 1.f, 1.f, 1.f,
120 1.f, -1.f, 1.f, 0.f
121};
122
124{
125 static QShader getShader(const QString &name)
126 {
127 QFile f(name);
128 if (f.open(QIODevice::ReadOnly))
129 return QShader::fromSerialized(f.readAll());
130 return {};
131 }
132
133public:
134 TextureCopy(QRhi *rhi, QRhiTexture *externalTex)
135 : m_rhi(rhi)
136 {
137 m_vertexBuffer.reset(m_rhi->newBuffer(QRhiBuffer::Immutable, QRhiBuffer::VertexBuffer, sizeof(g_quad)));
138 m_vertexBuffer->create();
139
140 m_uniformBuffer.reset(m_rhi->newBuffer(QRhiBuffer::Dynamic, QRhiBuffer::UniformBuffer, 64 + 64 + 4 + 4));
141 m_uniformBuffer->create();
142
143 m_sampler.reset(m_rhi->newSampler(QRhiSampler::Nearest, QRhiSampler::Nearest, QRhiSampler::None,
144 QRhiSampler::ClampToEdge, QRhiSampler::ClampToEdge));
145 m_sampler->create();
146
147 m_srb.reset(m_rhi->newShaderResourceBindings());
148 m_srb->setBindings({
149 QRhiShaderResourceBinding::uniformBuffer(0, QRhiShaderResourceBinding::VertexStage | QRhiShaderResourceBinding::FragmentStage, m_uniformBuffer.get()),
150 QRhiShaderResourceBinding::sampledTexture(1, QRhiShaderResourceBinding::FragmentStage, externalTex, m_sampler.get())
151 });
152 m_srb->create();
153
154 m_vertexShader = getShader(QStringLiteral(":/qt-project.org/multimedia/shaders/externalsampler.vert.qsb"));
155 Q_ASSERT(m_vertexShader.isValid());
156 m_fragmentShader = getShader(QStringLiteral(":/qt-project.org/multimedia/shaders/externalsampler.frag.qsb"));
157 Q_ASSERT(m_fragmentShader.isValid());
158 }
159
160#if QT_CONFIG(opengl)
162#endif
163
164private:
165 QRhi *m_rhi = nullptr;
166 std::unique_ptr<QRhiBuffer> m_vertexBuffer;
167 std::unique_ptr<QRhiBuffer> m_uniformBuffer;
168 std::unique_ptr<QRhiSampler> m_sampler;
169 std::unique_ptr<QRhiShaderResourceBindings> m_srb;
170 QShader m_vertexShader;
171 QShader m_fragmentShader;
172};
173
174#if QT_CONFIG(opengl)
175static std::unique_ptr<QRhiGraphicsPipeline> newGraphicsPipeline(QRhi *rhi,
176 QRhiShaderResourceBindings *shaderResourceBindings,
177 QRhiRenderPassDescriptor *renderPassDescriptor,
178 QShader vertexShader,
179 QShader fragmentShader)
180{
181 std::unique_ptr<QRhiGraphicsPipeline> gp(rhi->newGraphicsPipeline());
182 gp->setTopology(QRhiGraphicsPipeline::TriangleFan);
183 gp->setShaderStages({
184 { QRhiShaderStage::Vertex, vertexShader },
185 { QRhiShaderStage::Fragment, fragmentShader }
186 });
187 QRhiVertexInputLayout inputLayout;
188 inputLayout.setBindings({
189 { 4 * sizeof(float) }
190 });
191 inputLayout.setAttributes({
192 { 0, 0, QRhiVertexInputAttribute::Float2, 0 },
193 { 0, 1, QRhiVertexInputAttribute::Float2, 2 * sizeof(float) }
194 });
195 gp->setVertexInputLayout(inputLayout);
196 gp->setShaderResourceBindings(shaderResourceBindings);
197 gp->setRenderPassDescriptor(renderPassDescriptor);
198 gp->create();
199
200 return gp;
201}
202
203std::unique_ptr<QRhiTexture> TextureCopy::copyExternalGlTexture(QSize size, const QMatrix4x4 &externalTexMatrix)
204{
205 std::unique_ptr<QRhiTexture> tex(m_rhi->newTexture(QRhiTexture::RGBA8, size, 1, QRhiTexture::RenderTarget));
206 if (!tex->create()) {
207 qWarning("Failed to create frame texture");
208 return {};
209 }
210
211 std::unique_ptr<QRhiTextureRenderTarget> renderTarget(m_rhi->newTextureRenderTarget({ { tex.get() } }));
212 std::unique_ptr<QRhiRenderPassDescriptor> renderPassDescriptor(renderTarget->newCompatibleRenderPassDescriptor());
213 renderTarget->setRenderPassDescriptor(renderPassDescriptor.get());
214 renderTarget->create();
215
216 QRhiResourceUpdateBatch *rub = m_rhi->nextResourceUpdateBatch();
217 rub->uploadStaticBuffer(m_vertexBuffer.get(), g_quad);
218
219 QMatrix4x4 identity;
220 char *p = m_uniformBuffer->beginFullDynamicBufferUpdateForCurrentFrame();
221 memcpy(p, identity.constData(), 64);
222 memcpy(p + 64, externalTexMatrix.constData(), 64);
223 float opacity = 1.0f;
224 memcpy(p + 64 + 64, &opacity, 4);
225 m_uniformBuffer->endFullDynamicBufferUpdateForCurrentFrame();
226
227 auto graphicsPipeline = newGraphicsPipeline(m_rhi, m_srb.get(), renderPassDescriptor.get(),
228 m_vertexShader, m_fragmentShader);
229
230 const QRhiCommandBuffer::VertexInput vbufBinding(m_vertexBuffer.get(), 0);
231
232 QRhiCommandBuffer *cb = nullptr;
233 if (m_rhi->beginOffscreenFrame(&cb) != QRhi::FrameOpSuccess)
234 return {};
235
236 cb->beginPass(renderTarget.get(), Qt::transparent, { 1.0f, 0 }, rub);
237 cb->setGraphicsPipeline(graphicsPipeline.get());
238 cb->setViewport({0, 0, float(size.width()), float(size.height())});
239 cb->setShaderResources(m_srb.get());
240 cb->setVertexInput(0, 1, &vbufBinding);
241 cb->draw(4);
242 cb->endPass();
243 m_rhi->endOffscreenFrame();
244
245 QOpenGLContext *ctx = QOpenGLContext::currentContext();
246 QOpenGLFunctions *f = ctx->functions();
247 static_cast<QOpenGLExtensions *>(f)->flushShared();
248
249 return tex;
250}
251
252static QMatrix4x4 extTransformMatrix(AndroidSurfaceTexture *surfaceTexture)
253{
254 QMatrix4x4 m = surfaceTexture->getTransformMatrix();
255 // flip it back, see
256 // http://androidxref.com/9.0.0_r3/xref/frameworks/native/libs/gui/GLConsumer.cpp#866
257 // (NB our matrix ctor takes row major)
258 static const QMatrix4x4 flipV(1.0f, 0.0f, 0.0f, 0.0f,
259 0.0f, -1.0f, 0.0f, 1.0f,
260 0.0f, 0.0f, 1.0f, 0.0f,
261 0.0f, 0.0f, 0.0f, 1.0f);
262 m *= flipV;
263 return m;
264}
265
266#endif
267
269{
271public:
277
284
285 void start()
286 {
287 QThread::start();
288 moveToThread(this);
289 }
290
291#if QT_CONFIG(opengl)
293 {
298 }
299#endif
300
301public Q_SLOTS:
303 {
304 // Check if 'm_surfaceTexture' is not reset and if the current index is the same that
305 // was used for creating connection because there can be pending frames in queue.
307#if QT_CONFIG(opengl)
313 m_size);
316#endif
317 }
318 }
319
320 void clearFrame() { Q_EMIT newFrame({}); }
321
322#if QT_CONFIG(opengl)
324 {
326 if (!m_rhi)
327 return {};
328
332 }
333#endif
334
336
344
346 {
348 return m_surfaceTexture.get();
349
350#if QT_CONFIG(opengl)
352 ? static_cast<const QRhiGles2NativeHandles *>(rhi->nativeHandles())->context
353 : nullptr;
354 initRhi(ctx);
355
357 m_texture->create();
362 [this, index] () { this->onFrameAvailable(index); });
363
365
366 } else {
369 }
370
371 return m_surfaceTexture.get();
372#else
373 qCritical()
374 << "Attempting to use Qt Multimedia VideoOutput on a Qt build without OpenGL support. "
375 << "This is not supported by the native Android media backend.";
376 m_rhi.reset(QRhi::create(QRhi::Null, nullptr));
377 return nullptr;
378#endif
379 }
380
382 void newFrame(const QVideoFrame &);
383
384private:
385 QAndroidTextureVideoOutput * m_videoOutput;
386 std::shared_ptr<QRhi> m_rhi;
387 std::unique_ptr<AndroidSurfaceTexture> m_surfaceTexture;
388 std::unique_ptr<QRhiTexture> m_texture;
389 std::unique_ptr<TextureCopy> m_textureCopy;
390 QSize m_size;
391};
392
393#if QT_CONFIG(opengl)
394QAbstractVideoBuffer::MapData AndroidTextureVideoBuffer::map(QVideoFrame::MapMode mode)
395{
396 QAbstractVideoBuffer::MapData mapData;
397
398 if (m_mapMode != QVideoFrame::NotMapped || mode != QVideoFrame::ReadOnly)
399 return mapData;
400
401 // Read back in the texture thread: a thread-local rhi of the calling thread does not share
402 // a context with the texture.
403 const std::shared_ptr<AndroidTextureThread> thread = m_thread.lock();
404 if (!thread)
405 return mapData;
406
407 if (thread->isCurrentThread()) {
408 m_image = thread->imageFromVideoBuffer(*this);
409 } else {
410 QMetaObject::invokeMethod(
411 thread.get(), [&] { m_image = thread->imageFromVideoBuffer(*this); },
412 Qt::BlockingQueuedConnection);
413 }
414
415 if (m_image.isNull())
416 return mapData;
417
418 m_mapMode = QVideoFrame::ReadOnly;
419 mapData.planeCount = 1;
420 mapData.bytesPerLine[0] = m_image.bytesPerLine();
421 mapData.dataSize[0] = static_cast<int>(m_image.sizeInBytes());
422 mapData.data[0] = m_image.bits();
423 return mapData;
424}
425#endif
426
427namespace {
428
429bool hasRhi(QVideoSink *videoSink)
430{
431 auto *sink = videoSink ? qobject_cast<QRhiVideoSink *>(videoSink->platformVideoSink()) : nullptr;
432 return sink && sink->withRhi([](QRhi *rhi) {
433 return rhi != nullptr;
434 });
435}
436
437template <typename Functor>
438auto withSinkRhi(QVideoSink *videoSink, Functor &&functor)
439{
440 auto *sink = videoSink ? qobject_cast<QRhiVideoSink *>(videoSink->platformVideoSink()) : nullptr;
441 if (!sink)
442 return functor(static_cast<QRhi *>(nullptr));
443 return sink->withRhi(std::forward<Functor>(functor));
444}
445
446}
447
448QAndroidTextureVideoOutput::QAndroidTextureVideoOutput(QVideoSink *sink, QObject *parent)
449 : QAndroidVideoOutput(parent)
450 , m_sink(sink)
451{
452 if (!m_sink) {
453 qDebug() << "Cannot create QAndroidTextureVideoOutput without a sink.";
454 m_surfaceThread = nullptr;
455 return;
456 }
457
458 startNewSurfaceThread();
459}
460
461void QAndroidTextureVideoOutput::startNewSurfaceThread()
462{
463 m_surfaceThread = std::make_shared<AndroidTextureThread>(this);
464 connect(m_surfaceThread.get(), &AndroidTextureThread::newFrame,
465 this, &QAndroidTextureVideoOutput::newFrame);
466 m_surfaceThread->start();
467}
468
470{
471 // Make sure that no more VideFrames will be created by surfaceThread
472 QMetaObject::invokeMethod(m_surfaceThread.get(),
473 &AndroidTextureThread::clearSurfaceTexture, Qt::BlockingQueuedConnection);
474}
475
476void QAndroidTextureVideoOutput::setSubtitle(const QString &subtitle)
477{
478 if (m_sink) {
479 auto *sink = m_sink->platformVideoSink();
480 if (sink)
481 sink->setSubtitleText(subtitle);
482 }
483}
484
486{
487 return hasRhi(m_sink) && m_surfaceCreatedWithoutRhi;
488}
489
491{
492 if (!m_sink)
493 return nullptr;
494
495 AndroidSurfaceTexture *surface = nullptr;
496 QMetaObject::invokeMethod(m_surfaceThread.get(), [&] {
497 withSinkRhi(m_sink, [&](QRhi *rhi) {
498 if (!rhi) {
499 m_surfaceCreatedWithoutRhi = true;
500 }
501 else if (m_surfaceCreatedWithoutRhi) {
502 m_surfaceThread->clearSurfaceTexture();
503 m_surfaceCreatedWithoutRhi = false;
504 }
505 surface = m_surfaceThread->createSurfaceTexture(rhi);
506 });
507 },
508 Qt::BlockingQueuedConnection);
509 return surface;
510}
511
513{
514 if (m_nativeSize == size)
515 return;
516
517 m_nativeSize = size;
518 QMetaObject::invokeMethod(m_surfaceThread.get(),
519 [&](){ m_surfaceThread->setFrameSize(size); },
520 Qt::BlockingQueuedConnection);
521}
522
524{
525 m_nativeSize = {};
526 QMetaObject::invokeMethod(m_surfaceThread.get(), [&](){ m_surfaceThread->clearFrame(); });
527}
528
530{
531 if (m_sink)
532 m_sink->platformVideoSink()->setVideoFrame({});
533 QMetaObject::invokeMethod(m_surfaceThread.get(), &AndroidTextureThread::clearSurfaceTexture);
534}
535
536void QAndroidTextureVideoOutput::newFrame(const QVideoFrame &frame)
537{
538 if (m_sink)
539 m_sink->setVideoFrame(frame);
540}
541
542QT_END_NAMESPACE
543
544#include "qandroidvideooutput.moc"
545#include "moc_qandroidvideooutput_p.cpp"
void setSubtitle(const QString &subtitle)
void setVideoSize(const QSize &) override
AndroidSurfaceTexture * surfaceTexture() override
QAndroidVideoFrameTextures(QRhi *rhi, QSize size, quint64 handle)
QRhiTexture * texture(uint plane) const override
Definition qfile.h:71
TextureCopy(QRhi *rhi, QRhiTexture *externalTex)
Combined button and popup list for selecting options.
static const float g_quad[]