glwidget.cpp 60.3 KB
Newer Older
1
/*
2
3
4
 * Copyright (c) 2011-2016 Meltytech, LLC
 * Original author: Dan Dennedy <dan@dennedy.org>
 * Modified for Kdenlive: Jean-Baptiste Mardelle
5
6
 *
 * GL shader based on BSD licensed code from Peter Bengtsson:
Yuri Chornoivan's avatar
Yuri Chornoivan committed
7
 * https://www.fourcc.org/source/YUV420P-OpenGL-GLSLang.c
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

23
#include <KDeclarative/KDeclarative>
24
#include <KMessageBox>
Laurent Montel's avatar
Laurent Montel committed
25
#include <QApplication>
Nicolas Carion's avatar
Nicolas Carion committed
26
#include <QOpenGLFunctions_3_2_Core>
Laurent Montel's avatar
Laurent Montel committed
27
#include <QPainter>
28
#include <QQmlContext>
Nicolas Carion's avatar
style    
Nicolas Carion committed
29
#include <QQuickItem>
30
#include <QFontDatabase>
31
#include <kdeclarative_version.h>
32
#include <KLocalizedContext>
33
#include <klocalizedstring.h>
34
35

#include "core.h"
Nicolas Carion's avatar
Nicolas Carion committed
36
#include "glwidget.h"
37
#include "kdenlivesettings.h"
38
#include "monitorproxy.h"
Nicolas Carion's avatar
linting    
Nicolas Carion committed
39
#include "profiles/profilemodel.hpp"
Nicolas Carion's avatar
style    
Nicolas Carion committed
40
#include "timeline2/view/qml/timelineitems.h"
Nicolas Carion's avatar
Nicolas Carion committed
41
#include <mlt++/Mlt.h>
42
#include <lib/localeHandling.h>
43

44
#ifndef GL_UNPACK_ROW_LENGTH
Nicolas Carion's avatar
Nicolas Carion committed
45
46
47
48
49
#ifdef GL_UNPACK_ROW_LENGTH_EXT
#define GL_UNPACK_ROW_LENGTH GL_UNPACK_ROW_LENGTH_EXT
#else
#error GL_UNPACK_ROW_LENGTH undefined
#endif
50
51
#endif

52
53
#if 1
#define check_error(fn) {}
54
#else
55
#define check_error(fn) { int err = fn->glGetError(); if (err != GL_NO_ERROR) { qCritical(KDENLIVE_LOG) << "GL error"  << hex << err << dec << "at" << __FILE__ << ":" << __LINE__; } }
56
#endif
57

58

59
60
61
62
63
64
#ifndef GL_TIMEOUT_IGNORED
#define GL_TIMEOUT_IGNORED 0xFFFFFFFFFFFFFFFFull
#endif

using namespace Mlt;

65
GLWidget::GLWidget(int id, QObject *parent)
66
67
68
69
70
    : QQuickView((QWindow *)parent)
    , sendFrameForAnalysis(false)
    , m_glslManager(nullptr)
    , m_consumer(nullptr)
    , m_producer(nullptr)
Vincent Pinon's avatar
Vincent Pinon committed
71
    , m_id(id)
72
    , m_rulerHeight(QFontInfo(QFontDatabase::systemFont(QFontDatabase::SmallestReadableFont)).pixelSize() * 1.5)
73
    , m_bgColor(KdenliveSettings::window_background())
Vincent Pinon's avatar
Vincent Pinon committed
74
    , m_shader(nullptr)
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
    , m_initSem(0)
    , m_analyseSem(1)
    , m_isInitialized(false)
    , m_threadStartEvent(nullptr)
    , m_threadStopEvent(nullptr)
    , m_threadCreateEvent(nullptr)
    , m_threadJoinEvent(nullptr)
    , m_displayEvent(nullptr)
    , m_frameRenderer(nullptr)
    , m_projectionLocation(0)
    , m_modelViewLocation(0)
    , m_vertexLocation(0)
    , m_texCoordLocation(0)
    , m_colorspaceLocation(0)
    , m_zoom(1.0f)
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
90
91
92
    , m_profileSize(1920, 1080)
    , m_colorSpace(601)
    , m_dar(1.78)
93
    , m_sendFrame(false)
94
95
    , m_isZoneMode(false)
    , m_isLoopMode(false)
96
    , m_loopIn(0)
97
98
    , m_offset(QPoint(0, 0))
    , m_fbo(nullptr)
99
    , m_shareContext(nullptr)
100
101
    , m_openGLSync(false)
    , m_ClientWaitSync(nullptr)
102
{
103
104
    KDeclarative::KDeclarative kdeclarative;
    kdeclarative.setupEngine(engine());
105
106
    KLocalizedContext *localizedContextObject = new KLocalizedContext(engine());
    engine()->rootContext()->setContextObject(localizedContextObject);
107

108
109
110
111
    m_texture[0] = m_texture[1] = m_texture[2] = 0;
    qRegisterMetaType<Mlt::Frame>("Mlt::Frame");
    qRegisterMetaType<SharedFrame>("SharedFrame");

112
113
114
115
116
    if (m_id == Kdenlive::ClipMonitor && !(KdenliveSettings::displayClipMonitorInfo() & 0x01)) {
        m_rulerHeight = 0;
    } else if (!(KdenliveSettings::displayProjectMonitorInfo() & 0x01)) {
        m_rulerHeight = 0;
    }
117
    m_displayRulerHeight = m_rulerHeight;
118

119
120
121
122
    setPersistentOpenGLContext(true);
    setPersistentSceneGraph(true);
    setClearBeforeRendering(false);
    setResizeMode(QQuickView::SizeRootObjectToView);
123
    m_offscreenSurface.setFormat(QOpenGLContext::globalShareContext()->format());
124
125
    m_offscreenSurface.create();

126
127
    m_refreshTimer.setSingleShot(true);
    m_refreshTimer.setInterval(50);
128
    m_blackClip.reset(new Mlt::Producer(pCore->getCurrentProfile()->profile(), "color:0"));
129
    m_blackClip->set("kdenlive:id", "black");
130
    m_blackClip->set("out", 3);
131
    connect(&m_refreshTimer, &QTimer::timeout, this, &GLWidget::refresh);
132
    m_producer = m_blackClip;
133
    rootContext()->setContextProperty("markersModel", nullptr);
134
135
    if (!initGPUAccel()) {
        disableGPUAccel();
Laurent Montel's avatar
Laurent Montel committed
136
    }
Corey O'Connor's avatar
Corey O'Connor committed
137

Laurent Montel's avatar
Laurent Montel committed
138
139
    connect(this, &QQuickWindow::sceneGraphInitialized, this, &GLWidget::initializeGL, Qt::DirectConnection);
    connect(this, &QQuickWindow::beforeRendering, this, &GLWidget::paintGL, Qt::DirectConnection);
140
    connect(pCore.get(), &Core::updateMonitorProfile, this, &GLWidget::reloadProfile);
Corey O'Connor's avatar
Corey O'Connor committed
141

142
143
144
    registerTimelineItems();
    m_proxy = new MonitorProxy(this);
    rootContext()->setContextProperty("controller", m_proxy);
145
146
147
148
}

GLWidget::~GLWidget()
{
149
    // C & D
150
151
152
153
154
    delete m_glslManager;
    delete m_threadStartEvent;
    delete m_threadStopEvent;
    delete m_threadCreateEvent;
    delete m_threadJoinEvent;
155
    delete m_displayEvent;
156
157
158
159
160
161
162
163
164
    if (m_frameRenderer) {
        if (m_frameRenderer->isRunning()) {
            QMetaObject::invokeMethod(m_frameRenderer, "cleanup");
            m_frameRenderer->quit();
            m_frameRenderer->wait();
            m_frameRenderer->deleteLater();
        } else {
            delete m_frameRenderer;
        }
165
    }
166
    m_blackClip.reset();
167
    delete m_shareContext;
168
    delete m_shader;
169
    // delete pCore->getCurrentProfile();
170
171
}

172
void GLWidget::updateAudioForAnalysis()
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
173
{
Laurent Montel's avatar
Laurent Montel committed
174
175
176
    if (m_frameRenderer) {
        m_frameRenderer->sendAudioForAnalysis = KdenliveSettings::monitor_audio();
    }
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
177
178
}

179
void GLWidget::initializeGL()
180
{
181
    if (m_isInitialized) return;
182

183
    openglContext()->makeCurrent(&m_offscreenSurface);
184
    initializeOpenGLFunctions();
185

186
    // C & D
187
    if (onlyGLESGPUAccel()) {
188
        disableGPUAccel();
189
    }
190

191
192
    createShader();

193
    m_openGLSync = initGPUAccelSync();
194

195
    // C & D
196
197
198
199
200
    if (m_glslManager) {
        // Create a context sharing with this context for the RenderThread context.
        // This is needed because openglContext() is active in another thread
        // at the time that RenderThread is created.
        // See this Qt bug for more info: https://bugreports.qt.io/browse/QTBUG-44677
Corey O'Connor's avatar
Corey O'Connor committed
201
        // TODO: QTBUG-44677 is closed. still applicable?
202
203
204
205
206
        m_shareContext = new QOpenGLContext;
        m_shareContext->setFormat(openglContext()->format());
        m_shareContext->setShareContext(openglContext());
        m_shareContext->create();
    }
207

208
    m_frameRenderer = new FrameRenderer(openglContext(), &m_offscreenSurface, m_ClientWaitSync);
209

210
    m_frameRenderer->sendAudioForAnalysis = KdenliveSettings::monitor_audio();
Corey O'Connor's avatar
Corey O'Connor committed
211

212
    openglContext()->makeCurrent(this);
213
214
    connect(m_frameRenderer, &FrameRenderer::textureReady, this, &GLWidget::updateTexture, Qt::DirectConnection);
    connect(m_frameRenderer, &FrameRenderer::frameDisplayed, this, &GLWidget::onFrameDisplayed, Qt::QueuedConnection);
215
    connect(m_frameRenderer, &FrameRenderer::frameDisplayed, this, &GLWidget::frameDisplayed, Qt::QueuedConnection);
216
    m_initSem.release();
217
    m_isInitialized = true;
218
    reconfigure();
219
220
221
222
223
}

void GLWidget::resizeGL(int width, int height)
{
    int x, y, w, h;
224
    height -= m_displayRulerHeight;
Nicolas Carion's avatar
Nicolas Carion committed
225
    double this_aspect = (double)width / height;
226

227
    // Special case optimization to negate odd effect of sample aspect ratio
228
    // not corresponding exactly with image resolution.
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
229
    if ((int)(this_aspect * 1000) == (int)(m_dar * 1000)) {
230
231
232
233
        w = width;
        h = height;
    }
    // Use OpenGL to normalise sample aspect ratio
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
234
    else if (height * m_dar > width) {
235
        w = width;
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
236
        h = width / m_dar;
Laurent Montel's avatar
Laurent Montel committed
237
    } else {
238
        w = height * m_dar;
239
240
241
242
243
        h = height;
    }
    x = (width - w) / 2;
    y = (height - h) / 2;
    m_rect.setRect(x, y, w, h);
Laurent Montel's avatar
Laurent Montel committed
244
    QQuickItem *rootQml = rootObject();
245
    if (rootQml) {
246
247
        QSize s = pCore->getCurrentFrameSize();
        double scalex = (double)m_rect.width() / s.width() * m_zoom;
248
        double scaley = (double)m_rect.height() / s.height() * m_zoom;
249
        rootQml->setProperty("center", m_rect.center());
250
251
        rootQml->setProperty("scalex", scalex);
        rootQml->setProperty("scaley", scaley);
252
        if (rootQml->objectName() == QLatin1String("rootsplit")) {
253
            // Adjust splitter pos
254
            rootQml->setProperty("splitterPos", x + (rootQml->property("percentage").toDouble() * w));
255
        }
256
    }
257
258
259
    emit rectChanged();
}

Laurent Montel's avatar
Laurent Montel committed
260
void GLWidget::resizeEvent(QResizeEvent *event)
261
262
{
    resizeGL(event->size().width(), event->size().height());
263
    QQuickView::resizeEvent(event);
264
265
}

266
267
268
269
270
271
272
273
274
275
276
void GLWidget::createGPUAccelFragmentProg()
{
    m_shader->addShaderFromSourceCode(QOpenGLShader::Fragment, "uniform sampler2D tex;"
                                                               "varying highp vec2 coordinates;"
                                                               "void main(void) {"
                                                               "  gl_FragColor = texture2D(tex, coordinates);"
                                                               "}");
    m_shader->link();
    m_textureLocation[0] = m_shader->uniformLocation("tex");
}

277
278
279
void GLWidget::createShader()
{
    m_shader = new QOpenGLShaderProgram;
Nicolas Carion's avatar
Nicolas Carion committed
280
281
282
283
284
285
286
287
288
    m_shader->addShaderFromSourceCode(QOpenGLShader::Vertex, "uniform highp mat4 projection;"
                                                             "uniform highp mat4 modelView;"
                                                             "attribute highp vec4 vertex;"
                                                             "attribute highp vec2 texCoord;"
                                                             "varying highp vec2 coordinates;"
                                                             "void main(void) {"
                                                             "  gl_Position = projection * modelView * vertex;"
                                                             "  coordinates = texCoord;"
                                                             "}");
289
    // C & D
290
    if (m_glslManager) {
291
        createGPUAccelFragmentProg();
292
    } else {
293
        // A & B
294
        createYUVTextureProjectFragmentProg();
295
    }
296

297
298
299
300
301
302
    m_projectionLocation = m_shader->uniformLocation("projection");
    m_modelViewLocation = m_shader->uniformLocation("modelView");
    m_vertexLocation = m_shader->attributeLocation("vertex");
    m_texCoordLocation = m_shader->attributeLocation("texCoord");
}

303
304
305
void GLWidget::createYUVTextureProjectFragmentProg()
{
    m_shader->addShaderFromSourceCode(QOpenGLShader::Fragment,
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
                                      "uniform sampler2D Ytex, Utex, Vtex;"
                                      "uniform lowp int colorspace;"
                                      "varying highp vec2 coordinates;"
                                      "void main(void) {"
                                      "  mediump vec3 texel;"
                                      "  texel.r = texture2D(Ytex, coordinates).r - 0.0625;" // Y
                                      "  texel.g = texture2D(Utex, coordinates).r - 0.5;"    // U
                                      "  texel.b = texture2D(Vtex, coordinates).r - 0.5;"    // V
                                      "  mediump mat3 coefficients;"
                                      "  if (colorspace == 601) {"
                                      "    coefficients = mat3("
                                      "      1.1643,  1.1643,  1.1643," // column 1
                                      "      0.0,    -0.39173, 2.017,"  // column 2
                                      "      1.5958, -0.8129,  0.0);"   // column 3
                                      "  } else {"                      // ITU-R 709
                                      "    coefficients = mat3("
                                      "      1.1643, 1.1643, 1.1643," // column 1
                                      "      0.0,   -0.213,  2.112,"  // column 2
                                      "      1.793, -0.533,  0.0);"   // column 3
                                      "  }"
                                      "  gl_FragColor = vec4(coefficients * texel, 1.0);"
                                      "}");
328
329
330
331
332
333
334
    m_shader->link();
    m_textureLocation[0] = m_shader->uniformLocation("Ytex");
    m_textureLocation[1] = m_shader->uniformLocation("Utex");
    m_textureLocation[2] = m_shader->uniformLocation("Vtex");
    m_colorspaceLocation = m_shader->uniformLocation("colorspace");
}

335
static void uploadTextures(QOpenGLContext *context, const SharedFrame &frame, GLuint texture[])
336
337
338
{
    int width = frame.get_image_width();
    int height = frame.get_image_height();
339
    const uint8_t *image = frame.get_image(mlt_image_yuv420p);
Laurent Montel's avatar
Laurent Montel committed
340
    QOpenGLFunctions *f = context->functions();
341

342
343
344
    // The planes of pixel data may not be a multiple of the default 4 bytes.
    f->glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

345
    // Upload each plane of YUV to a texture.
Nicolas Carion's avatar
Nicolas Carion committed
346
    if (texture[0] != 0u) {
347
        f->glDeleteTextures(3, texture);
Laurent Montel's avatar
Laurent Montel committed
348
    }
349
350
351
352
    check_error(f);
    f->glGenTextures(3, texture);
    check_error(f);

Laurent Montel's avatar
Laurent Montel committed
353
    f->glBindTexture(GL_TEXTURE_2D, texture[0]);
354
355
356
357
358
359
360
361
362
    check_error(f);
    f->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    check_error(f);
    f->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    check_error(f);
    f->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    check_error(f);
    f->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    check_error(f);
Nicolas Carion's avatar
Nicolas Carion committed
363
    f->glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, width, height, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, image);
364
365
    check_error(f);

Laurent Montel's avatar
Laurent Montel committed
366
    f->glBindTexture(GL_TEXTURE_2D, texture[1]);
367
368
369
370
371
372
373
374
375
    check_error(f);
    f->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    check_error(f);
    f->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    check_error(f);
    f->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    check_error(f);
    f->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    check_error(f);
Nicolas Carion's avatar
Nicolas Carion committed
376
    f->glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, width / 2, height / 2, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, image + width * height);
377
378
    check_error(f);

Laurent Montel's avatar
Laurent Montel committed
379
    f->glBindTexture(GL_TEXTURE_2D, texture[2]);
380
381
382
383
384
385
386
387
388
    check_error(f);
    f->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    check_error(f);
    f->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    check_error(f);
    f->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    check_error(f);
    f->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    check_error(f);
Nicolas Carion's avatar
Nicolas Carion committed
389
    f->glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, width / 2, height / 2, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, image + width * height + width / 2 * height / 2);
390
391
392
    check_error(f);
}

393
394
395
396
397
398
void GLWidget::clear()
{
    stopGlsl();
    update();
}

399
400
401
402
403
void GLWidget::releaseAnalyse()
{
    m_analyseSem.release();
}

404
405
bool GLWidget::acquireSharedFrameTextures()
{
406
    // A
407
    if ((m_glslManager == nullptr) && !openglContext()->supportsThreadedOpenGL()) {
408
        QMutexLocker locker(&m_contextSharedAccess);
409
        if (!m_sharedFrame.is_valid()) {
Corey O'Connor's avatar
Corey O'Connor committed
410
            return false;
411
412
        }
        uploadTextures(openglContext(), m_sharedFrame, m_texture);
413
    } else if (m_glslManager) {
414
        // C & D
415
        m_contextSharedAccess.lock();
416
        if (m_sharedFrame.is_valid()) {
417
            m_texture[0] = *((const GLuint *)m_sharedFrame.get_image(mlt_image_glsl_texture));
418
419
420
421
        }
    }

    if (!m_texture[0]) {
422
        // C & D
423
        if (m_glslManager) m_contextSharedAccess.unlock();
Corey O'Connor's avatar
Corey O'Connor committed
424
        return false;
425
    }
426

Corey O'Connor's avatar
Corey O'Connor committed
427
428
429
    return true;
}

430
431
void GLWidget::bindShaderProgram()
{
432
    m_shader->bind();
Corey O'Connor's avatar
Corey O'Connor committed
433

434
    // C & D
435
436
437
    if (m_glslManager) {
        m_shader->setUniformValue(m_textureLocation[0], 0);
    } else {
438
        // A & B
439
440
441
        m_shader->setUniformValue(m_textureLocation[0], 0);
        m_shader->setUniformValue(m_textureLocation[1], 1);
        m_shader->setUniformValue(m_textureLocation[2], 2);
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
442
        m_shader->setUniformValue(m_colorspaceLocation, m_colorSpace);
443
    }
Corey O'Connor's avatar
Corey O'Connor committed
444
445
}

446
447
void GLWidget::releaseSharedFrameTextures()
{
448
    // C & D
Corey O'Connor's avatar
Corey O'Connor committed
449
450
    if (m_glslManager) {
        glFinish();
451
        m_contextSharedAccess.unlock();
Corey O'Connor's avatar
Corey O'Connor committed
452
453
454
    }
}

455
456
bool GLWidget::initGPUAccel()
{
457
458
    if (!KdenliveSettings::gpu_accel()) return false;

459
    m_glslManager = new Mlt::Filter(pCore->getCurrentProfile()->profile(), "glsl.manager");
460
461
462
    return m_glslManager->is_valid();
}

463
464
// C & D
// TODO: insure safe, idempotent on all pipelines.
465
466
void GLWidget::disableGPUAccel()
{
467
468
469
470
471
472
473
474
    delete m_glslManager;
    m_glslManager = nullptr;
    KdenliveSettings::setGpu_accel(false);
    // Need to destroy MLT global reference to prevent filters from trying to use GPU.
    mlt_properties_set_data(mlt_global_properties(), "glslManager", nullptr, 0, nullptr, nullptr);
    emit gpuNotSupported();
}

475
476
bool GLWidget::onlyGLESGPUAccel() const
{
477
478
479
480
    return (m_glslManager != nullptr) && openglContext()->isOpenGLES();
}

#if defined(Q_OS_WIN)
481
482
bool GLWidget::initGPUAccelSync()
{
483
484
485
486
487
    // no-op
    // TODO: getProcAddress is not working on Windows?
    return false;
}
#else
488
489
bool GLWidget::initGPUAccelSync()
{
490
491
492
493
494
495
496
497
    if (!KdenliveSettings::gpu_accel()) return false;
    if (m_glslManager == nullptr) return false;
    if (!openglContext()->hasExtension("GL_ARB_sync")) return false;

    m_ClientWaitSync = (ClientWaitSync_fp)openglContext()->getProcAddress("glClientWaitSync");
    if (m_ClientWaitSync) {
        return true;
    } else {
498
        qWarning() << "no GL sync";
499
500
501
502
503
504
505
506
        // fallback on A || B
        // TODO: fallback on A || B || C?
        disableGPUAccel();
        return false;
    }
}
#endif

Corey O'Connor's avatar
Corey O'Connor committed
507
508
509
void GLWidget::paintGL()
{
    QOpenGLFunctions *f = openglContext()->functions();
510
511
    float width = this->width() * devicePixelRatio();
    float height = this->height() * devicePixelRatio();
Corey O'Connor's avatar
Corey O'Connor committed
512
513
514
515

    f->glDisable(GL_BLEND);
    f->glDisable(GL_DEPTH_TEST);
    f->glDepthMask(GL_FALSE);
516
    f->glViewport(0, (m_displayRulerHeight * devicePixelRatio() * 0.5 + 0.5), width, height);
Corey O'Connor's avatar
Corey O'Connor committed
517
    check_error(f);
518
    f->glClearColor(m_bgColor.redF(), m_bgColor.greenF(), m_bgColor.blueF(), 0);
Corey O'Connor's avatar
Corey O'Connor committed
519
520
521
    f->glClear(GL_COLOR_BUFFER_BIT);
    check_error(f);

522
    if (!acquireSharedFrameTextures()) return;
Corey O'Connor's avatar
Corey O'Connor committed
523
524
525
526
527
528
529
530
531
532
533

    // Bind textures.
    for (uint i = 0; i < 3; ++i) {
        if (m_texture[i] != 0u) {
            f->glActiveTexture(GL_TEXTURE0 + i);
            f->glBindTexture(GL_TEXTURE_2D, m_texture[i]);
            check_error(f);
        }
    }

    bindShaderProgram();
534
    check_error(f);
535
536
537

    // Setup an orthographic projection.
    QMatrix4x4 projection;
538
    projection.scale(2.0f / width, 2.0f / height);
539
    m_shader->setUniformValue(m_projectionLocation, projection);
540
    check_error(f);
541
542
543

    // Set model view.
    QMatrix4x4 modelView;
544
    if (!qFuzzyCompare(m_zoom, 1.0f)) {
Nicolas Carion's avatar
Nicolas Carion committed
545
        if ((offset().x() != 0) || (offset().y() != 0)) modelView.translate(-offset().x() * devicePixelRatio(), offset().y() * devicePixelRatio());
546
547
548
        modelView.scale(zoom(), zoom());
    }
    m_shader->setUniformValue(m_modelViewLocation, modelView);
549
    check_error(f);
550
551
552
553
554

    // Provide vertices of triangle strip.
    QVector<QVector2D> vertices;
    width = m_rect.width() * devicePixelRatio();
    height = m_rect.height() * devicePixelRatio();
555
556
557
558
    vertices << QVector2D(-width / 2.0f, -height / 2.0f);
    vertices << QVector2D(-width / 2.0f, height / 2.0f);
    vertices << QVector2D(width / 2.0f, -height / 2.0f);
    vertices << QVector2D(width / 2.0f, height / 2.0f);
559
    m_shader->enableAttributeArray(m_vertexLocation);
560
    check_error(f);
561
    m_shader->setAttributeArray(m_vertexLocation, vertices.constData());
562
    check_error(f);
563
564
565
566
567
568
569
570

    // Provide texture coordinates.
    QVector<QVector2D> texCoord;
    texCoord << QVector2D(0.0f, 1.0f);
    texCoord << QVector2D(0.0f, 0.0f);
    texCoord << QVector2D(1.0f, 1.0f);
    texCoord << QVector2D(1.0f, 0.0f);
    m_shader->enableAttributeArray(m_texCoordLocation);
571
    check_error(f);
572
    m_shader->setAttributeArray(m_texCoordLocation, texCoord.constData());
573
    check_error(f);
574
575

    // Render
576
    glDrawArrays(GL_TRIANGLE_STRIP, 0, vertices.size());
577
    check_error(f);
578

579
    if (m_sendFrame && m_analyseSem.tryAcquire(1)) {
580
        // Render RGB frame for analysis
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
581
        if ((m_fbo == nullptr) || m_fbo->size() != m_profileSize) {
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
582
            delete m_fbo;
583
            QOpenGLFramebufferObjectFormat fmt;
584
            fmt.setSamples(1);
Nicolas Carion's avatar
Nicolas Carion committed
585
            fmt.setInternalTextureFormat(GL_RGB);                             // GL_RGBA32F);  // which one is the fastest ?
586
            m_fbo = new QOpenGLFramebufferObject(m_profileSize.width(), m_profileSize.height(), fmt); // GL_TEXTURE_2D);
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
587
588
        }
        m_fbo->bind();
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
589
        glViewport(0, 0, m_profileSize.width(), m_profileSize.height());
590
591

        QMatrix4x4 projection2;
Vincent Pinon's avatar
Vincent Pinon committed
592
        projection2.scale(2.0f / (float)width, 2.0f / (float)height);
593
594
        m_shader->setUniformValue(m_projectionLocation, projection2);

595
        glDrawArrays(GL_TRIANGLE_STRIP, 0, vertices.size());
596
        check_error(f);
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
597
598
        m_fbo->release();
        emit analyseFrame(m_fbo->toImage());
599
        m_sendFrame = false;
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
600
    }
601
602
603
604
    // Cleanup
    m_shader->disableAttributeArray(m_vertexLocation);
    m_shader->disableAttributeArray(m_texCoordLocation);
    m_shader->release();
605
    for (uint i = 0; i < 3; ++i) {
Nicolas Carion's avatar
Nicolas Carion committed
606
        if (m_texture[i] != 0u) {
607
608
            f->glActiveTexture(GL_TEXTURE0 + i);
            f->glBindTexture(GL_TEXTURE_2D, 0);
609
            check_error(f);
610
611
        }
    }
612
    glActiveTexture(GL_TEXTURE0);
613
    check_error(f);
Corey O'Connor's avatar
Corey O'Connor committed
614
615
616

    releaseSharedFrameTextures();
    check_error(f);
617
618
}

619
void GLWidget::slotZoom(bool zoomIn)
620
{
621
622
    if (zoomIn) {
        if (qFuzzyCompare(m_zoom, 1.0f)) {
Nicolas Carion's avatar
Nicolas Carion committed
623
624
625
626
627
628
            setZoom(2.0f);
        } else if (qFuzzyCompare(m_zoom, 2.0f)) {
            setZoom(3.0f);
        } else if (m_zoom < 1.0f) {
            setZoom(m_zoom * 2);
        }
629
630
631
632
633
634
635
    } else {
        if (qFuzzyCompare(m_zoom, 3.0f)) {
            setZoom(2.0);
        } else if (qFuzzyCompare(m_zoom, 2.0f)) {
            setZoom(1.0);
        } else if (m_zoom > 0.2) {
            setZoom(m_zoom / 2);
636
        }
637
638
639
    }
}

640
641
642
643
644
645
void GLWidget::updateRulerHeight(int addedHeight)
{
    m_displayRulerHeight =  m_rulerHeight > 0 ? QFontInfo(QFontDatabase::systemFont(QFontDatabase::SmallestReadableFont)).pixelSize() * 1.5 + addedHeight : 0;
    resizeGL(width(), height());
}

646
void GLWidget::requestSeek(int position)
647
{
648
    m_consumer->set("scrub_audio", 1);
649
650
651
    m_producer->seek(position);
    if (!qFuzzyIsNull(m_producer->get_speed())) {
        m_consumer->purge();
652
    }
653
    restartConsumer();
654
    m_consumer->set("refresh", 1);
655
656
}

657
658
void GLWidget::requestRefresh()
{
659
    if (m_producer && qFuzzyIsNull(m_producer->get_speed())) {
660
        m_consumer->set("scrub_audio", 0);
661
662
663
664
        m_refreshTimer.start();
    }
}

665
666
667
668
669
QString GLWidget::frameToTime(int frames) const
{
    return m_consumer ? m_consumer->frames_to_time(frames, mlt_time_smpte_df) : QStringLiteral("-");
}

670
671
672
void GLWidget::refresh()
{
    m_refreshTimer.stop();
673
    QMutexLocker locker(&m_mltMutex);
674
    restartConsumer();
675
676
677
    m_consumer->set("refresh", 1);
}

678
bool GLWidget::checkFrameNumber(int pos, int offset, bool isPlaying)
679
{
680
    const double speed = m_producer->get_speed();
681
    m_proxy->positionFromConsumer(pos, isPlaying);
682
    int maxPos = m_producer->get_int("out");
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
683
    if (m_isLoopMode || m_isZoneMode) {
684
        if (isPlaying && pos >= maxPos) {
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
685
686
687
            m_consumer->purge();
            if (!m_isLoopMode) {
                return false;
688
            }
689
            m_producer->seek(m_isZoneMode ? m_proxy->zoneIn() : m_loopIn);
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
690
691
692
            m_producer->set_speed(1.0);
            m_consumer->set("refresh", 1);
            return true;
693
        }
694
        return true;
695
    } else if (isPlaying) {
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
696
        maxPos -= offset;
697
        if (pos >= (maxPos - 1) && !(speed < 0.)) {
698
            // Playing past last clip, pause
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
699
700
701
            m_producer->set_speed(0);
            m_consumer->set("refresh", 0);
            m_consumer->purge();
702
            m_proxy->setPosition(qMax(0, maxPos));
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
703
            m_producer->seek(qMax(0, maxPos));
704
705
706
707
708
709
            return false;
        } else if (pos <= 0 && speed < 0.) {
            // rewinding reached 0, pause
            m_producer->set_speed(0);
            m_consumer->set("refresh", 0);
            m_consumer->purge();
710
            m_proxy->setPosition(0);
711
            m_producer->seek(0);
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
712
713
            return false;
        }
714
    }
715
    return isPlaying;
716
717
}

Laurent Montel's avatar
Laurent Montel committed
718
void GLWidget::mousePressEvent(QMouseEvent *event)
719
{
Nicolas Carion's avatar
Nicolas Carion committed
720
721
    if ((rootObject() != nullptr) && rootObject()->objectName() != QLatin1String("root") && !(event->modifiers() & Qt::ControlModifier) &&
        !(event->buttons() & Qt::MiddleButton)) {
722
        event->ignore();
723
        QQuickView::mousePressEvent(event);
724
725
        return;
    }
Nicolas Carion's avatar
Nicolas Carion committed
726
    if ((event->button() & Qt::LeftButton) != 0u) {
727
        if ((event->modifiers() & Qt::ControlModifier) != 0u) {
728
729
730
731
732
733
            // Pan view
            m_panStart = event->pos();
            setCursor(Qt::ClosedHandCursor);
        } else {
            m_dragStart = event->pos();
        }
Nicolas Carion's avatar
Nicolas Carion committed
734
    } else if ((event->button() & Qt::RightButton) != 0u) {
735
        emit showContextMenu(event->globalPos());
Nicolas Carion's avatar
Nicolas Carion committed
736
    } else if ((event->button() & Qt::MiddleButton) != 0u) {
737
738
        m_panStart = event->pos();
        setCursor(Qt::ClosedHandCursor);
739
    }
740
    event->accept();
741
    QQuickView::mousePressEvent(event);
742
743
}

Laurent Montel's avatar
Laurent Montel committed
744
void GLWidget::mouseMoveEvent(QMouseEvent *event)
745
{
Nicolas Carion's avatar
Nicolas Carion committed
746
747
    if ((rootObject() != nullptr) && rootObject()->objectName() != QLatin1String("root") && !(event->modifiers() & Qt::ControlModifier) &&
        !(event->buttons() & Qt::MiddleButton)) {
748
        event->ignore();
749
        QQuickView::mouseMoveEvent(event);
750
751
        return;
    }
752
    /*    if (event->modifiers() == Qt::ShiftModifier && m_producer) {
753
754
755
        emit seekTo(m_producer->get_length() *  event->x() / width());
        return;
    }*/
756
757
758
759
760
761
762
763
    QQuickView::mouseMoveEvent(event);
    if (!m_panStart.isNull()) {
        emit panView(m_panStart - event->pos());
        m_panStart = event->pos();
        event->accept();
        QQuickView::mouseMoveEvent(event);
        return;
    }
Laurent Montel's avatar
Laurent Montel committed
764
    if (!(event->buttons() & Qt::LeftButton)) {
765
        QQuickView::mouseMoveEvent(event);
766
        return;
Laurent Montel's avatar
Laurent Montel committed
767
    }
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
768
    if (!event->isAccepted() && !m_dragStart.isNull() && (event->pos() - m_dragStart).manhattanLength() >= QApplication::startDragDistance()) {
769
770
771
        m_dragStart = QPoint();
        emit startDrag();
    }
772
773
}

Laurent Montel's avatar
Laurent Montel committed
774
void GLWidget::keyPressEvent(QKeyEvent *event)
775
{
776
    QQuickView::keyPressEvent(event);
777
778
779
    if (!event->isAccepted()) {
        emit passKeyEvent(event);
    }
780
781
782
783
784
785
}

void GLWidget::createThread(RenderThread **thread, thread_function_t function, void *data)
{
#ifdef Q_OS_WIN
    // On Windows, MLT event consumer-thread-create is fired from the Qt main thread.
Laurent Montel's avatar
Laurent Montel committed
786
    while (!m_isInitialized) {
787
        qApp->processEvents();
Laurent Montel's avatar
Laurent Montel committed
788
    }
789
790
791
792
793
#else
    if (!m_isInitialized) {
        m_initSem.acquire();
    }
#endif
Vincent Pinon's avatar
Vincent Pinon committed
794
    (*thread) = new RenderThread(function, data, m_shareContext, &m_offscreenSurface);
795
796
797
    (*thread)->start();
}

Nicolas Carion's avatar
Nicolas Carion committed
798
static void onThreadCreate(mlt_properties owner, GLWidget *self, RenderThread **thread, int *priority, thread_function_t function, void *data)
799
800
801
{
    Q_UNUSED(owner)
    Q_UNUSED(priority)
Nicolas Carion's avatar
Nicolas Carion committed
802
    // self->clearFrameRenderer();
803
    self->createThread(thread, function, data);
804
    self->lockMonitor();
805
806
}

Laurent Montel's avatar
Laurent Montel committed
807
static void onThreadJoin(mlt_properties owner, GLWidget *self, RenderThread *thread)
808
809
810
811
812
813
{
    Q_UNUSED(owner)
    if (thread) {
        thread->quit();
        thread->wait();
        delete thread;
Nicolas Carion's avatar
Nicolas Carion committed
814
        // self->clearFrameRenderer();
815
        self->releaseMonitor();
816
817
818
819
820
    }
}

void GLWidget::startGlsl()
{
821
    // C & D
822
    if (m_glslManager) {
Nicolas Carion's avatar
Nicolas Carion committed
823
        // clearFrameRenderer();
824
        m_glslManager->fire_event("init glsl");
Nicolas Carion's avatar
Nicolas Carion committed
825
        if (m_glslManager->get_int("glsl_supported") == 0) {
826
            disableGPUAccel();
Laurent Montel's avatar
Laurent Montel committed
827
        } else {
828
829
830
831
832
            emit started();
        }
    }
}

Laurent Montel's avatar
Laurent Montel committed
833
static void onThreadStarted(mlt_properties owner, GLWidget *self)
834
835
836
837
838
{
    Q_UNUSED(owner)
    self->startGlsl();
}

839
840
841
842
843
844
845
846
847
848
void GLWidget::releaseMonitor()
{
    emit lockMonitor(false);
}

void GLWidget::lockMonitor()
{
    emit lockMonitor(true);
}

849
850
void GLWidget::stopGlsl()
{
Laurent Montel's avatar
Laurent Montel committed
851
    if (m_consumer) {
852
        m_consumer->purge();
Laurent Montel's avatar
Laurent Montel committed
853
    }
854

855
    // C & D
Nicolas Carion's avatar
Nicolas Carion committed
856
857
858
859
860
    // TODO This is commented out for now because it is causing crashes.
    // Technically, this should be the correct thing to do, but it appears
    // some changes have created regression (see shotcut)
    // with respect to restarting the consumer in GPU mode.
    // m_glslManager->fire_event("close glsl");
861
862
863
    m_texture[0] = 0;
}

Laurent Montel's avatar
Laurent Montel committed
864
static void onThreadStopped(mlt_properties owner, GLWidget *self)
865
866
867
868
869
{
    Q_UNUSED(owner)
    self->stopGlsl();
}

870
871
872
873
874
875
876
int GLWidget::setProducer(const QString &file)
{
    if (m_producer) {
        m_producer.reset();
    }
    m_producer = std::make_shared<Mlt::Producer>(new Mlt::Producer(pCore->getCurrentProfile()->profile(), nullptr, file.toUtf8().constData()));
    if (m_consumer) {
877
        //m_consumer->stop();
878
879
880
881
882
883
884
885
886
887
888
889
890
        if (!m_consumer->is_stopped()) {
            m_consumer->stop();
        }
    }
    int error = reconfigure();
    if (error == 0) {
        // The profile display aspect ratio may have changed.
        resizeGL(width(), height());
        startConsumer();
    }
    return error;
}

Nicolas Carion's avatar
Nicolas Carion committed
891
int GLWidget::setProducer(const std::shared_ptr<Mlt::Producer> &producer, bool isActive, int position)
892
{
893
894
895
    int error = 0;
    QString currentId;
    int consumerPosition = 0;
896
    currentId = m_producer->parent().get("kdenlive:id");
897
898
899
900
    if (m_consumer) {
        consumerPosition = m_consumer->position();
    }
    stop();
901
    if (producer) {
902
903
        m_producer = producer;
    } else {
904
905
906
        if (currentId == QLatin1String("black")) {
            return 0;
        }
907
        m_producer = m_blackClip;
908
        // Reset markersModel
909
        rootContext()->setContextProperty("markersModel", nullptr);
910
    }
911
    // redundant check. postcondition of above is m_producer != null
912
913
914
915
916
    m_producer->