glwidget.cpp 60.7 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"
Nicolas Carion's avatar
Nicolas Carion committed
42
#include <mlt++/Mlt.h>
43
#include <lib/localeHandling.h>
44

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

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

59

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

using namespace Mlt;

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

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

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

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

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

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

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

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

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

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

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

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

192
193
    createShader();

194
    m_openGLSync = initGPUAccelSync();
195

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

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

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

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

void GLWidget::resizeGL(int width, int height)
{
    int x, y, w, h;
225
    height -= m_displayRulerHeight;
226
    double this_aspect = double(width) / height;
227

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

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

267
268
269
270
271
272
273
274
275
276
277
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");
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    // 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();
535
    check_error(f);
536
537
538

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

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

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

    // 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);
572
    check_error(f);
573
    m_shader->setAttributeArray(m_texCoordLocation, texCoord.constData());
574
    check_error(f);
575
576

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

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

        QMatrix4x4 projection2;
593
        projection2.scale(2.0f / width, 2.0f / height);
594
595
        m_shader->setUniformValue(m_projectionLocation, projection2);

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

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

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

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

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
    restartConsumer();
655
    m_consumer->set("refresh", 1);
656
657
}

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

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

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

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

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

Nicolas Carion's avatar
Nicolas Carion committed
894
int GLWidget::setProducer(const std::shared_ptr<Mlt::Producer> &producer, bool isActive, int position)
895
{
896
897
898
    int error = 0;
    QString currentId;
    int consumerPosition = 0;
899
    currentId = m_producer->parent().get("kdenlive:id");
900
901
902
903
    if (m_consumer) {
        consumerPosition = m_consumer->position();
    }
    stop();