silence dbus-send output
[harmattan/cameraplus] / lib / qtcamviewfinderrenderermeego.cpp
1 /*!
2  * This file is part of CameraPlus.
3  *
4  * Copyright (C) 2012-2013 Mohammed Sameer <msameer@foolab.org>
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
19  */
20
21 #include "qtcamviewfinderrenderermeego.h"
22 #include <QDebug>
23 #include <gst/video/video.h>
24 #include <QPainter>
25 #include "qtcamconfig.h"
26 #include <QX11Info>
27 #include <QGLContext>
28 #include <QGLShaderProgram>
29 #include <gst/interfaces/meegovideotexture.h>
30
31 QT_CAM_VIEWFINDER_RENDERER(RENDERER_TYPE_MEEGO, QtCamViewfinderRendererMeeGo);
32
33 #define GL_TEXTURE_EXTERNAL_OES                  0x8060
34
35 typedef void *EGLSyncKHR;
36 #define EGL_SYNC_FENCE_KHR                       0x30F9
37
38 typedef EGLSyncKHR(EGLAPIENTRYP _PFNEGLCREATESYNCKHRPROC)(EGLDisplay dpy, EGLenum type,
39                                                           const EGLint *attrib_list);
40
41 _PFNEGLCREATESYNCKHRPROC eglCreateSyncKHR = 0;
42
43 static const QString FRAGMENT_SHADER = ""
44     "#extension GL_OES_EGL_image_external: enable\n"
45     "uniform samplerExternalOES texture0;"
46     "varying lowp vec2 fragTexCoord;"
47     "void main() {"
48     "  gl_FragColor = texture2D(texture0, fragTexCoord);"
49     "}"
50   "";
51
52 static const QString VERTEX_SHADER = ""
53     "attribute highp vec4 inputVertex;"
54     "attribute lowp vec2 textureCoord;"
55     "uniform highp mat4 matrix;"
56     "uniform highp mat4 matrixWorld;"
57     "varying lowp vec2 fragTexCoord;"
58     ""
59     "void main() {"
60     "  gl_Position = matrix * matrixWorld * inputVertex;"
61     "  fragTexCoord = textureCoord;"
62     "}"
63   "";
64
65 QtCamViewfinderRendererMeeGo::QtCamViewfinderRendererMeeGo(QtCamConfig *config,
66                                                            QObject *parent) :
67   QtCamViewfinderRenderer(config, parent),
68   m_conf(config),
69   m_sink(0),
70   m_frame(-1),
71   m_id(0),
72   m_notify(0),
73   m_needsInit(true),
74   m_program(0) {
75
76   // Texture coordinates:
77   // Reversed because of Qt reversed coordinate system
78   m_texCoords[0] = 0;       m_texCoords[1] = 1;
79   m_texCoords[2] = 1;       m_texCoords[3] = 1;
80   m_texCoords[4] = 1;       m_texCoords[5] = 0;
81   m_texCoords[6] = 0;       m_texCoords[7] = 0;
82
83   bzero(&m_vertexCoords, 8);
84 }
85
86 QtCamViewfinderRendererMeeGo::~QtCamViewfinderRendererMeeGo() {
87   if (m_sink) {
88     g_signal_handler_disconnect(m_sink, m_id);
89     g_signal_handler_disconnect(m_sink, m_notify);
90     g_object_remove_toggle_ref(G_OBJECT(m_sink), (GToggleNotify)sink_notify, this);
91     m_sink = 0;
92   }
93 }
94
95 bool QtCamViewfinderRendererMeeGo::needsNativePainting() {
96   return true;
97 }
98
99 void QtCamViewfinderRendererMeeGo::paint(const QMatrix4x4& matrix, const QRectF& viewport) {
100   QMutexLocker locker(&m_frameMutex);
101   if (m_frame == -1) {
102     return;
103   }
104
105   if (m_needsInit) {
106     calculateProjectionMatrix(viewport);
107
108     if (!eglCreateSyncKHR && m_conf->viewfinderUseFence()) {
109       eglCreateSyncKHR = (_PFNEGLCREATESYNCKHRPROC)eglGetProcAddress("eglCreateSyncKHR");
110
111       if (!eglCreateSyncKHR) {
112         qWarning() << "eglCreateSyncKHR not found. Fences disabled";
113       }
114     }
115
116     m_needsInit = false;
117   }
118
119   if (!m_program) {
120     // Program will be created if needed and will never be deleted even
121     // if attaching the shaders fail.
122     createProgram();
123   }
124
125   paintFrame(matrix, m_frame);
126 }
127
128 void QtCamViewfinderRendererMeeGo::resize(const QSizeF& size) {
129   if (size == m_size) {
130     return;
131   }
132
133   m_size = size;
134
135   m_renderArea = QRectF();
136
137   calculateCoords();
138
139   // This will destroy everything
140   // but we need a way to reset the viewport and the transformation matrix only.
141   m_needsInit = true;
142
143   emit renderAreaChanged();
144 }
145
146 void QtCamViewfinderRendererMeeGo::reset() {
147   QMutexLocker locker(&m_frameMutex);
148   m_frame = -1;
149 }
150
151 GstElement *QtCamViewfinderRendererMeeGo::sinkElement() {
152   if (!QGLContext::currentContext()) {
153     qCritical() << "Cannot create the GStreamer element without an OpenGL context.";
154     return 0;
155   }
156
157   if (!m_sink) {
158     m_sink = gst_element_factory_make(m_conf->viewfinderSink().toLatin1().data(),
159                                       "QtCamViewfinderRendererMeeGoSink");
160     if (!m_sink) {
161       qCritical() << "Failed to create" << m_conf->viewfinderSink();
162       return 0;
163     }
164
165     g_object_add_toggle_ref(G_OBJECT(m_sink), (GToggleNotify)sink_notify, this);
166   }
167
168   Display *d = QX11Info::display();
169   g_object_set(G_OBJECT(m_sink), "x-display", d, "use-framebuffer-memory", TRUE, NULL);
170
171   m_dpy = eglGetDisplay((EGLNativeDisplayType)d);
172   if (m_dpy == EGL_NO_DISPLAY) {
173     qCritical() << "Failed to obtain EGL Display";
174   }
175
176   EGLContext context = eglGetCurrentContext();
177   if (context == EGL_NO_CONTEXT) {
178     qCritical() << "Failed to obtain EGL context";
179   }
180
181   g_object_set(G_OBJECT(m_sink), "egl-display", m_dpy, "egl-context", context, NULL);
182
183   m_id = g_signal_connect(G_OBJECT(m_sink), "frame-ready", G_CALLBACK(frame_ready), this);
184
185   GstPad *pad = gst_element_get_static_pad(m_sink, "sink");
186   m_notify = g_signal_connect(G_OBJECT(pad), "notify::caps",
187                               G_CALLBACK(sink_caps_changed), this);
188   gst_object_unref(pad);
189
190   return m_sink;
191 }
192
193 void QtCamViewfinderRendererMeeGo::frame_ready(GstElement *sink, int frame,
194                                                QtCamViewfinderRendererMeeGo *r) {
195   Q_UNUSED(sink);
196   Q_UNUSED(frame);
197
198   r->m_frameMutex.lock();
199   r->m_frame = frame;
200   r->m_frameMutex.unlock();
201
202   QMetaObject::invokeMethod(r, "updateRequested", Qt::QueuedConnection);
203 }
204
205 void QtCamViewfinderRendererMeeGo::sink_notify(QtCamViewfinderRendererMeeGo *q,
206                                                GObject *object, gboolean is_last_ref) {
207
208   Q_UNUSED(object);
209
210   if (is_last_ref) {
211     g_signal_handler_disconnect(q->m_sink, q->m_id);
212     g_object_remove_toggle_ref(G_OBJECT(q->m_sink), (GToggleNotify)sink_notify, q);
213     q->m_sink = 0;
214   }
215 }
216
217 void QtCamViewfinderRendererMeeGo::sink_caps_changed(GObject *obj, GParamSpec *pspec,
218                                                      QtCamViewfinderRendererMeeGo *q) {
219   Q_UNUSED(obj);
220   Q_UNUSED(pspec);
221
222   int width, height;
223   if (obj && gst_video_get_size(GST_PAD(obj), &width, &height)) {
224     QMetaObject::invokeMethod(q, "setVideoSize", Qt::QueuedConnection,
225                               Q_ARG(QSizeF, QSizeF(width, height)));
226   }
227 }
228
229 void QtCamViewfinderRendererMeeGo::calculateProjectionMatrix(const QRectF& rect) {
230   m_projectionMatrix = QMatrix4x4();
231   m_projectionMatrix.ortho(rect);
232 }
233
234 void QtCamViewfinderRendererMeeGo::createProgram() {
235   if (m_program) {
236     delete m_program;
237   }
238
239   m_program = new QGLShaderProgram(this);
240
241   if (!m_program->addShaderFromSourceCode(QGLShader::Vertex, VERTEX_SHADER)) {
242     qCritical() << "Failed to add vertex shader";
243     return;
244   }
245
246   if (!m_program->addShaderFromSourceCode(QGLShader::Fragment, FRAGMENT_SHADER)) {
247     qCritical() << "Failed to add fragment shader";
248     return;
249   }
250
251   m_program->bindAttributeLocation("inputVertex", 0);
252   m_program->bindAttributeLocation("textureCoord", 1);
253
254   if (!m_program->link()) {
255     qCritical() << "Failed to link program!";
256     return;
257   }
258
259   if (!m_program->bind()) {
260     qCritical() << "Failed to bind program";
261     return;
262   }
263
264   m_program->setUniformValue("texture0", 0); // texture UNIT 0
265   m_program->release();
266 }
267
268 void QtCamViewfinderRendererMeeGo::paintFrame(const QMatrix4x4& matrix, int frame) {
269   EGLSyncKHR sync = 0;
270
271   if (frame == -1) {
272     return;
273   }
274
275   MeegoGstVideoTexture *sink = MEEGO_GST_VIDEO_TEXTURE(m_sink);
276   if (!meego_gst_video_texture_acquire_frame(sink, frame)) {
277     qDebug() << "Failed to acquire frame";
278     return;
279   }
280
281   m_program->bind();
282
283   m_program->setUniformValue("matrix", m_projectionMatrix);
284   m_program->setUniformValue("matrixWorld", matrix);
285
286   if (!meego_gst_video_texture_bind_frame(sink, GL_TEXTURE_EXTERNAL_OES, frame)) {
287     qDebug() << "Failed to bind frame";
288     m_program->release();
289     return;
290   }
291
292   glEnableVertexAttribArray(0);
293   glEnableVertexAttribArray(1);
294
295   glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, &m_vertexCoords);
296   glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, &m_texCoords);
297
298   glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
299
300   if (!meego_gst_video_texture_bind_frame(sink, GL_TEXTURE_EXTERNAL_OES, -1)) {
301     qDebug() << "Failed to unbind frame";
302   }
303
304   glDisableVertexAttribArray(1);
305   glDisableVertexAttribArray(0);
306
307   m_program->release();
308
309   if (eglCreateSyncKHR) {
310     sync = eglCreateSyncKHR(m_dpy, EGL_SYNC_FENCE_KHR, NULL);
311   }
312
313   meego_gst_video_texture_release_frame(sink, frame, sync);
314 }
315
316 void QtCamViewfinderRendererMeeGo::calculateCoords() {
317   if (!m_size.isValid() || !m_videoSize.isValid()) {
318     return;
319   }
320
321   QRectF area = renderArea();
322
323   qreal leftMargin = area.x();
324   qreal topMargin = area.y();
325   QSizeF renderSize = area.size();
326
327   m_vertexCoords[0] = leftMargin;
328   m_vertexCoords[1] = topMargin + renderSize.height();
329
330   m_vertexCoords[2] = renderSize.width() + leftMargin;
331   m_vertexCoords[3] = topMargin + renderSize.height();
332
333   m_vertexCoords[4] = renderSize.width() + leftMargin;
334   m_vertexCoords[5] = topMargin;
335
336   m_vertexCoords[6] = leftMargin;
337   m_vertexCoords[7] = topMargin;
338 }
339
340 QRectF QtCamViewfinderRendererMeeGo::renderArea() {
341   if (!m_renderArea.isNull()) {
342     return m_renderArea;
343   }
344
345   QSizeF renderSize = m_videoSize;
346   renderSize.scale(m_size, Qt::KeepAspectRatio);
347
348   qreal leftMargin = (m_size.width() - renderSize.width())/2.0;
349   qreal topMargin = (m_size.height() - renderSize.height())/2.0;
350
351   m_renderArea = QRectF(QPointF(leftMargin, topMargin), renderSize);
352
353   return m_renderArea;
354 }
355
356 QSizeF QtCamViewfinderRendererMeeGo::videoResolution() {
357   return m_videoSize;
358 }
359
360 void QtCamViewfinderRendererMeeGo::setVideoSize(const QSizeF& size) {
361   if (size == m_videoSize) {
362     return;
363   }
364
365   m_videoSize = size;
366
367   m_renderArea = QRectF();
368
369   calculateCoords();
370
371   m_needsInit = true;
372
373   emit renderAreaChanged();
374   emit videoResolutionChanged();
375 }