glwidget.cpp 59.4 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 <klocalizedstring.h>
33
34

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

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

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

56

57
58
59
60
61
62
#ifndef GL_TIMEOUT_IGNORED
#define GL_TIMEOUT_IGNORED 0xFFFFFFFFFFFFFFFFull
#endif

using namespace Mlt;

63
GLWidget::GLWidget(int id, QObject *parent)
64
65
66
67
68
    : QQuickView((QWindow *)parent)
    , sendFrameForAnalysis(false)
    , m_glslManager(nullptr)
    , m_consumer(nullptr)
    , m_producer(nullptr)
Vincent Pinon's avatar
Vincent Pinon committed
69
    , m_id(id)
70
    , m_rulerHeight(QFontInfo(QFontDatabase::systemFont(QFontDatabase::SmallestReadableFont)).pixelSize() * 1.5)
71
    , m_bgColor(KdenliveSettings::window_background())
Vincent Pinon's avatar
Vincent Pinon committed
72
    , m_shader(nullptr)
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
    , 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
88
89
90
    , m_profileSize(1920, 1080)
    , m_colorSpace(601)
    , m_dar(1.78)
91
    , m_sendFrame(false)
92
93
    , m_isZoneMode(false)
    , m_isLoopMode(false)
94
95
    , m_offset(QPoint(0, 0))
    , m_fbo(nullptr)
96
    , m_shareContext(nullptr)
97
98
    , m_openGLSync(false)
    , m_ClientWaitSync(nullptr)
99
{
100
101
102
103
104
    KDeclarative::KDeclarative kdeclarative;
    kdeclarative.setDeclarativeEngine(engine());
    kdeclarative.setupEngine(engine());
    kdeclarative.setupContext();

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

    setPersistentOpenGLContext(true);
    setPersistentSceneGraph(true);
    setClearBeforeRendering(false);
    setResizeMode(QQuickView::SizeRootObjectToView);
113

114
115
116
    m_offscreenSurface.setFormat(QWindow::format());
    m_offscreenSurface.create();

117
118
    m_refreshTimer.setSingleShot(true);
    m_refreshTimer.setInterval(50);
119
    m_blackClip.reset(new Mlt::Producer(pCore->getCurrentProfile()->profile(), "color:0"));
120
    m_blackClip->set("kdenlive:id", "black");
121
    m_blackClip->set("out", 3);
122
    connect(&m_refreshTimer, &QTimer::timeout, this, &GLWidget::refresh);
123
    m_producer = m_blackClip;
124
    rootContext()->setContextProperty("markersModel", 0);
125
126
    if (!initGPUAccel()) {
        disableGPUAccel();
Laurent Montel's avatar
Laurent Montel committed
127
    }
Corey O'Connor's avatar
Corey O'Connor committed
128

Laurent Montel's avatar
Laurent Montel committed
129
130
    connect(this, &QQuickWindow::sceneGraphInitialized, this, &GLWidget::initializeGL, Qt::DirectConnection);
    connect(this, &QQuickWindow::beforeRendering, this, &GLWidget::paintGL, Qt::DirectConnection);
131
    connect(pCore.get(), &Core::updateMonitorProfile, this, &GLWidget::reloadProfile);
Corey O'Connor's avatar
Corey O'Connor committed
132

133
134
135
    registerTimelineItems();
    m_proxy = new MonitorProxy(this);
    rootContext()->setContextProperty("controller", m_proxy);
136
137
138
139
}

GLWidget::~GLWidget()
{
140
    // C & D
141
142
143
144
145
    delete m_glslManager;
    delete m_threadStartEvent;
    delete m_threadStopEvent;
    delete m_threadCreateEvent;
    delete m_threadJoinEvent;
146
    delete m_displayEvent;
147
148
149
150
151
152
153
154
155
    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;
        }
156
    }
157
    m_blackClip.reset();
158
    delete m_shareContext;
159
    delete m_shader;
160
    // delete pCore->getCurrentProfile();
161
162
}

163
void GLWidget::updateAudioForAnalysis()
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
164
{
Laurent Montel's avatar
Laurent Montel committed
165
166
167
    if (m_frameRenderer) {
        m_frameRenderer->sendAudioForAnalysis = KdenliveSettings::monitor_audio();
    }
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
168
169
}

170
void GLWidget::initializeGL()
171
{
172
    if (m_isInitialized) return;
173

174
    openglContext()->makeCurrent(&m_offscreenSurface);
175
    initializeOpenGLFunctions();
176

Nicolas Carion's avatar
Nicolas Carion committed
177
178
    qCDebug(KDENLIVE_LOG) << "OpenGL vendor: " << QString::fromUtf8((const char *)glGetString(GL_VENDOR));
    qCDebug(KDENLIVE_LOG) << "OpenGL renderer: " << QString::fromUtf8((const char *)glGetString(GL_RENDERER));
Laurent Montel's avatar
Laurent Montel committed
179
180
181
    qCDebug(KDENLIVE_LOG) << "OpenGL Threaded: " << openglContext()->supportsThreadedOpenGL();
    qCDebug(KDENLIVE_LOG) << "OpenGL ARG_SYNC: " << openglContext()->hasExtension("GL_ARB_sync");
    qCDebug(KDENLIVE_LOG) << "OpenGL OpenGLES: " << openglContext()->isOpenGLES();
182

183
    // C & D
184
    if (onlyGLESGPUAccel()) {
185
        disableGPUAccel();
186
    }
187

188
189
    createShader();

190
    m_openGLSync = initGPUAccelSync();
191

192
    // C & D
193
194
195
196
197
    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
198
        // TODO: QTBUG-44677 is closed. still applicable?
199
200
201
202
203
        m_shareContext = new QOpenGLContext;
        m_shareContext->setFormat(openglContext()->format());
        m_shareContext->setShareContext(openglContext());
        m_shareContext->create();
    }
204

205
    m_frameRenderer = new FrameRenderer(openglContext(), &m_offscreenSurface, m_ClientWaitSync);
206

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

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

void GLWidget::resizeGL(int width, int height)
{
    int x, y, w, h;
221
    height -= m_rulerHeight;
Nicolas Carion's avatar
Nicolas Carion committed
222
    double this_aspect = (double)width / height;
223

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

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

263
264
265
266
267
268
269
270
271
272
273
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");
}

274
275
276
void GLWidget::createShader()
{
    m_shader = new QOpenGLShaderProgram;
Nicolas Carion's avatar
Nicolas Carion committed
277
278
279
280
281
282
283
284
285
    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;"
                                                             "}");
286
    // C & D
287
    if (m_glslManager) {
288
        createGPUAccelFragmentProg();
289
    } else {
290
        // A & B
291
        createYUVTextureProjectFragmentProg();
292
    }
293

294
295
296
297
298
299
    m_projectionLocation = m_shader->uniformLocation("projection");
    m_modelViewLocation = m_shader->uniformLocation("modelView");
    m_vertexLocation = m_shader->attributeLocation("vertex");
    m_texCoordLocation = m_shader->attributeLocation("texCoord");
}

300
301
302
void GLWidget::createYUVTextureProjectFragmentProg()
{
    m_shader->addShaderFromSourceCode(QOpenGLShader::Fragment,
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
                                      "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);"
                                      "}");
325
326
327
328
329
330
331
    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");
}

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

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

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

Laurent Montel's avatar
Laurent Montel committed
350
    f->glBindTexture(GL_TEXTURE_2D, texture[0]);
351
352
353
354
355
356
357
358
359
    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
360
    f->glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, width, height, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, image);
361
362
    check_error(f);

Laurent Montel's avatar
Laurent Montel committed
363
    f->glBindTexture(GL_TEXTURE_2D, texture[1]);
364
365
366
367
368
369
370
371
372
    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
373
    f->glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, width / 2, height / 2, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, image + width * height);
374
375
    check_error(f);

Laurent Montel's avatar
Laurent Montel committed
376
    f->glBindTexture(GL_TEXTURE_2D, texture[2]);
377
378
379
380
381
382
383
384
385
    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
386
    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);
387
388
389
    check_error(f);
}

390
391
392
393
394
395
void GLWidget::clear()
{
    stopGlsl();
    update();
}

396
397
398
399
400
void GLWidget::releaseAnalyse()
{
    m_analyseSem.release();
}

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

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

Corey O'Connor's avatar
Corey O'Connor committed
424
425
426
    return true;
}

427
428
void GLWidget::bindShaderProgram()
{
429
    m_shader->bind();
Corey O'Connor's avatar
Corey O'Connor committed
430

431
    // C & D
432
433
434
    if (m_glslManager) {
        m_shader->setUniformValue(m_textureLocation[0], 0);
    } else {
435
        // A & B
436
437
438
        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
439
        m_shader->setUniformValue(m_colorspaceLocation, m_colorSpace);
440
    }
Corey O'Connor's avatar
Corey O'Connor committed
441
442
}

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

452
453
bool GLWidget::initGPUAccel()
{
454
455
    if (!KdenliveSettings::gpu_accel()) return false;

456
    m_glslManager = new Mlt::Filter(pCore->getCurrentProfile()->profile(), "glsl.manager");
457
458
459
    return m_glslManager->is_valid();
}

460
461
// C & D
// TODO: insure safe, idempotent on all pipelines.
462
463
void GLWidget::disableGPUAccel()
{
464
465
466
467
468
469
470
471
    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();
}

472
473
bool GLWidget::onlyGLESGPUAccel() const
{
474
475
476
477
    return (m_glslManager != nullptr) && openglContext()->isOpenGLES();
}

#if defined(Q_OS_WIN)
478
479
bool GLWidget::initGPUAccelSync()
{
480
481
482
483
484
    // no-op
    // TODO: getProcAddress is not working on Windows?
    return false;
}
#else
485
486
bool GLWidget::initGPUAccelSync()
{
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
    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 {
        qCDebug(KDENLIVE_LOG) << "  / / // NO GL SYNC, ERROR";
        // fallback on A || B
        // TODO: fallback on A || B || C?
        disableGPUAccel();
        return false;
    }
}
#endif

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

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

519
    if (!acquireSharedFrameTextures()) return;
Corey O'Connor's avatar
Corey O'Connor committed
520
521
522
523
524
525
526
527
528
529
530

    // 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();
531
    check_error(f);
532
533
534

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

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

    // Provide vertices of triangle strip.
    QVector<QVector2D> vertices;
    width = m_rect.width() * devicePixelRatio();
    height = m_rect.height() * devicePixelRatio();
552
553
554
555
    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);
556
    m_shader->enableAttributeArray(m_vertexLocation);
557
    check_error(f);
558
    m_shader->setAttributeArray(m_vertexLocation, vertices.constData());
559
    check_error(f);
560
561
562
563
564
565
566
567

    // 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);
568
    check_error(f);
569
    m_shader->setAttributeArray(m_texCoordLocation, texCoord.constData());
570
    check_error(f);
571
572

    // Render
573
    glDrawArrays(GL_TRIANGLE_STRIP, 0, vertices.size());
574
    check_error(f);
575

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

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

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

    releaseSharedFrameTextures();
    check_error(f);
614
615
}

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

void GLWidget::wheelEvent(QWheelEvent *event)
{
    if (((event->modifiers() & Qt::ControlModifier) != 0u) && ((event->modifiers() & Qt::ShiftModifier) != 0u)) {
        slotZoom(event->delta() > 0);
641
642
        return;
    }
643
    emit mouseSeek(event->delta(), (uint)event->modifiers());
644
645
646
    event->accept();
}

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

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

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

673
674
675
void GLWidget::refresh()
{
    m_refreshTimer.stop();
676
    QMutexLocker locker(&m_mltMutex);
677
678
679
680
681
682
    if (m_consumer->is_stopped()) {
        m_consumer->start();
    }
    m_consumer->set("refresh", 1);
}

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

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

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

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

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
789
    while (!m_isInitialized) {
790
        qApp->processEvents();
Laurent Montel's avatar
Laurent Montel committed
791
    }
792
793
794
795
796
#else
    if (!m_isInitialized) {
        m_initSem.acquire();
    }
#endif
Vincent Pinon's avatar
Vincent Pinon committed
797
    (*thread) = new RenderThread(function, data, m_shareContext, &m_offscreenSurface);
798
799
800
    (*thread)->start();
}

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

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

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

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

842
843
844
845
846
847
848
849
850
851
void GLWidget::releaseMonitor()
{
    emit lockMonitor(false);
}

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

852
853
void GLWidget::stopGlsl()
{
Laurent Montel's avatar
Laurent Montel committed
854
    if (m_consumer) {
855
        m_consumer->purge();
Laurent Montel's avatar
Laurent Montel committed
856
    }
857

858
    // C & D
Nicolas Carion's avatar
Nicolas Carion committed
859
860
861
862
863
    // 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");
864
865
866
    m_texture[0] = 0;
}

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

Nicolas Carion's avatar
Nicolas Carion committed
873
int GLWidget::setProducer(const std::shared_ptr<Mlt::Producer> &producer, bool isActive, int position)
874
{
875
876
877
    int error = 0;
    QString currentId;
    int consumerPosition = 0;
878
    currentId = m_producer->parent().get("kdenlive:id");
879
    if (producer) {
880
881
        m_producer = producer;
    } else {
882
883
884
        if (currentId == QLatin1String("black")) {
            return 0;
        }
885
        m_producer = m_blackClip;
886
887
        // Reset markersModel
        rootContext()->setContextProperty("markersModel", 0);
888
    }
889
    // redundant check. postcondition of above is m_producer != null
Vincent Pinon's avatar
Vincent Pinon committed
890
    if (m_producer) {
891
892
893
        m_producer->set_speed(0);
        if (m_consumer) {
            consumerPosition = m_consumer->position();
894
            m_consumer->stop();
895
896
897
898
            if (!m_consumer->is_stopped()) {
                m_consumer->stop();
            }
        }
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
899
        error = reconfigure();
Nicolas Carion's avatar
Nicolas Carion committed
900
        if (error == 0) {
901
902
903
            // The profile display aspect ratio may have changed.
            resizeGL(width(), height());
        }
Laurent Montel's avatar
Laurent Montel committed
904
905
906
907
908
909
    } else {
        return error;
    }
    if (!m_consumer) {
        return error;
    }
910
    consumerPosition = m_consumer->position();
911
    if (position == -1 && m_producer->parent().get("kdenlive:id") == currentId) {
912
913
        position = consumerPosition;
    }
914
915
916
    if (isActive) {
        startConsumer();
    }
917
    m_consumer->set("scrub_audio", 0);
918
    m_proxy->setPosition(position > 0 ? position : m_producer->position());
919
920
921
    return error;
}

922
923
924
925
926
927
928
int GLWidget::droppedFrames() const
{
    return (m_consumer ? m_consumer->get_int("drop_count") : 0);
}

void GLWidget::resetDrops()
{
Laurent Montel's avatar
Laurent Montel committed
929
930
931
    if (m_consumer) {
        m_consumer->set("drop_count", 0);
    }
Jean-Baptiste Mardelle's avatar