summaryrefslogtreecommitdiffstats
path: root/src/3rdparty/phonon/gstreamer/glrenderer.cpp
blob: 020302813e1ecf975ee916b5ccace8a88eb1d50b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
/*  This file is part of the KDE project.

    Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).

    This library is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation, either version 2.1 or 3 of the License.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with this library.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <QtGui/QPainter>
#include <QtGui/QResizeEvent>

#ifndef QT_NO_OPENGL

#include "common.h"
#include "message.h"
#include "mediaobject.h"
#include "qwidgetvideosink.h"
#include "glrenderer.h"
#include "qrgb.h"

#if !defined(QT_OPENGL_ES)

#include <gst/gst.h>

// support old OpenGL installations (1.2)
// assume that if TEXTURE0 isn't defined, none are
#ifndef GL_TEXTURE0
# define GL_TEXTURE0    0x84C0
# define GL_TEXTURE1    0x84C1
# define GL_TEXTURE2    0x84C2
#endif

QT_BEGIN_NAMESPACE

static void frameRendered()
{
    static QString displayFps = qgetenv("PHONON_GST_FPS");
    if (displayFps.isEmpty())
        return;

    static int frames = 0;
    static QTime lastTime = QTime::currentTime();
    QTime time = QTime::currentTime();

    int delta = lastTime.msecsTo(time);
    if (delta > 2000) {
        printf("FPS: %f\n", 1000.0 * frames / qreal(delta));
        lastTime = time;
        frames = 0;
    }

    ++frames;
}

namespace Phonon
{
namespace Gstreamer
{

GLRenderer::GLRenderer(VideoWidget* videoWidget) :
    AbstractRenderer(videoWidget)
    , m_glWindow(0)
{
    videoWidget->backend()->logMessage("Creating OpenGL renderer");
    QGLFormat format = QGLFormat::defaultFormat();
    format.setSwapInterval(1);    // Enable vertical sync on draw to avoid tearing
    m_glWindow = new GLRenderWidgetImplementation(videoWidget, format);

    if ((m_videoSink = m_glWindow->createVideoSink())) {    //if ((m_videoSink = m_glWindow->createVideoSink())) {
        gst_object_ref (GST_OBJECT (m_videoSink)); //Take ownership
        gst_object_sink (GST_OBJECT (m_videoSink));

        QWidgetVideoSinkBase*  sink = reinterpret_cast<QWidgetVideoSinkBase*>(m_videoSink);
        // Let the videosink know which widget to direct frame updates to
        sink->renderWidget = videoWidget;
    }
}

GLRenderer::~GLRenderer()
{
    if (m_videoSink) {
        gst_object_unref (GST_OBJECT (m_videoSink));
        m_videoSink = 0;
    }
}


bool GLRenderer::eventFilter(QEvent * event)
{
    if (event->type() == QEvent::User) {
        NewFrameEvent *frameEvent= static_cast <NewFrameEvent *>(event);
        m_glWindow->setNextFrame(frameEvent->frame, frameEvent->width, frameEvent->height);
        return true;
    }
    else if (event->type() == QEvent::Resize) {
        m_glWindow->setGeometry(m_videoWidget->geometry());
        return true;
    }
    return false;
}

void GLRenderer::handleMediaNodeEvent(const MediaNodeEvent *event)
{
    switch (event->type()) {
    case MediaNodeEvent::SourceChanged:
    {
        Q_ASSERT(m_glWindow);
        m_glWindow->clearFrame();
        break;
    }
    default:
        break;
    }
}

GstElement* GLRenderWidgetImplementation::createVideoSink()
{
    if (hasYUVSupport())
        return GST_ELEMENT(g_object_new(get_type_YUV(), NULL));
    return 0;
}

void GLRenderWidgetImplementation::setNextFrame(const QByteArray &array, int w, int h)
{
    if (m_videoWidget->root()->state() == Phonon::LoadingState)
        return;

    m_frame = QImage();

    if (hasYUVSupport())
        updateTexture(array, w, h);
    else
        m_frame = QImage((uchar *)array.constData(), w, h, QImage::Format_RGB32);

    m_array = array;
    m_width = w;
    m_height = h;

    update();
}

void GLRenderWidgetImplementation::clearFrame()
{
    m_frame = QImage();
    m_array = QByteArray();
    update();
}

bool GLRenderWidgetImplementation::hasYUVSupport() const
{
    return m_yuvSupport;
}

static QImage convertFromYUV(const QByteArray &array, int w, int h)
{
    QImage result(w, h, QImage::Format_RGB32);

    // TODO: bilinearly interpolate the U and V channels for better result

    for (int y = 0; y < h; ++y) {
        uint *sp = (uint *)result.scanLine(y);

        const uchar *yp = (const uchar *)(array.constData() + y * w);
        const uchar *up = (const uchar *)(array.constData() + w * h + (y/2)*(w/2));
        const uchar *vp = (const uchar *)(array.constData() + w * h * 5/4 + (y/2)*(w/2));

        for (int x = 0; x < w; ++x) {
            const int sy = *yp;
            const int su = *up;
            const int sv = *vp;

            const int R = int(1.164 * (sy - 16) + 1.596 * (sv - 128));
            const int G = int(1.164 * (sy - 16) - 0.813 * (sv - 128) - 0.391 * (su - 128));
            const int B = int(1.164 * (sy - 16)                      + 2.018 * (su - 128));

            *sp = qRgb(qBound(0, R, 255),
                       qBound(0, G, 255),
                       qBound(0, B, 255));

            ++yp;
            ++sp;
            if (x & 1) {
                ++up;
                ++vp;
            }
        }
    }
    return result;
}

const QImage &GLRenderWidgetImplementation::currentFrame() const
{
    if (m_frame.isNull() && !m_array.isNull())
        m_frame = convertFromYUV(m_array, m_width, m_height);

    return m_frame;
}

#ifndef GL_FRAGMENT_PROGRAM_ARB
#define GL_FRAGMENT_PROGRAM_ARB           0x8804
#define GL_PROGRAM_FORMAT_ASCII_ARB       0x8875
#endif

// arbfp1 fragment program for converting yuv to rgb
const char *const yuvToRgb =
    "!!ARBfp1.0"
    "PARAM c[3] = { { 0.5, 0.0625 },"
    "{ 1.164, 0, 1.596, 2.0179999 },"
    "{ 1.164, -0.391, -0.81300002 } };"
    "TEMP R0;"
    "TEMP R1;"
    "TEX R0.x, fragment.texcoord[0], texture[2], 2D;"
    "ADD R1.z, R0.x, -c[0].x;"
    "TEX R1.x, fragment.texcoord[0], texture[0], 2D;"
    "TEX R0.x, fragment.texcoord[0], texture[1], 2D;"
    "ADD R1.x, R1, -c[0].y;"
    "ADD R1.y, R0.x, -c[0].x;"
    "DP3 result.color.x, R1, c[1];"
    "DP3 result.color.y, R1, c[2];"
    "DP3 result.color.z, R1, c[1].xwyw;"
    "END";

GLRenderWidgetImplementation::GLRenderWidgetImplementation(VideoWidget*videoWidget, const QGLFormat &format) :
        QGLWidget(format, videoWidget)
        , m_program(0)
        , m_yuvSupport(false)
        , m_videoWidget(videoWidget)
{
    makeCurrent();
    glGenTextures(3, m_texture);

    glProgramStringARB = (_glProgramStringARB) context()->getProcAddress(QLatin1String("glProgramStringARB"));
    glBindProgramARB = (_glBindProgramARB) context()->getProcAddress(QLatin1String("glBindProgramARB"));
    glDeleteProgramsARB = (_glDeleteProgramsARB) context()->getProcAddress(QLatin1String("glDeleteProgramsARB"));
    glGenProgramsARB = (_glGenProgramsARB) context()->getProcAddress(QLatin1String("glGenProgramsARB"));
    glActiveTexture = (_glActiveTexture) context()->getProcAddress(QLatin1String("glActiveTexture"));

    m_hasPrograms = glProgramStringARB && glBindProgramARB && glDeleteProgramsARB && glGenProgramsARB && glActiveTexture;

    if (m_hasPrograms) {
        glGenProgramsARB(1, &m_program);
        glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, m_program);

        const GLbyte *gl_src = reinterpret_cast<const GLbyte *>(yuvToRgb);
        glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB,
                           int(strlen(yuvToRgb)), gl_src);

        if (glGetError() != GL_NO_ERROR) {
            glDeleteProgramsARB(1, &m_program);
            m_hasPrograms = false;
        } else {
            m_yuvSupport = true;
        }
    }

    QPalette palette;
    palette.setColor(QPalette::Background, Qt::black);
    setPalette(palette);
    setAutoFillBackground(true);
    // Videowidget allways have this property to allow hiding the mouse cursor
    setMouseTracking(true);
}

void GLRenderWidgetImplementation::updateTexture(const QByteArray &array, int width, int height)
{
    m_width = width;
    m_height = height;

    makeCurrent();

    int w[3] = { width, width/2, width/2 };
    int h[3] = { height, height/2, height/2 };
    int offs[3] = { 0, width*height, width*height*5/4 };

    for (int i = 0; i < 3; ++i) {
        glBindTexture(GL_TEXTURE_2D, m_texture[i]);
        glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, w[i], h[i], 0,
                     GL_LUMINANCE, GL_UNSIGNED_BYTE, array.data() + offs[i]);

        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
    }
}

void GLRenderWidgetImplementation::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    m_drawFrameRect = m_videoWidget->calculateDrawFrameRect();
    if (m_yuvSupport && frameIsSet()) {
        glEnable(GL_FRAGMENT_PROGRAM_ARB);
        glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, m_program);
        const float tx_array[] = { 0, 0, 1, 0, 1, 1, 0, 1};
        const QRectF r = drawFrameRect();

        const float v_array[] = { float(r.left()), float(r.top()), float(r.right()), float(r.top()), float(r.right()), float(r.bottom()), float(r.left()), float(r.bottom()) };

        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, m_texture[0]);
        glActiveTexture(GL_TEXTURE1);
        glBindTexture(GL_TEXTURE_2D, m_texture[1]);
        glActiveTexture(GL_TEXTURE2);
        glBindTexture(GL_TEXTURE_2D, m_texture[2]);
        glActiveTexture(GL_TEXTURE0);

        glVertexPointer(2, GL_FLOAT, 0, v_array);
        glTexCoordPointer(2, GL_FLOAT, 0, tx_array);
        glEnableClientState(GL_VERTEX_ARRAY);
        glEnableClientState(GL_TEXTURE_COORD_ARRAY);
        glDrawArrays(GL_QUADS, 0, 4);
        glDisableClientState(GL_TEXTURE_COORD_ARRAY);
        glDisableClientState(GL_VERTEX_ARRAY);

        glDisable(GL_FRAGMENT_PROGRAM_ARB);
    } else {
        painter.setRenderHint(QPainter::SmoothPixmapTransform);
        painter.drawImage(drawFrameRect(), currentFrame());
    }

    frameRendered();
}
}
} //namespace Phonon::Gstreamer

QT_END_NAMESPACE

#endif // QT_OPENGL_ES
#endif // QT_NO_OPENGL