glwidget.cpp 62 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 <KLocalizedContext>
25
#include <KMessageBox>
Laurent Montel's avatar
Laurent Montel committed
26
#include <QApplication>
27
#include <QFontDatabase>
Nicolas Carion's avatar
Nicolas Carion committed
28
#include <QOpenGLFunctions_3_2_Core>
Laurent Montel's avatar
Laurent Montel committed
29
#include <QPainter>
30
#include <QQmlContext>
Nicolas Carion's avatar
style    
Nicolas Carion committed
31
#include <QQuickItem>
32
#include <kdeclarative_version.h>
33
#include <klocalizedstring.h>
34
#include <memory>
35
36

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

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

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

60

61
62
63
64
65
66
#ifndef GL_TIMEOUT_IGNORED
#define GL_TIMEOUT_IGNORED 0xFFFFFFFFFFFFFFFFull
#endif

using namespace Mlt;

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

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

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

121
122
123
124
    setPersistentOpenGLContext(true);
    setPersistentSceneGraph(true);
    setClearBeforeRendering(false);
    setResizeMode(QQuickView::SizeRootObjectToView);
125
126
127
128
    auto fmt = QOpenGLContext::globalShareContext()->format();
    fmt.setDepthBufferSize(format().depthBufferSize());
    fmt.setStencilBufferSize(format().stencilBufferSize());
    m_offscreenSurface.setFormat(fmt);
129
130
    m_offscreenSurface.create();

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

Laurent Montel's avatar
Laurent Montel committed
143
144
    connect(this, &QQuickWindow::sceneGraphInitialized, this, &GLWidget::initializeGL, Qt::DirectConnection);
    connect(this, &QQuickWindow::beforeRendering, this, &GLWidget::paintGL, Qt::DirectConnection);
145
    connect(pCore.get(), &Core::updateMonitorProfile, this, &GLWidget::reloadProfile);
Corey O'Connor's avatar
Corey O'Connor committed
146

147
148
149
    registerTimelineItems();
    m_proxy = new MonitorProxy(this);
    rootContext()->setContextProperty("controller", m_proxy);
150
    engine()->addImageProvider(QStringLiteral("thumbnail"), new ThumbnailProvider);
151
152
153
154
}

GLWidget::~GLWidget()
{
155
    // C & D
156
157
158
159
160
    delete m_glslManager;
    delete m_threadStartEvent;
    delete m_threadStopEvent;
    delete m_threadCreateEvent;
    delete m_threadJoinEvent;
161
    delete m_displayEvent;
162
163
164
165
166
167
168
169
170
    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;
        }
171
    }
172
    m_blackClip.reset();
173
    delete m_shareContext;
174
    delete m_shader;
175
    // delete pCore->getCurrentProfile();
176
177
}

178
void GLWidget::updateAudioForAnalysis()
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
179
{
Laurent Montel's avatar
Laurent Montel committed
180
181
182
    if (m_frameRenderer) {
        m_frameRenderer->sendAudioForAnalysis = KdenliveSettings::monitor_audio();
    }
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
183
184
}

185
void GLWidget::initializeGL()
186
{
187
    if (m_isInitialized) return;
188

189
    openglContext()->makeCurrent(&m_offscreenSurface);
190
    initializeOpenGLFunctions();
191

192
    // C & D
193
    if (onlyGLESGPUAccel()) {
194
        disableGPUAccel();
195
    }
196

197
198
    createShader();

199
    m_openGLSync = initGPUAccelSync();
200

201
    // C & D
202
203
204
205
206
    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
207
        // TODO: QTBUG-44677 is closed. still applicable?
208
209
210
211
212
        m_shareContext = new QOpenGLContext;
        m_shareContext->setFormat(openglContext()->format());
        m_shareContext->setShareContext(openglContext());
        m_shareContext->create();
    }
213

214
    m_frameRenderer = new FrameRenderer(openglContext(), &m_offscreenSurface, m_ClientWaitSync);
215

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

218
    openglContext()->makeCurrent(this);
219
220
    connect(m_frameRenderer, &FrameRenderer::textureReady, this, &GLWidget::updateTexture, Qt::DirectConnection);
    connect(m_frameRenderer, &FrameRenderer::frameDisplayed, this, &GLWidget::onFrameDisplayed, Qt::QueuedConnection);
221
    connect(m_frameRenderer, &FrameRenderer::frameDisplayed, this, &GLWidget::frameDisplayed, Qt::QueuedConnection);
222
    m_initSem.release();
223
    m_isInitialized = true;
224
    QMetaObject::invokeMethod(this, "reconfigure", Qt::QueuedConnection);
225
226
227
228
229
}

void GLWidget::resizeGL(int width, int height)
{
    int x, y, w, h;
230
    height -= m_displayRulerHeight;
231
    double this_aspect = double(width) / height;
232

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

Laurent Montel's avatar
Laurent Montel committed
266
void GLWidget::resizeEvent(QResizeEvent *event)
267
268
{
    resizeGL(event->size().width(), event->size().height());
269
    QQuickView::resizeEvent(event);
270
271
}

272
273
274
275
276
277
278
279
280
281
282
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");
}

283
284
285
void GLWidget::createShader()
{
    m_shader = new QOpenGLShaderProgram;
Nicolas Carion's avatar
Nicolas Carion committed
286
287
288
289
290
291
292
293
294
    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;"
                                                             "}");
295
    // C & D
296
    if (m_glslManager) {
297
        createGPUAccelFragmentProg();
298
    } else {
299
        // A & B
300
        createYUVTextureProjectFragmentProg();
301
    }
302

303
304
305
306
307
308
    m_projectionLocation = m_shader->uniformLocation("projection");
    m_modelViewLocation = m_shader->uniformLocation("modelView");
    m_vertexLocation = m_shader->attributeLocation("vertex");
    m_texCoordLocation = m_shader->attributeLocation("texCoord");
}

309
310
311
void GLWidget::createYUVTextureProjectFragmentProg()
{
    m_shader->addShaderFromSourceCode(QOpenGLShader::Fragment,
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
                                      "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);"
                                      "}");
334
335
336
337
338
339
340
    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");
}

341
static void uploadTextures(QOpenGLContext *context, const SharedFrame &frame, GLuint texture[])
342
343
344
{
    int width = frame.get_image_width();
    int height = frame.get_image_height();
345
    const uint8_t *image = frame.get_image(mlt_image_yuv420p);
Laurent Montel's avatar
Laurent Montel committed
346
    QOpenGLFunctions *f = context->functions();
347

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

351
    // Upload each plane of YUV to a texture.
Nicolas Carion's avatar
Nicolas Carion committed
352
    if (texture[0] != 0u) {
353
        f->glDeleteTextures(3, texture);
Laurent Montel's avatar
Laurent Montel committed
354
    }
355
356
357
358
    check_error(f);
    f->glGenTextures(3, texture);
    check_error(f);

Laurent Montel's avatar
Laurent Montel committed
359
    f->glBindTexture(GL_TEXTURE_2D, texture[0]);
360
361
362
363
364
365
366
367
368
    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
369
    f->glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, width, height, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, image);
370
371
    check_error(f);

Laurent Montel's avatar
Laurent Montel committed
372
    f->glBindTexture(GL_TEXTURE_2D, texture[1]);
373
374
375
376
377
378
379
380
381
    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
382
    f->glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, width / 2, height / 2, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, image + width * height);
383
384
    check_error(f);

Laurent Montel's avatar
Laurent Montel committed
385
    f->glBindTexture(GL_TEXTURE_2D, texture[2]);
386
387
388
389
390
391
392
393
394
    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
395
    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);
396
397
398
    check_error(f);
}

399
400
401
402
403
404
void GLWidget::clear()
{
    stopGlsl();
    update();
}

405
406
407
408
409
void GLWidget::releaseAnalyse()
{
    m_analyseSem.release();
}

410
411
bool GLWidget::acquireSharedFrameTextures()
{
412
    // A
413
    if ((m_glslManager == nullptr) && !openglContext()->supportsThreadedOpenGL()) {
414
        QMutexLocker locker(&m_contextSharedAccess);
415
        if (!m_sharedFrame.is_valid()) {
Corey O'Connor's avatar
Corey O'Connor committed
416
            return false;
417
418
        }
        uploadTextures(openglContext(), m_sharedFrame, m_texture);
419
    } else if (m_glslManager) {
420
        // C & D
421
        m_contextSharedAccess.lock();
422
        if (m_sharedFrame.is_valid()) {
Vincent Pinon's avatar
Vincent Pinon committed
423
            m_texture[0] = *(reinterpret_cast<const GLuint *>(m_sharedFrame.get_image(mlt_image_glsl_texture)));
424
425
426
427
        }
    }

    if (!m_texture[0]) {
428
        // C & D
429
        if (m_glslManager) m_contextSharedAccess.unlock();
Corey O'Connor's avatar
Corey O'Connor committed
430
        return false;
431
    }
432

Corey O'Connor's avatar
Corey O'Connor committed
433
434
435
    return true;
}

436
437
void GLWidget::bindShaderProgram()
{
438
    m_shader->bind();
Corey O'Connor's avatar
Corey O'Connor committed
439

440
    // C & D
441
442
443
    if (m_glslManager) {
        m_shader->setUniformValue(m_textureLocation[0], 0);
    } else {
444
        // A & B
445
446
447
        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
448
        m_shader->setUniformValue(m_colorspaceLocation, m_colorSpace);
449
    }
Corey O'Connor's avatar
Corey O'Connor committed
450
451
}

452
453
void GLWidget::releaseSharedFrameTextures()
{
454
    // C & D
Corey O'Connor's avatar
Corey O'Connor committed
455
456
    if (m_glslManager) {
        glFinish();
457
        m_contextSharedAccess.unlock();
Corey O'Connor's avatar
Corey O'Connor committed
458
459
460
    }
}

461
462
bool GLWidget::initGPUAccel()
{
463
464
    if (!KdenliveSettings::gpu_accel()) return false;

465
    m_glslManager = new Mlt::Filter(pCore->getCurrentProfile()->profile(), "glsl.manager");
466
467
468
    return m_glslManager->is_valid();
}

469
470
// C & D
// TODO: insure safe, idempotent on all pipelines.
471
472
void GLWidget::disableGPUAccel()
{
473
474
475
476
477
478
479
480
    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();
}

481
482
bool GLWidget::onlyGLESGPUAccel() const
{
483
484
485
486
    return (m_glslManager != nullptr) && openglContext()->isOpenGLES();
}

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

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

Corey O'Connor's avatar
Corey O'Connor committed
513
514
515
void GLWidget::paintGL()
{
    QOpenGLFunctions *f = openglContext()->functions();
516
517
    float width = float(this->width() * devicePixelRatio());
    float height = float(this->height() * devicePixelRatio());
Corey O'Connor's avatar
Corey O'Connor committed
518
519
520
521

    f->glDisable(GL_BLEND);
    f->glDisable(GL_DEPTH_TEST);
    f->glDepthMask(GL_FALSE);
522
    f->glViewport(0, int(m_displayRulerHeight * devicePixelRatio() * 0.5 + 0.5), int(width), int(height));
Corey O'Connor's avatar
Corey O'Connor committed
523
    check_error(f);
524
    f->glClearColor(float(m_bgColor.redF()), float(m_bgColor.greenF()), float(m_bgColor.blueF()), 0);
Corey O'Connor's avatar
Corey O'Connor committed
525
526
527
    f->glClear(GL_COLOR_BUFFER_BIT);
    check_error(f);

528
    if (!acquireSharedFrameTextures()) return;
Corey O'Connor's avatar
Corey O'Connor committed
529
530
531
532
533
534
535
536
537
538
539

    // 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();
540
    check_error(f);
541
542
543

    // Setup an orthographic projection.
    QMatrix4x4 projection;
544
    projection.scale(2.0f / width, 2.0f / height);
545
    m_shader->setUniformValue(m_projectionLocation, projection);
546
    check_error(f);
547
548
549

    // Set model view.
    QMatrix4x4 modelView;
550
    if (!qFuzzyCompare(m_zoom, 1.0f)) {
551
        if ((offset().x() != 0) || (offset().y() != 0)) modelView.translate(float(-offset().x() * devicePixelRatio()), float(offset().y() * devicePixelRatio()));
552
553
554
        modelView.scale(zoom(), zoom());
    }
    m_shader->setUniformValue(m_modelViewLocation, modelView);
555
    check_error(f);
556
557
558

    // Provide vertices of triangle strip.
    QVector<QVector2D> vertices;
559
560
    width = float(m_rect.width() * devicePixelRatio());
    height = float(m_rect.height() * devicePixelRatio());
561
562
563
564
    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);
565
    m_shader->enableAttributeArray(m_vertexLocation);
566
    check_error(f);
567
    m_shader->setAttributeArray(m_vertexLocation, vertices.constData());
568
    check_error(f);
569
570
571
572
573
574
575
576

    // 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);
577
    check_error(f);
578
    m_shader->setAttributeArray(m_texCoordLocation, texCoord.constData());
579
    check_error(f);
580
581

    // Render
582
    glDrawArrays(GL_TRIANGLE_STRIP, 0, vertices.size());
583
    check_error(f);
584

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

        QMatrix4x4 projection2;
598
        projection2.scale(2.0f / width, 2.0f / height);
599
600
        m_shader->setUniformValue(m_projectionLocation, projection2);

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

    releaseSharedFrameTextures();
    check_error(f);
623
624
}

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

646
647
void GLWidget::updateRulerHeight(int addedHeight)
{
648
    m_displayRulerHeight =  m_rulerHeight > 0 ? int(QFontInfo(QFontDatabase::systemFont(QFontDatabase::SmallestReadableFont)).pixelSize() * 1.5) + addedHeight : 0;
649
650
651
    resizeGL(width(), height());
}

652
653
654
655
656
bool GLWidget::isReady() const
{
    return m_consumer != nullptr;
}

657
void GLWidget::requestSeek(int position)
658
{
Eric Parker's avatar
Eric Parker committed
659
660
661
662
663
    if(KdenliveSettings::audio_scrub()){
        m_consumer->set("scrub_audio", 1);
    } else {
        m_consumer->set("scrub_audio", 0);
    }
664
665
666
    m_producer->seek(position);
    if (!qFuzzyIsNull(m_producer->get_speed())) {
        m_consumer->purge();
667
    }
668
    restartConsumer();
669
    m_consumer->set("refresh", 1);
670
671
}

672
673
void GLWidget::requestRefresh()
{
674
    if (m_producer && qFuzzyIsNull(m_producer->get_speed())) {
675
        m_consumer->set("scrub_audio", 0);
676
677
678
679
        m_refreshTimer.start();
    }
}

680
681
682
683
684
QString GLWidget::frameToTime(int frames) const
{
    return m_consumer ? m_consumer->frames_to_time(frames, mlt_time_smpte_df) : QStringLiteral("-");
}

685
686
687
void GLWidget::refresh()
{
    m_refreshTimer.stop();
688
    QMutexLocker locker(&m_mltMutex);
689
690
691
692
    if (m_consumer) {
        restartConsumer();
        m_consumer->set("refresh", 1);
    }
693
694
}

695
bool GLWidget::checkFrameNumber(int pos, int offset, bool isPlaying)
696
{
697
    const double speed = m_producer->get_speed();
698
    m_proxy->positionFromConsumer(pos, isPlaying);
699
    int maxPos = m_producer->get_int("out");
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
700
    if (m_isLoopMode || m_isZoneMode) {
701
        if (isPlaying && pos >= maxPos) {
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
702
703
704
            m_consumer->purge();
            if (!m_isLoopMode) {
                return false;
705
            }
706
            m_producer->seek(m_isZoneMode ? m_proxy->zoneIn() : m_loopIn);
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
707
            m_producer->set_speed(1.0);
708
            m_proxy->setSpeed(1.);
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
709
710
            m_consumer->set("refresh", 1);
            return true;
711
        }
712
        return true;
713
    } else if (isPlaying) {
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
714
        maxPos -= offset;
715
        if (pos >= (maxPos - 1) && !(speed < 0.)) {
716
            // Playing past last clip, pause
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
717
            m_producer->set_speed(0);
718
            m_proxy->setSpeed(0);
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
719
720
            m_consumer->set("refresh", 0);
            m_consumer->purge();
721
            m_proxy->setPosition(qMax(0, maxPos));
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
722
            m_producer->seek(qMax(0, maxPos));
723
724
725
726
            return false;
        } else if (pos <= 0 && speed < 0.) {
            // rewinding reached 0, pause
            m_producer->set_speed(0);
727
            m_proxy->setSpeed(0);
728
729
            m_consumer->set("refresh", 0);
            m_consumer->purge();
730
            m_proxy->setPosition(0);
731
            m_producer->seek(0);
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
732
733
            return false;
        }
734
    }
735
    return isPlaying;
736
737
}

Laurent Montel's avatar
Laurent Montel committed
738
void GLWidget::mousePressEvent(QMouseEvent *event)
739
{
Nicolas Carion's avatar
Nicolas Carion committed
740
741
    if ((rootObject() != nullptr) && rootObject()->objectName() != QLatin1String("root") && !(event->modifiers() & Qt::ControlModifier) &&
        !(event->buttons() & Qt::MiddleButton)) {
742
        event->ignore();
743
        QQuickView::mousePressEvent(event);
744
745
        return;
    }
Nicolas Carion's avatar
Nicolas Carion committed
746
    if ((event->button() & Qt::LeftButton) != 0u) {
747
        if ((event->modifiers() & Qt::ControlModifier) != 0u) {
748
749
750
751
752
753
            // Pan view
            m_panStart = event->pos();
            setCursor(Qt::ClosedHandCursor);
        } else {
            m_dragStart = event->pos();
        }
Nicolas Carion's avatar
Nicolas Carion committed
754
    } else if ((event->button() & Qt::RightButton) != 0u) {
755
        emit showContextMenu(event->globalPos());
Nicolas Carion's avatar
Nicolas Carion committed
756
    } else if ((event->button() & Qt::MiddleButton) != 0u) {
757
758
        m_panStart = event->pos();
        setCursor(Qt::ClosedHandCursor);
759
    }
760
    event->accept();
761
    QQuickView::mousePressEvent(event);
762
763
}

Laurent Montel's avatar
Laurent Montel committed
764
void GLWidget::mouseMoveEvent(QMouseEvent *event)
765
{
Nicolas Carion's avatar
Nicolas Carion committed
766
767
    if ((rootObject() != nullptr) && rootObject()->objectName() != QLatin1String("root") && !(event->modifiers() & Qt::ControlModifier) &&
        !(event->buttons() & Qt::MiddleButton)) {
768
        event->ignore();
769
        QQuickView::mouseMoveEvent(event);
770
771
        return;
    }
772
    /*    if (event->modifiers() == Qt::ShiftModifier && m_producer) {
773
774
775
        emit seekTo(m_producer->get_length() *  event->x() / width());
        return;
    }*/
776
777
778
779
780
781
782
783
    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
784
    if (!(event->buttons() & Qt::LeftButton)) {
785
        QQuickView::mouseMoveEvent(event);
786
        return;
Laurent Montel's avatar
Laurent Montel committed
787
    }
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
788
    if (!event->isAccepted() && !m_dragStart.isNull() && (event->pos() - m_dragStart).manhattanLength() >= QApplication::startDragDistance()) {
789
790
791
        m_dragStart = QPoint();
        emit startDrag();
    }
792
793
}

Laurent Montel's avatar
Laurent Montel committed
794
void GLWidget::keyPressEvent(QKeyEvent *event)
795
{
796
    QQuickView::keyPressEvent(event);
797
798
799
    if (!event->isAccepted()) {
        emit passKeyEvent(event);
    }
800
801
802
803
804
805
}

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
806
    while (!m_isInitialized) {
807
        qApp->processEvents();
Laurent Montel's avatar
Laurent Montel committed
808
    }
809
810
811
812
813
#else
    if (!m_isInitialized) {
        m_initSem.acquire();
    }
#endif
Vincent Pinon's avatar
Vincent Pinon committed
814
    (*thread) = new RenderThread(function, data, m_shareContext, &m_offscreenSurface);
815
816
817
    (*thread)->start();
}

Nicolas Carion's avatar
Nicolas Carion committed
818
static void onThreadCreate(mlt_properties owner, GLWidget *self, RenderThread **thread, int *priority, thread_function_t function, void *data)
819
820
821
{
    Q_UNUSED(owner)
    Q_UNUSED(priority)
Nicolas Carion's avatar
Nicolas Carion committed
822
    // self->clearFrameRenderer();
823
    self->createThread(thread, function, data);
824
    self->lockMonitor();
825
826
}

Laurent Montel's avatar
Laurent Montel committed
827
static void onThreadJoin(mlt_properties owner, GLWidget *self, RenderThread *thread)
828
829
830
831
832
833
{
    Q_UNUSED(owner)
    if (thread) {
        thread->quit();
        thread->wait();
        delete thread;
Nicolas Carion's avatar
Nicolas Carion committed
834
        // self->clearFrameRenderer();
835
        self->releaseMonitor();
836
837
838
839
840
    }
}

void GLWidget::startGlsl()
{
841
    // C & D
842
    if (m_glslManager) {
Nicolas Carion's avatar
Nicolas Carion committed
843
        // clearFrameRenderer();
844
        m_glslManager->fire_event("init glsl");
Nicolas Carion's avatar
Nicolas Carion committed
845
        if (m_glslManager->get_int("glsl_supported") == 0) {
846
            disableGPUAccel();
Laurent Montel's avatar
Laurent Montel committed
847
        } else {
848
849
850
851
852
            emit started();
        }
    }
}

Laurent Montel's avatar
Laurent Montel committed
853
static void onThreadStarted(mlt_properties owner, GLWidget *self)
854
855
856
857
858
{
    Q_UNUSED(owner)
    self->startGlsl();
}

859
860
861
862
863
864
865
866
867
868
void GLWidget::releaseMonitor()
{
    emit lockMonitor(false);
}

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

869
870
void GLWidget::stopGlsl()
{
Laurent Montel's avatar
Laurent Montel committed
871
    if (m_consumer) {
872
        m_consumer->purge();
Laurent Montel's avatar
Laurent Montel committed
873
    }
874

875
    // C & D
Nicolas Carion's avatar
Nicolas Carion committed
876
877
878
879
880
    // 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");
881
882
883
    m_texture[0] = 0;
}

Laurent Montel's avatar
Laurent Montel committed
884
static void onThreadStopped(mlt_properties owner, GLWidget *self)
885
886
887
888
889
{
    Q_UNUSED(owner)
    self->stopGlsl();
}

890
891
892
893
894
895
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()));
896
897
898
899
    if (!m_producer && !m_producer->is_valid()) {
        m_producer.reset();
        m_producer = m_blackClip;
    }
900
    if (m_consumer) {
901
        //m_consumer->stop();
902
903
904
905
906
907
908
909
910
911
912
913
914
        if (!m_consumer->is_stopped()) {
            m_consumer->stop