glwidget.cpp 58.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
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
 *
 * GL shader based on BSD licensed code from Peter Bengtsson:
 * http://www.fourcc.org/source/YUV420P-OpenGL-GLSLang.c
 *
 * 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 <kdeclarative_version.h>
31
#include <klocalizedstring.h>
32
33

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

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

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

55

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

using namespace Mlt;

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

104
105
106
107
108
109
110
111
    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);
112

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

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

Laurent Montel's avatar
Laurent Montel committed
128
129
    connect(this, &QQuickWindow::sceneGraphInitialized, this, &GLWidget::initializeGL, Qt::DirectConnection);
    connect(this, &QQuickWindow::beforeRendering, this, &GLWidget::paintGL, Qt::DirectConnection);
Corey O'Connor's avatar
Corey O'Connor committed
130

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

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

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

168
void GLWidget::initializeGL()
169
{
170
    if (m_isInitialized) return;
171

172
    openglContext()->makeCurrent(&m_offscreenSurface);
173
    initializeOpenGLFunctions();
174

Nicolas Carion's avatar
Nicolas Carion committed
175
176
    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
177
178
179
    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();
180

181
    // C & D
182
    if (onlyGLESGPUAccel()) {
183
        disableGPUAccel();
184
    }
185

186
187
    createShader();

188
    m_openGLSync = initGPUAccelSync();
189

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

203
    m_frameRenderer = new FrameRenderer(openglContext(), &m_offscreenSurface, m_ClientWaitSync);
204

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

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

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

222
    // Special case optimization to negate odd effect of sample aspect ratio
223
    // not corresponding exactly with image resolution.
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
224
    if ((int)(this_aspect * 1000) == (int)(m_dar * 1000)) {
225
226
227
228
        w = width;
        h = height;
    }
    // Use OpenGL to normalise sample aspect ratio
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
229
    else if (height * m_dar > width) {
230
        w = width;
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
231
        h = width / m_dar;
Laurent Montel's avatar
Laurent Montel committed
232
    } else {
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
233
        w = height * m_dar;
234
235
236
237
238
        h = height;
    }
    x = (width - w) / 2;
    y = (height - h) / 2;
    m_rect.setRect(x, y, w, h);
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
239
    double scalex = (double)m_rect.width() / m_profileSize.width() * m_zoom;
240
    double scaley = (double)m_rect.width() /
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
241
242
                    ((double)m_profileSize.height() * m_dar / m_profileSize.width()) /
                    m_profileSize.width() * m_zoom;
243
    QPoint center = m_rect.center();
Laurent Montel's avatar
Laurent Montel committed
244
    QQuickItem *rootQml = rootObject();
245
246
    if (rootQml) {
        rootQml->setProperty("center", center);
247
248
        rootQml->setProperty("scalex", scalex);
        rootQml->setProperty("scaley", scaley);
249
        if (rootQml->objectName() == QLatin1String("rootsplit")) {
250
251
252
            // Adjust splitter pos
            rootQml->setProperty("splitterPos", x + (rootQml->property("realpercent").toDouble() * w));
        }
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
507
508
509
510
511
512
513
514
void GLWidget::paintGL()
{
    QOpenGLFunctions *f = openglContext()->functions();
    int width = this->width() * devicePixelRatio();
    int height = this->height() * devicePixelRatio();

    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;
Vincent Pinon's avatar
Vincent Pinon committed
535
    projection.scale(2.0f / (float)width, 2.0f / (float)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(float(-width) / 2.0f, float(-height) / 2.0f);
    vertices << QVector2D(float(-width) / 2.0f, float(height) / 2.0f);
    vertices << QVector2D(float(width) / 2.0f, float(-height) / 2.0f);
    vertices << QVector2D(float(width) / 2.0f, float(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 ?
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
583
            m_fbo = new QOpenGLFramebufferObject(m_profileSize.height(), 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)
684
{
685
    emit consumerPosition(pos);
686
    const double speed = m_producer->get_speed();
687
688
689
    bool isPlaying = !qFuzzyIsNull(speed);
    if (isPlaying) {
        m_proxy->positionFromConsumer(pos);
690
    }
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
691
692
693
694
695
696
    int maxPos = m_producer->get_int("out");
    if (m_isLoopMode || m_isZoneMode) {
        if (qFuzzyIsNull(speed) && pos >= maxPos) {
            m_consumer->purge();
            if (!m_isLoopMode) {
                return false;
697
            }
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
698
699
700
701
            m_producer->seek(m_proxy->zoneIn());
            m_producer->set_speed(1.0);
            m_consumer->set("refresh", 1);
            return true;
702
        }
703
        return true;
704
    } else if (!qFuzzyIsNull(speed)) {
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
705
        maxPos -= offset;
706
707
        if (pos >= (maxPos - 1) && speed > 0.) {
            // Playing past last clip, pause
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
708
709
710
711
            m_producer->set_speed(0);
            m_consumer->set("refresh", 0);
            m_consumer->purge();
            m_producer->seek(qMax(0, maxPos));
712
713
714
715
716
717
718
            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
719
720
            return false;
        }
721
722
723
724
    }
    return true;
}

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

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

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

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

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

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

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

Laurent Montel's avatar
Laurent Montel committed
840
static void onThreadStarted(mlt_properties owner, GLWidget *self)
841
842
843
844
845
{
    Q_UNUSED(owner)
    self->startGlsl();
}

846
847
848
849
850
851
852
853
854
855
void GLWidget::releaseMonitor()
{
    emit lockMonitor(false);
}

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

856
857
void GLWidget::stopGlsl()
{
Laurent Montel's avatar
Laurent Montel committed
858
    if (m_consumer) {
859
        m_consumer->purge();
Laurent Montel's avatar
Laurent Montel committed
860
    }
861

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

Laurent Montel's avatar
Laurent Montel committed
871
static void onThreadStopped(mlt_properties owner, GLWidget *self)
872
873
874
875
876
{
    Q_UNUSED(owner)
    self->stopGlsl();
}

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

925
926
927
928
929
930
931
int GLWidget::droppedFrames() const
{
    return (m_consumer ? m_consumer->get_int("drop_count") : 0);
}