1 /****************************************************************************
2 **
3 ** Copyright (C) 2016 Pelagicore AG
4 ** Contact: https://www.qt.io/licensing/
5 **
6 ** This file is part of the Qt Toolkit.
7 **
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** Commercial License Usage
10 ** Licensees holding valid commercial Qt licenses may use this file in
11 ** accordance with the commercial license agreement provided with the
12 ** Software or, alternatively, in accordance with the terms contained in
13 ** a written agreement between you and The Qt Company. For licensing terms
14 ** and conditions see https://www.qt.io/terms-conditions. For further
15 ** information use the contact form at https://www.qt.io/contact-us.
16 **
17 ** GNU Lesser General Public License Usage
18 ** Alternatively, this file may be used under the terms of the GNU Lesser
19 ** General Public License version 3 as published by the Free Software
20 ** Foundation and appearing in the file LICENSE.LGPL3 included in the
21 ** packaging of this file. Please review the following information to
22 ** ensure the GNU Lesser General Public License version 3 requirements
23 ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
24 **
25 ** GNU General Public License Usage
26 ** Alternatively, this file may be used under the terms of the GNU
27 ** General Public License version 2.0 or (at your option) the GNU General
28 ** Public license version 3 or any later version approved by the KDE Free
29 ** Qt Foundation. The licenses are as published by the Free Software
30 ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
31 ** included in the packaging of this file. Please review the following
32 ** information to ensure the GNU General Public License requirements will
33 ** be met: https://www.gnu.org/licenses/gpl-2.0.html and
34 ** https://www.gnu.org/licenses/gpl-3.0.html.
35 **
36 ** $QT_END_LICENSE$
37 **
38 ****************************************************************************/
39 
40 #include <GLES2/gl2.h>
41 #include <GLES2/gl2ext.h>
42 
43 #include "qsgvivantevideomaterial.h"
44 #include "qsgvivantevideomaterialshader.h"
45 #include "qsgvivantevideonode.h"
46 
47 #include <QOpenGLContext>
48 #include <QThread>
49 
50 #include <unistd.h>
51 
52 #include <QtMultimedia/private/qtmultimediaglobal_p.h>
53 #include "private/qgstvideobuffer_p.h"
54 #include <gst/allocators/gstphysmemory.h>
55 
56 //#define QT_VIVANTE_VIDEO_DEBUG
57 
QSGVivanteVideoMaterial()58 QSGVivanteVideoMaterial::QSGVivanteVideoMaterial() :
59     mOpacity(1.0),
60     mWidth(0),
61     mHeight(0),
62     mFormat(QVideoFrame::Format_Invalid),
63     mCurrentTexture(0),
64     mMappable(true),
65     mTexDirectTexture(0)
66 {
67 #ifdef QT_VIVANTE_VIDEO_DEBUG
68     qDebug() << Q_FUNC_INFO;
69 #endif
70 
71     setFlag(Blending, false);
72 
73     mShader = new QSGVivanteVideoMaterialShader;
74 }
75 
~QSGVivanteVideoMaterial()76 QSGVivanteVideoMaterial::~QSGVivanteVideoMaterial()
77 {
78     clearTextures();
79 }
80 
type() const81 QSGMaterialType *QSGVivanteVideoMaterial::type() const {
82     static QSGMaterialType theType;
83     return &theType;
84 }
85 
createShader() const86 QSGMaterialShader *QSGVivanteVideoMaterial::createShader() const {
87     return mShader;
88 }
89 
compare(const QSGMaterial * other) const90 int QSGVivanteVideoMaterial::compare(const QSGMaterial *other) const {
91     if (this->type() == other->type()) {
92         const QSGVivanteVideoMaterial *m = static_cast<const QSGVivanteVideoMaterial *>(other);
93         if (this->mBitsToTextureMap == m->mBitsToTextureMap)
94             return 0;
95         else
96             return 1;
97     }
98     return 1;
99 }
100 
updateBlending()101 void QSGVivanteVideoMaterial::updateBlending() {
102     setFlag(Blending, qFuzzyCompare(mOpacity, qreal(1.0)) ? false : true);
103 }
104 
setCurrentFrame(const QVideoFrame & frame,QSGVideoNode::FrameFlags flags)105 void QSGVivanteVideoMaterial::setCurrentFrame(const QVideoFrame &frame, QSGVideoNode::FrameFlags flags)
106 {
107     QMutexLocker lock(&mFrameMutex);
108     mCurrentFrame = frame;
109     mMappable = mMapError == GL_NO_ERROR && !flags.testFlag(QSGVideoNode::FrameFiltered);
110 
111 #ifdef QT_VIVANTE_VIDEO_DEBUG
112     qDebug() << Q_FUNC_INFO << " new frame: " << frame;
113 #endif
114 }
115 
bind()116 void QSGVivanteVideoMaterial::bind()
117 {
118     QOpenGLContext *glcontext = QOpenGLContext::currentContext();
119     if (glcontext == 0) {
120         qWarning() << Q_FUNC_INFO << "no QOpenGLContext::currentContext() => return";
121         return;
122     }
123 
124     QMutexLocker lock(&mFrameMutex);
125     if (mCurrentFrame.isValid())
126         mCurrentTexture = vivanteMapping(mCurrentFrame);
127     else
128         glBindTexture(GL_TEXTURE_2D, mCurrentTexture);
129 }
130 
clearTextures()131 void QSGVivanteVideoMaterial::clearTextures()
132 {
133     for (auto it = mBitsToTextureMap.cbegin(), end = mBitsToTextureMap.cend(); it != end; ++it) {
134         GLuint id = it.value();
135 #ifdef QT_VIVANTE_VIDEO_DEBUG
136         qDebug() << "delete texture: " << id;
137 #endif
138         glDeleteTextures(1, &id);
139     }
140     mBitsToTextureMap.clear();
141 
142     if (mTexDirectTexture) {
143         glDeleteTextures(1, &mTexDirectTexture);
144         mTexDirectTexture = 0;
145     }
146 }
147 
vivanteMapping(QVideoFrame vF)148 GLuint QSGVivanteVideoMaterial::vivanteMapping(QVideoFrame vF)
149 {
150     QOpenGLContext *glcontext = QOpenGLContext::currentContext();
151     if (glcontext == 0) {
152         qWarning() << Q_FUNC_INFO << "no QOpenGLContext::currentContext() => return 0";
153         return 0;
154     }
155 
156     static PFNGLTEXDIRECTVIVPROC glTexDirectVIV_LOCAL = 0;
157     static PFNGLTEXDIRECTVIVMAPPROC glTexDirectVIVMap_LOCAL = 0;
158     static PFNGLTEXDIRECTINVALIDATEVIVPROC glTexDirectInvalidateVIV_LOCAL = 0;
159 
160     if (glTexDirectVIV_LOCAL == 0 || glTexDirectVIVMap_LOCAL == 0 || glTexDirectInvalidateVIV_LOCAL == 0) {
161         glTexDirectVIV_LOCAL = reinterpret_cast<PFNGLTEXDIRECTVIVPROC>(glcontext->getProcAddress("glTexDirectVIV"));
162         glTexDirectVIVMap_LOCAL = reinterpret_cast<PFNGLTEXDIRECTVIVMAPPROC>(glcontext->getProcAddress("glTexDirectVIVMap"));
163         glTexDirectInvalidateVIV_LOCAL = reinterpret_cast<PFNGLTEXDIRECTINVALIDATEVIVPROC>(glcontext->getProcAddress("glTexDirectInvalidateVIV"));
164     }
165     if (glTexDirectVIV_LOCAL == 0 || glTexDirectVIVMap_LOCAL == 0 || glTexDirectInvalidateVIV_LOCAL == 0) {
166         qWarning() << Q_FUNC_INFO << "couldn't find \"glTexDirectVIVMap\" and/or \"glTexDirectInvalidateVIV\" => do nothing and return";
167         return 0;
168     }
169 
170     if (mWidth != vF.width() || mHeight != vF.height() || mFormat != vF.pixelFormat()) {
171         mWidth = vF.width();
172         mHeight = vF.height();
173         mFormat = vF.pixelFormat();
174         mMapError = GL_NO_ERROR;
175         clearTextures();
176     }
177 
178     if (vF.map(QAbstractVideoBuffer::ReadOnly)) {
179 
180         if (mMappable) {
181             if (!mBitsToTextureMap.contains(vF.bits())) {
182                 // Haven't yet seen this logical address: map to texture.
183                 GLuint tmpTexId;
184                 glGenTextures(1, &tmpTexId);
185                 mBitsToTextureMap.insert(vF.bits(), tmpTexId);
186 
187                 // Determine the full width & height. Full means: actual width/height plus extra padding pixels.
188                 // The full width can be deduced from the bytesPerLine value. The full height is calculated
189                 // by calculating the distance between the start of the first and second planes, and dividing
190                 // it by the stride (= the bytesPerLine). If there is only one plane, we don't worry about
191                 // extra padding rows, since there are no adjacent extra planes.
192                 // XXX: This assumes the distance between bits(1) and bits(0) is exactly the size of the first
193                 // plane (the Y plane in the case of YUV data). A better way would be to have a dedicated
194                 // planeSize() or planeOffset() getter.
195                 // Also, this assumes that planes are tightly packed, that is, there is no space between them.
196                 // It is okay to assume this here though, because the Vivante direct textures also assume that.
197                 // In other words, if the planes aren't tightly packed, then the direct textures won't be able
198                 // to render the frame correctly anyway.
199                 int fullWidth = vF.bytesPerLine() / QSGVivanteVideoNode::getBytesForPixelFormat(vF.pixelFormat());
200                 int fullHeight = (vF.planeCount() > 1) ? ((vF.bits(1) - vF.bits(0)) / vF.bytesPerLine()) : vF.height();
201 
202                 // The uscale is the ratio of actual width to the full width (same for vscale and height).
203                 // Since the vivante direct textures do not offer a way to explicitly specify the amount of padding
204                 // columns and rows, we use a trick. We show the full frame - including the padding pixels - in the
205                 // texture, but render only a subset of that texture. This subset goes from (0,0) to (uScale, vScale).
206                 // In the shader, the texture coordinates (which go from (0.0, 0.0) to (1.0, 1.0)) are multiplied by
207                 // the u/v scale values. Since 1.0 * x = x, this effectively limits the texture coordinates from
208                 // (0.0, 0.0) - (1.0, 1.0) to (0.0, 0.0) - (uScale, vScale).
209                 float uScale = float(vF.width()) / float(fullWidth);
210                 float vScale = float(vF.height()) / float(fullHeight);
211                 mShader->setUVScale(uScale, vScale);
212 
213                 const uchar *constBits = vF.bits();
214                 void *bits = (void*)constBits;
215 
216 #ifdef QT_VIVANTE_VIDEO_DEBUG
217                 qDebug() << Q_FUNC_INFO
218                          << "new texture, texId: " << tmpTexId
219                          << "; constBits: " << constBits
220                          << "; actual/full width: " << vF.width() << "/" << fullWidth
221                          << "; actual/full height: " << vF.height() << "/" << fullHeight
222                          << "; UV scale: U " << uScale << " V " << vScale;
223 #endif
224 
225                 GLuint physical = ~0U;
226 #if GST_CHECK_VERSION(1,14,0)
227                 auto buffer = reinterpret_cast<QGstVideoBuffer *>(vF.buffer());
228                 auto mem = gst_buffer_peek_memory(buffer->buffer(), 0);
229                 auto phys_addr = gst_is_phys_memory(mem) ? gst_phys_memory_get_phys_addr(mem) : 0;
230                 if (phys_addr)
231                     physical = phys_addr;
232 #endif
233                 glBindTexture(GL_TEXTURE_2D, tmpTexId);
234                 glTexDirectVIVMap_LOCAL(GL_TEXTURE_2D,
235                                         fullWidth, fullHeight,
236                                         QSGVivanteVideoNode::getVideoFormat2GLFormatMap().value(vF.pixelFormat()),
237                                         &bits, &physical);
238 
239                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
240                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
241                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
242                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
243                 glTexDirectInvalidateVIV_LOCAL(GL_TEXTURE_2D);
244 
245                 mMapError = glGetError();
246                 if (mMapError == GL_NO_ERROR)
247                     return tmpTexId;
248 
249                 // Error occurred.
250                 // Fallback to copying data.
251             } else {
252                 // Fastest path: already seen this logical address. Just
253                 // indicate that the data belonging to the texture has changed.
254                 glBindTexture(GL_TEXTURE_2D, mBitsToTextureMap.value(vF.bits()));
255                 glTexDirectInvalidateVIV_LOCAL(GL_TEXTURE_2D);
256                 return mBitsToTextureMap.value(vF.bits());
257             }
258         }
259 
260         // Cannot map. So copy.
261         if (!mTexDirectTexture) {
262             glGenTextures(1, &mTexDirectTexture);
263             glBindTexture(GL_TEXTURE_2D, mTexDirectTexture);
264             glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
265             glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
266             glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
267             glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
268             glTexDirectVIV_LOCAL(GL_TEXTURE_2D, mCurrentFrame.width(), mCurrentFrame.height(),
269                                  QSGVivanteVideoNode::getVideoFormat2GLFormatMap().value(mCurrentFrame.pixelFormat()),
270                                  (GLvoid **) &mTexDirectPlanes);
271         } else {
272             glBindTexture(GL_TEXTURE_2D, mTexDirectTexture);
273         }
274         switch (mCurrentFrame.pixelFormat()) {
275         case QVideoFrame::Format_YUV420P:
276         case QVideoFrame::Format_YV12:
277             memcpy(mTexDirectPlanes[0], mCurrentFrame.bits(0), mCurrentFrame.height() * mCurrentFrame.bytesPerLine(0));
278             memcpy(mTexDirectPlanes[1], mCurrentFrame.bits(1), mCurrentFrame.height() / 2 * mCurrentFrame.bytesPerLine(1));
279             memcpy(mTexDirectPlanes[2], mCurrentFrame.bits(2), mCurrentFrame.height() / 2 * mCurrentFrame.bytesPerLine(2));
280             break;
281         case QVideoFrame::Format_NV12:
282         case QVideoFrame::Format_NV21:
283             memcpy(mTexDirectPlanes[0], mCurrentFrame.bits(0), mCurrentFrame.height() * mCurrentFrame.bytesPerLine(0));
284             memcpy(mTexDirectPlanes[1], mCurrentFrame.bits(1), mCurrentFrame.height() / 2 * mCurrentFrame.bytesPerLine(1));
285             break;
286         default:
287             memcpy(mTexDirectPlanes[0], mCurrentFrame.bits(), mCurrentFrame.height() * mCurrentFrame.bytesPerLine());
288             break;
289         }
290         glTexDirectInvalidateVIV_LOCAL(GL_TEXTURE_2D);
291         return mTexDirectTexture;
292     }
293     else {
294 #ifdef QT_VIVANTE_VIDEO_DEBUG
295         qWarning() << " couldn't map the QVideoFrame vF: " << vF;
296 #endif
297         return 0;
298     }
299 
300     Q_ASSERT(false); // should never reach this line!;
301     return 0;
302 }
303