renderwidget.cpp 81.4 KB
Newer Older
1
/*
Alexander Lohnau's avatar
Alexander Lohnau committed
2
    SPDX-FileCopyrightText: 2008 Jean-Baptiste Mardelle <jb@kdenlive.org>
3
    SPDX-FileCopyrightText: 2022 Julius Künzel <jk.kdedev@smartlab.uber.space>
4

5
    SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
6
*/
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
7

8
#include "renderwidget.h"
9
#include "bin/bin.h"
10
#include "bin/projectitemmodel.h"
Nicolas Carion's avatar
linting    
Nicolas Carion committed
11
#include "core.h"
12
#include "dialogs/renderpresetdialog.h"
13
#include "doc/kdenlivedoc.h"
14
#include "kdenlivesettings.h"
15
#include "monitor/monitor.h"
Nicolas Carion's avatar
Nicolas Carion committed
16
17
#include "profiles/profilemodel.hpp"
#include "profiles/profilerepository.hpp"
18
#include "project/projectmanager.h"
19
#include "utils/timecode.h"
20
#include "xml/xml.hpp"
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
21

22
23
24
25
#include "renderpresets/tree/renderpresettreemodel.hpp"
#include "renderpresets/renderpresetrepository.hpp"
#include "renderpresets/renderpresetmodel.hpp"

26
#include "klocalizedstring.h"
27
#include <KColorScheme>
28
#include <KIO/DesktopExecParser>
29
#include <KIO/OpenFileManagerWindowJob>
Nicolas Carion's avatar
Nicolas Carion committed
30
31
32
#include <KMessageBox>
#include <KNotification>
#include <KRun>
33
#include <kio_version.h>
Nicolas Carion's avatar
Nicolas Carion committed
34
#include <knotifications_version.h>
35

Laurent Montel's avatar
Laurent Montel committed
36
#include "kdenlive_debug.h"
Nicolas Carion's avatar
Nicolas Carion committed
37
38
#include <QDBusConnectionInterface>
#include <QDir>
39
#include <QDomDocument>
40
#include <QFileIconProvider>
41
42
#include <QHeaderView>
#include <QInputDialog>
43
44
#include <QJsonArray>
#include <QJsonObject>
Nicolas Carion's avatar
Nicolas Carion committed
45
#include <QKeyEvent>
46
#include <QMenu>
Nicolas Carion's avatar
Nicolas Carion committed
47
#include <QMimeDatabase>
48
#include <QProcess>
49
#include <QStandardPaths>
50
#include <QTemporaryFile>
Nicolas Carion's avatar
Nicolas Carion committed
51
52
53
54
#include <QThread>
#include <QTreeWidgetItem>
#include <qglobal.h>
#include <qstring.h>
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
55

56
57
58
59
60
#ifdef KF5_USE_PURPOSE
#include <Purpose/AlternativesModel>
#include <PurposeWidgets/Menu>
#endif

Vincent Pinon's avatar
Vincent Pinon committed
61
#include <locale>
62
63
64
#ifdef Q_OS_MAC
#include <xlocale.h>
#endif
65

66
// Render job roles
67
68
69
70
71
72
enum {
    ParametersRole = Qt::UserRole + 1,
    StartTimeRole,
    ProgressRole,
    ExtraInfoRole = ProgressRole + 2, // vpinon: don't understand why, else spurious message displayed
    LastTimeRole,
73
74
    LastFrameRole,
    OpenBrowserRole
75
};
76

77
// Running job status
Nicolas Carion's avatar
Nicolas Carion committed
78
enum JOBSTATUS { WAITINGJOB = 0, STARTINGJOB, RUNNINGJOB, FINISHEDJOB, FAILEDJOB, ABORTEDJOB };
79

80
81
82
RenderJobItem::RenderJobItem(QTreeWidget *parent, const QStringList &strings, int type)
    : QTreeWidgetItem(parent, strings, type)
    , m_status(-1)
83
{
84
    setSizeHint(1, QSize(parent->columnWidth(1), parent->fontMetrics().height() * 3));
85
86
87
88
89
    setStatus(WAITINGJOB);
}

void RenderJobItem::setStatus(int status)
{
90
    if (m_status == status) {
Laurent Montel's avatar
Laurent Montel committed
91
        return;
92
    }
93
94
    m_status = status;
    switch (status) {
95
    case WAITINGJOB:
96
        setIcon(0, QIcon::fromTheme(QStringLiteral("media-playback-pause")));
97
        setData(1, Qt::UserRole, i18n("Waiting…"));
98
99
100
        break;
    case FINISHEDJOB:
        setData(1, Qt::UserRole, i18n("Rendering finished"));
101
        setIcon(0, QIcon::fromTheme(QStringLiteral("dialog-ok")));
102
103
104
105
        setData(1, ProgressRole, 100);
        break;
    case FAILEDJOB:
        setData(1, Qt::UserRole, i18n("Rendering crashed"));
106
        setIcon(0, QIcon::fromTheme(QStringLiteral("dialog-close")));
107
108
109
110
        setData(1, ProgressRole, 100);
        break;
    case ABORTEDJOB:
        setData(1, Qt::UserRole, i18n("Rendering aborted"));
111
        setIcon(0, QIcon::fromTheme(QStringLiteral("dialog-cancel")));
112
        setData(1, ProgressRole, 100);
Vincent Pinon's avatar
Vincent Pinon committed
113
        break;
114
115
    default:
        break;
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
    }
}

int RenderJobItem::status() const
{
    return m_status;
}

void RenderJobItem::setMetadata(const QString &data)
{
    m_data = data;
}

const QString RenderJobItem::metadata() const
{
    return m_data;
}
133

134
RenderWidget::RenderWidget(bool enableProxy, QWidget *parent)
135
136
    : QDialog(parent)
    , m_blockProcessing(false)
137
{
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
138
    m_view.setupUi(this);
139
140
    int size = style()->pixelMetric(QStyle::PM_SmallIconSize);
    QSize iconSize(size, size);
141

142
    // ===== "Render Project" tab =====
143
144
    m_view.buttonDelete->setIconSize(iconSize);
    m_view.buttonEdit->setIconSize(iconSize);
145
146
    m_view.buttonNew->setIconSize(iconSize);
    m_view.buttonSaveAs->setIconSize(iconSize);
147
    m_view.buttonDownload->setIconSize(iconSize);
148

149
150
    m_view.buttonRender->setEnabled(false);
    m_view.buttonGenerateScript->setEnabled(false);
151

152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
    connect(m_view.profileTree, &QTreeView::doubleClicked, this, [&](const QModelIndex &index){
        if (m_treeModel->parent(index) == QModelIndex()) {
            // This is a top level item - group - don't edit
            return;
        }
        slotEditPreset();
    });
    connect(m_view.buttonNew, &QAbstractButton::clicked, this, &RenderWidget::slotNewPreset);
    connect(m_view.buttonEdit, &QAbstractButton::clicked, this, &RenderWidget::slotEditPreset);
    connect(m_view.buttonDelete, &QAbstractButton::clicked, this, [this](){
        RenderPresetRepository::get()->deletePreset(m_currentProfile);
        m_currentProfile = QString();
        parseProfiles();
        refreshView();
    });
    connect(m_view.buttonSaveAs, &QAbstractButton::clicked, this, &RenderWidget::slotSavePresetAs);
    connect(m_view.buttonDownload, &QAbstractButton::clicked, this, [&](){
        if (pCore->getNewStuff(QStringLiteral(":data/kdenlive_renderprofiles.knsrc")) > 0) {
            parseProfiles();
        }
    });
    m_view.optionsGroup->setVisible(m_view.options->isChecked());
    connect(m_view.options, &QAbstractButton::toggled, m_view.optionsGroup, &QWidget::setVisible);
175

176
177
    connect(m_view.out_file, &KUrlRequester::textChanged, this, static_cast<void (RenderWidget::*)()>(&RenderWidget::slotUpdateButtons));
    connect(m_view.out_file, &KUrlRequester::urlSelected, this, static_cast<void (RenderWidget::*)(const QUrl &)>(&RenderWidget::slotUpdateButtons));
178

179
180
181
182
    connect(m_view.render_multi, &QAbstractButton::clicked, this, &RenderWidget::slotRenderModeChanged);
    connect(m_view.render_guide, &QAbstractButton::clicked, this, &RenderWidget::slotRenderModeChanged);
    connect(m_view.render_zone, &QAbstractButton::clicked, this, &RenderWidget::slotRenderModeChanged);
    connect(m_view.render_full, &QAbstractButton::clicked, this, &RenderWidget::slotRenderModeChanged);
183

184
185
    connect(m_view.guide_end, static_cast<void (KComboBox::*)(int)>(&KComboBox::activated), this, &RenderWidget::slotCheckStartGuidePosition);
    connect(m_view.guide_start, static_cast<void (KComboBox::*)(int)>(&KComboBox::activated), this, &RenderWidget::slotCheckEndGuidePosition);
186
187


188
    // === "More Options" widget ===
189
    setRescaleEnabled(false);
190
191
    m_view.guide_zone_box->setVisible(false);
    m_view.guide_multi_box->setVisible(false);
192
    m_view.error_box->setVisible(false);
193
    m_view.tc_type->addItem(i18n("None"));
194
    m_view.tc_type->addItem(i18n("Timecode"), QStringLiteral("#timecode#"));
195
196
    m_view.tc_type->addItem(i18n("Timecode Non Drop Frame"), QStringLiteral("#smtpe_ndf#"));
    m_view.tc_type->addItem(i18n("Frame Number"), QStringLiteral("#frame#"));
197
    m_view.checkTwoPass->setEnabled(false);
198
    m_view.proxy_render->setHidden(!enableProxy);
199
200
201
202
203
204
205
    connect(m_view.proxy_render, &QCheckBox::toggled, this, [&](bool enabled){
        errorMessage(ProxyWarning, enabled ? i18n("Rendering using low quality proxy") : QString());
    });

    connect(m_view.quality, &QAbstractSlider::valueChanged, this, &RenderWidget::refreshParams);
    connect(m_view.qualityGroup, &QGroupBox::toggled, this, &RenderWidget::refreshParams);
    connect(m_view.speed, &QAbstractSlider::valueChanged, this, &RenderWidget::adjustSpeed);
206

207
208
    m_view.encoder_threads->setMaximum(QThread::idealThreadCount());
    m_view.encoder_threads->setValue(KdenliveSettings::encodethreads());
209
    connect(m_view.encoder_threads, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this, &KdenliveSettings::setEncodethreads);
210
    connect(m_view.encoder_threads, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this, &RenderWidget::refreshParams);
211

212
213
    connect(m_view.video_box, &QGroupBox::toggled, this, &RenderWidget::refreshParams);
    connect(m_view.audio_box, &QGroupBox::toggled, this, &RenderWidget::refreshParams);
214
    m_view.rescale_keep->setChecked(KdenliveSettings::rescalekeepratio());
215
216
    connect(m_view.rescale, &QAbstractButton::toggled, this, &RenderWidget::setRescaleEnabled);
    connect(m_view.rescale, &QAbstractButton::toggled, this, &RenderWidget::refreshParams);
217
218
    connect(m_view.rescale_width, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this, &RenderWidget::slotUpdateRescaleWidth);
    connect(m_view.rescale_height, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this, &RenderWidget::slotUpdateRescaleHeight);
Laurent Montel's avatar
Laurent Montel committed
219
    connect(m_view.rescale_keep, &QAbstractButton::clicked, this, &RenderWidget::slotSwitchAspectRatio);
220
221
222
223
224
225
226
227
228
229
230
    m_view.parallel_process->setChecked(KdenliveSettings::parallelrender());
    connect(m_view.parallel_process, &QCheckBox::stateChanged, [&](int state) {
        KdenliveSettings::setParallelrender(state == Qt::Checked);
        refreshParams();
    });
    if (KdenliveSettings::gpu_accel()) {
        // Disable parallel rendering for movit
        m_view.parallel_process->setEnabled(false);
    }
    connect(m_view.export_meta, &QCheckBox::stateChanged, this, &RenderWidget::refreshParams);
    connect(m_view.checkTwoPass, &QCheckBox::stateChanged, this, &RenderWidget::refreshParams);
231

232
233
    connect(m_view.buttonRender, &QAbstractButton::clicked, this, [&](){ slotPrepareExport(); });
    connect(m_view.buttonGenerateScript, &QAbstractButton::clicked, this, [&](){ slotPrepareExport(true); });
234

235
236
    m_view.infoMessage->hide();
    m_view.jobInfo->hide();
237
    parseProfiles();
238
239

    // ===== "Job Queue" tab =====
240
    parseScriptFiles();
241
    m_view.running_jobs->setUniformRowHeights(false);
242
    m_view.running_jobs->setContextMenuPolicy(Qt::CustomContextMenu);
243
    connect(m_view.running_jobs, &QTreeWidget::customContextMenuRequested, this, &RenderWidget::prepareJobContextMenu);
244
    m_view.scripts_list->setUniformRowHeights(false);
Laurent Montel's avatar
Laurent Montel committed
245
246
247
248
249
250
251
252
    connect(m_view.start_script, &QAbstractButton::clicked, this, &RenderWidget::slotStartScript);
    connect(m_view.delete_script, &QAbstractButton::clicked, this, &RenderWidget::slotDeleteScript);
    connect(m_view.scripts_list, &QTreeWidget::itemSelectionChanged, this, &RenderWidget::slotCheckScript);
    connect(m_view.running_jobs, &QTreeWidget::itemSelectionChanged, this, &RenderWidget::slotCheckJob);
    connect(m_view.running_jobs, &QTreeWidget::itemDoubleClicked, this, &RenderWidget::slotPlayRendering);

    connect(m_view.abort_job, &QAbstractButton::clicked, this, &RenderWidget::slotAbortCurrentJob);
    connect(m_view.start_job, &QAbstractButton::clicked, this, &RenderWidget::slotStartCurrentJob);
253
    connect(m_view.clean_up, &QAbstractButton::clicked, this, &RenderWidget::slotCleanUpJobs);
Laurent Montel's avatar
Laurent Montel committed
254
255
256
257
258
    connect(m_view.hide_log, &QAbstractButton::clicked, this, &RenderWidget::slotHideLog);

    connect(m_view.buttonClose, &QAbstractButton::clicked, this, &QWidget::hide);
    connect(m_view.buttonClose2, &QAbstractButton::clicked, this, &QWidget::hide);
    connect(m_view.buttonClose3, &QAbstractButton::clicked, this, &QWidget::hide);
259

260
    m_jobsDelegate = new RenderViewDelegate(this);
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
261
    m_view.running_jobs->setHeaderLabels(QStringList() << QString() << i18n("File"));
262
    m_view.running_jobs->setItemDelegate(m_jobsDelegate);
263

264
    QHeaderView *header = m_view.running_jobs->header();
265
    header->setSectionResizeMode(0, QHeaderView::Fixed);
266
    header->resizeSection(0, size + 4);
267
    header->setSectionResizeMode(1, QHeaderView::Interactive);
268

269
    // ===== "Scripts" tab =====
270
    m_view.scripts_list->setHeaderLabels(QStringList() << QString() << i18n("Stored Playlists"));
271
272
    m_scriptsDelegate = new RenderViewDelegate(this);
    m_view.scripts_list->setItemDelegate(m_scriptsDelegate);
273
    header = m_view.scripts_list->header();
274
    header->setSectionResizeMode(0, QHeaderView::Fixed);
275
    header->resizeSection(0, size + 4);
276

Nicolas Carion's avatar
Nicolas Carion committed
277
// Find path for Kdenlive renderer
278
279
280
#ifdef Q_OS_WIN
    m_renderer = QCoreApplication::applicationDirPath() + QStringLiteral("/kdenlive_render.exe");
#else
281
    m_renderer = QCoreApplication::applicationDirPath() + QStringLiteral("/kdenlive_render");
282
#endif
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
283
    if (!QFile::exists(m_renderer)) {
284
        m_renderer = QStandardPaths::findExecutable(QStringLiteral("kdenlive_render"));
285
        if (m_renderer.isEmpty()) {
286
            KMessageBox::sorry(this, i18n("Could not find the kdenlive_render application, something is wrong with your installation. Rendering will not work"));
287
        }
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
288
289
    }

290
    QDBusConnectionInterface *interface = QDBusConnection::sessionBus().interface();
Nicolas Carion's avatar
Nicolas Carion committed
291
292
    if ((interface == nullptr) ||
        (!interface->isServiceRegistered(QStringLiteral("org.kde.ksmserver")) && !interface->isServiceRegistered(QStringLiteral("org.gnome.SessionManager")))) {
293
        m_view.shutdown->setEnabled(false);
294
    }
295
296
297
298

#ifdef KF5_USE_PURPOSE
    m_shareMenu = new Purpose::Menu();
    m_view.shareButton->setMenu(m_shareMenu);
299
    m_view.shareButton->setIcon(QIcon::fromTheme(QStringLiteral("document-share")));
300
    connect(m_shareMenu, &Purpose::Menu::finished, this, &RenderWidget::slotShareActionFinished);
301
302
303
#else
    m_view.shareButton->setEnabled(false);
#endif
304

305
    loadConfig();
306
    refreshView();
307
    focusItem();
308
    adjustSize();
309
310
}

311
312
void RenderWidget::slotShareActionFinished(const QJsonObject &output, int error, const QString &message)
{
313
#ifdef KF5_USE_PURPOSE
314
    m_view.jobInfo->hide();
315
    if (error) {
316
        KMessageBox::error(this, i18n("There was a problem sharing the document: %1", message), i18n("Share"));
317
318
319
    } else {
        const QString url = output["url"].toString();
        if (url.isEmpty()) {
320
321
322
            m_view.jobInfo->setMessageType(KMessageWidget::Positive);
            m_view.jobInfo->setText(i18n("Document shared successfully"));
            m_view.jobInfo->show();
323
        } else {
324
            KMessageBox::information(this, i18n("You can find the shared document at: <a href=\"%1\">%1</a>", url), i18n("Share"), QString(),
325
326
327
                                     KMessageBox::Notify | KMessageBox::AllowLink);
        }
    }
Nicolas Carion's avatar
Nicolas Carion committed
328
329
330
331
#else
    Q_UNUSED(output);
    Q_UNUSED(error);
    Q_UNUSED(message);
332
#endif
333
}
334

335
336
337
QSize RenderWidget::sizeHint() const
{
    // Make sure the widget has minimum size on opening
Nicolas Carion's avatar
Nicolas Carion committed
338
    return {200, 200};
339
340
}

341
342
RenderWidget::~RenderWidget()
{
343
    saveConfig();
344
345
346
347
348
349
350
351
    m_view.running_jobs->blockSignals(true);
    m_view.scripts_list->blockSignals(true);
    m_view.running_jobs->clear();
    m_view.scripts_list->clear();
    delete m_jobsDelegate;
    delete m_scriptsDelegate;
}

352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
void RenderWidget::saveConfig()
{
    KSharedConfigPtr config = KSharedConfig::openConfig();
    KConfigGroup resourceConfig(config, "RenderWidget");
    resourceConfig.writeEntry(QStringLiteral("showoptions"), m_view.options->isChecked());
    config->sync();
}

void RenderWidget::loadConfig()
{
    KSharedConfigPtr config = KSharedConfig::openConfig();
    KConfigGroup resourceConfig(config, "RenderWidget");
    m_view.options->setChecked(resourceConfig.readEntry("showoptions", false));
}

367
void RenderWidget::updateDocumentPath()
368
{
369
    if (m_view.out_file->url().isEmpty()) {
370
371
        return;
    }
372
373
374
    const QString fileName = m_view.out_file->url().fileName();
    m_view.out_file->setUrl(QUrl::fromLocalFile(QDir(pCore->currentDoc()->projectDataFolder()).absoluteFilePath(fileName)));
    parseScriptFiles();
375
376
}

377
void RenderWidget::slotRenderModeChanged()
378
{
379
380
    m_view.guide_zone_box->setVisible(m_view.render_guide->isChecked());
    m_view.guide_multi_box->setVisible(m_view.render_multi->isChecked());
381
    m_view.buttonGenerateScript->setVisible(!m_view.render_multi->isChecked());
382
383
384
385
386
387
388
389
}

void RenderWidget::slotUpdateRescaleWidth(int val)
{
    KdenliveSettings::setDefaultrescalewidth(val);
    if (!m_view.rescale_keep->isChecked()) {
        refreshParams();
        return;
390
    }
391
392
393
394
395
396
    m_view.rescale_height->blockSignals(true);
    std::unique_ptr<ProfileModel> &profile = pCore->getCurrentProfile();
    m_view.rescale_height->setValue(val * profile->height() / profile->width());
    KdenliveSettings::setDefaultrescaleheight(m_view.rescale_height->value());
    m_view.rescale_height->blockSignals(false);
    refreshParams();
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
397
398
}

399
void RenderWidget::slotUpdateRescaleHeight(int val)
400
{
401
402
403
    KdenliveSettings::setDefaultrescaleheight(val);
    if (!m_view.rescale_keep->isChecked()) {
        refreshParams();
404
        return;
405
    }
406
407
408
409
410
411
    m_view.rescale_width->blockSignals(true);
    std::unique_ptr<ProfileModel> &profile = pCore->getCurrentProfile();
    m_view.rescale_width->setValue(val * profile->width() / profile->height());
    KdenliveSettings::setDefaultrescaleheight(m_view.rescale_width->value());
    m_view.rescale_width->blockSignals(false);
    refreshParams();
412
413
}

414
void RenderWidget::slotSwitchAspectRatio()
415
{
416
417
418
419
    KdenliveSettings::setRescalekeepratio(m_view.rescale_keep->isChecked());
    if (m_view.rescale_keep->isChecked()) {
        slotUpdateRescaleWidth(m_view.rescale_width->value());
    }
420
421
}

422
423
void RenderWidget::slotCheckStartGuidePosition()
{
424
    if (m_view.guide_start->currentIndex() > m_view.guide_end->currentIndex()) {
425
        m_view.guide_start->setCurrentIndex(m_view.guide_end->currentIndex());
426
    }
427
428
}

429
430
void RenderWidget::slotCheckEndGuidePosition()
{
431
    if (m_view.guide_end->currentIndex() < m_view.guide_start->currentIndex()) {
432
        m_view.guide_end->setCurrentIndex(m_view.guide_start->currentIndex());
433
    }
434
435
}

436
void RenderWidget::setGuides(std::weak_ptr<MarkerListModel> guidesModel)
437
{
438
439
440
441
442
443
444
445
446
    m_guidesModel = std::move(guidesModel);
    reloadGuides();
    if (auto ptr = m_guidesModel.lock()) {
        connect(ptr.get(), &MarkerListModel::modelChanged, this, &RenderWidget::reloadGuides);
    }
}

void RenderWidget::reloadGuides()
{
447
    double projectDuration = GenTime(pCore->projectDuration() - 1, pCore->getCurrentFps()).ms() / 1000;
448
449
    QVariant startData = m_view.guide_start->currentData();
    QVariant endData = m_view.guide_end->currentData();
450
451
    m_view.guide_start->clear();
    m_view.guide_end->clear();
452
453
    m_view.guideCategoryCombo->clear();

454
455
    if (auto ptr = m_guidesModel.lock()) {
        QList<CommentedTime> markers = ptr->getAllMarkers();
456
        double fps = pCore->getCurrentFps();
457
        m_view.render_guide->setEnabled(!markers.isEmpty());
458
        m_view.render_multi->setEnabled(!markers.isEmpty());
459
        if (!markers.isEmpty()) {
460
            m_view.guide_start->addItem(i18n("Beginning"), 0);
Vincent Pinon's avatar
Vincent Pinon committed
461
            for (const auto &marker : qAsConst(markers)) {
462
463
464
465
466
                GenTime pos = marker.time();
                const QString guidePos = Timecode::getStringTimecode(pos.frames(fps), fps);
                m_view.guide_start->addItem(marker.comment() + QLatin1Char('/') + guidePos, pos.seconds());
                m_view.guide_end->addItem(marker.comment() + QLatin1Char('/') + guidePos, pos.seconds());
            }
467
            m_view.guide_end->addItem(i18n("End"), projectDuration);
468
469
470
471
472
473
474
475
            if (!startData.isNull()) {
                int ix = qMax(0, m_view.guide_start->findData(startData));
                m_view.guide_start->setCurrentIndex(ix);
            }
            if (!endData.isNull()) {
                int ix = qMax(m_view.guide_start->currentIndex() + 1, m_view.guide_end->findData(endData));
                m_view.guide_end->setCurrentIndex(ix);
            }
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491

            // Set up guide categories
            static std::array<QColor, 9> markerTypes = ptr->markerTypes;
            QPixmap pixmap(32,32);
            m_view.guideCategoryCombo->addItem(i18n("All Categories"), -1);
            for (uint i = 0; i < markerTypes.size(); ++i) {
                if (!ptr->getAllMarkers(i).isEmpty()) {
                    pixmap.fill(markerTypes[size_t(i)]);
                    QIcon colorIcon(pixmap);
                    m_view.guideCategoryCombo->addItem(colorIcon, i18n("Category %1", i), i);
                }
            }
        } else {
            if (m_view.render_guide->isChecked() || m_view.render_multi->isChecked()) {
                m_view.render_full->setChecked(true);
            }
492
        }
493
494
    } else {
        m_view.render_guide->setEnabled(false);
495
496
497
498
        m_view.render_multi->setEnabled(false);
        if (m_view.render_guide->isChecked() || m_view.render_multi->isChecked()) {
            m_view.render_full->setChecked(true);
        }
499
    }
500
    slotRenderModeChanged();
501
502
}

503
void RenderWidget::slotUpdateButtons(const QUrl &url)
504
{
505
506
507
508
    if (!RenderPresetRepository::get()->presetExists(m_currentProfile)) {
        m_view.buttonSaveAs->setEnabled(false);
        m_view.buttonDelete->setEnabled(false);
        m_view.buttonEdit->setEnabled(false);
509
        m_view.buttonRender->setEnabled(false);
510
        m_view.buttonGenerateScript->setEnabled(false);
511
    } else {
512
513
514
515
516
517
        std::unique_ptr<RenderPresetModel> &profile = RenderPresetRepository::get()->getPreset(m_currentProfile);
        m_view.buttonRender->setEnabled(!m_view.out_file->url().isEmpty() && profile->error().isEmpty());
        m_view.buttonGenerateScript->setEnabled(!m_view.out_file->url().isEmpty() && profile->error().isEmpty());
        m_view.buttonSaveAs->setEnabled(true);
        m_view.buttonDelete->setEnabled(profile->editable());
        m_view.buttonEdit->setEnabled(profile->editable());
518
    }
519
    if (url.isValid()) {
520
        if (!RenderPresetRepository::get()->presetExists(m_currentProfile)) {
521
522
            m_view.buttonRender->setEnabled(false);
            m_view.buttonGenerateScript->setEnabled(false);
523
524
            return;
        }
525
526
        std::unique_ptr<RenderPresetModel> &profile = RenderPresetRepository::get()->getPreset(m_currentProfile);
        m_view.out_file->setUrl(filenameWithExtension(url, profile->extension()));
527
528
529
    }
}

530

531
532
void RenderWidget::slotUpdateButtons()
{
533
    slotUpdateButtons(QUrl());
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
534
535
}

536
void RenderWidget::slotSavePresetAs()
537
{
538
539
    if (RenderPresetRepository::get()->presetExists(m_currentProfile)) {
        std::unique_ptr<RenderPresetModel> &profile = RenderPresetRepository::get()->getPreset(m_currentProfile);
540

541
542
543
        QPointer<RenderPresetDialog> dialog = new RenderPresetDialog(this, profile.get(), RenderPresetDialog::SaveAs);
        if (dialog->exec() == QDialog::Accepted) {
            parseProfiles(dialog->saveName());
544
        }
545
546
547
        delete dialog;
    } else {
        slotNewPreset();
548
    }
549
}
550

551
552
553
554
555
void RenderWidget::slotNewPreset()
{
    QPointer<RenderPresetDialog> dialog = new RenderPresetDialog(this);
    if (dialog->exec() == QDialog::Accepted) {
        parseProfiles(dialog->saveName());
556
    }
557
    delete dialog;
558
559
}

560
void RenderWidget::slotEditPreset()
561
{
562
563
    if (!RenderPresetRepository::get()->presetExists(m_currentProfile)) {
        return;
564
    }
565
    std::unique_ptr<RenderPresetModel> &profile = RenderPresetRepository::get()->getPreset(m_currentProfile);
566

567
568
569
    if (!profile->editable()) {
        return;
    }
570

571
572
573
574
575
576
    QPointer<RenderPresetDialog> dialog = new RenderPresetDialog(this, profile.get(), RenderPresetDialog::Edit);
    if (dialog->exec() == QDialog::Accepted) {      
        parseProfiles(dialog->saveName());
    }
    delete dialog;
}
577

578
void RenderWidget::focusItem(const QString &profile)
579
580
{
    QItemSelectionModel *selection = m_view.profileTree->selectionModel();
581
    QModelIndex index = m_treeModel->findPreset(profile);
582
583
    if (!index.isValid() && RenderPresetRepository::get()->presetExists(KdenliveSettings::renderProfile())) {
        index = m_treeModel->findPreset(KdenliveSettings::renderProfile());
584
    }
585
586
587
588
589
590
    if (index.isValid()) {
        selection->select(index, QItemSelectionModel::Select);
        // expand corresponding category
        auto parent = m_treeModel->parent(index);
        m_view.profileTree->expand(parent);
        m_view.profileTree->scrollTo(index, QAbstractItemView::PositionAtCenter);
591
    }
592
593
}

594
void RenderWidget::slotPrepareExport(bool delayedRendering, const QString &scriptPath)
595
{
596
597
598
599
600
601
    Q_UNUSED(scriptPath)
    if (pCore->projectDuration() < 2) {
        // Empty project, don't attempt to render
        m_view.infoMessage->setMessageType(KMessageWidget::Warning);
        m_view.infoMessage->setText(i18n("Add a clip to timeline before rendering"));
        m_view.infoMessage->animatedShow();
Laurent Montel's avatar
Laurent Montel committed
602
        return;
603
    }
604
605
606
607
608
    if (!QFile::exists(KdenliveSettings::rendererpath())) {
        m_view.infoMessage->setMessageType(KMessageWidget::Warning);
        m_view.infoMessage->setText(i18n("Cannot find the melt program required for rendering (part of Mlt)"));
        m_view.infoMessage->animatedShow();
        return;
609
    }
610
611
612
613
614
    m_view.infoMessage->hide();
    if (QFile::exists(m_view.out_file->url().toLocalFile())) {
        if (KMessageBox::warningYesNo(this, i18n("Output file already exists. Do you want to overwrite it?")) != KMessageBox::Yes) {
            return;
        }
615
    }
616
617
618
619
620
621
    // mantisbt 1051
    QDir dir(m_view.out_file->url().adjusted(QUrl::RemoveFilename).toLocalFile());
    if (!dir.exists() && !dir.mkpath(QStringLiteral("."))) {
        KMessageBox::sorry(this, i18n("The directory %1, could not be created.\nPlease make sure you have the required permissions.",
                                      m_view.out_file->url().adjusted(QUrl::RemoveFilename).toLocalFile()));
        return;
622
    }
623

624
    prepareRendering(delayedRendering);
625
626
}

627
void RenderWidget::prepareRendering(bool delayedRendering)
628
{
629
    saveRenderProfile();
630

631
632
633
    KdenliveDoc *project = pCore->currentDoc();
    QString overlayData = m_view.tc_type->currentData().toString();
    QString playlistContent = pCore->projectManager()->projectSceneList(project->url().adjusted(QUrl::RemoveFilename | QUrl::StripTrailingSlash).toLocalFile(), overlayData);
634

635
636
637
638
639
640
641
642
643
644
    // Set playlist audio volume to 100%
    QDomDocument doc;
    doc.setContent(playlistContent);
    QDomElement tractor = doc.documentElement().firstChildElement(QStringLiteral("tractor"));
    if (!tractor.isNull()) {
        QDomNodeList props = tractor.elementsByTagName(QStringLiteral("property"));
        for (int i = 0; i < props.count(); ++i) {
            if (props.at(i).toElement().attribute(QStringLiteral("name")) == QLatin1String("meta.volume")) {
                props.at(i).firstChild().setNodeValue(QStringLiteral("1"));
                break;
645
            }
646
647
        }
    }
Laurent Montel's avatar
Laurent Montel committed
648

649
650
651
652
    // Add autoclose to playlists.
    QDomNodeList playlists = doc.elementsByTagName(QStringLiteral("playlist"));
    for (int i = 0; i < playlists.length(); ++i) {
        playlists.item(i).toElement().setAttribute(QStringLiteral("autoclose"), 1);
653
    }
654

655
656
657
    // Do we want proxy rendering
    if (project->useProxy() && !m_view.proxy_render->isChecked()) {
        pCore->currentDoc()->useOriginals(doc);
658
659
    }

660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
    QString outputFile = m_view.out_file->url().toLocalFile();
    // in/out points
    int in = 0;
    // Remove last black frame
    int out = pCore->projectDuration() - 2;
    Monitor *pMon = pCore->getMonitor(Kdenlive::ProjectMonitor);
    double fps = pCore->getCurrentProfile()->fps();
    if (m_view.render_zone->isChecked()) {
        in = pMon->getZoneStart();
        out = pMon->getZoneEnd() - 1;
        generateRenderFiles(doc, in, out, outputFile, delayedRendering);
    } else if (m_view.render_guide->isChecked()) {
        double guideStart = m_view.guide_start->itemData(m_view.guide_start->currentIndex()).toDouble();
        double guideEnd = m_view.guide_end->itemData(m_view.guide_end->currentIndex()).toDouble();
        in = int(GenTime(guideStart).frames(fps));
        // End rendering at frame before last guide
        out = int(GenTime(guideEnd).frames(fps)) - 1;
        generateRenderFiles(doc, in, out, outputFile, delayedRendering);
    } else if (m_view.render_multi->isChecked()) {
        if (auto ptr = m_guidesModel.lock()) {
            int category = m_view.guideCategoryCombo->currentData().toInt();
            QList<CommentedTime> markers = ptr->getAllMarkers(category);
            if (!markers.isEmpty()) {
                bool beginParsed = false;
                QStringList names;
                for (int i = 0; i < markers.count(); i++) {
                    QString name;
                    int absoluteOut = pCore->projectDuration() - 2;
                    in = 0;
                    out = absoluteOut;
                    if (!beginParsed && i == 0 && markers.at(i).time().frames(fps) != 0) {
                        i -= 1;
                        beginParsed = true;
                        name = i18n("begin");
                    }
                    if (i >= 0) {
                        name = markers.at(i).comment();
                        in = markers.at(i).time().frames(fps);
                    }
                    int j = 0;
                    QString newName = name;
                    // if name alrady exist, add a suffix
                    while (names.contains(newName)) {
                        newName = QStringLiteral("%1_%2").arg(name).arg(j);
                        j++;
                    }
                    names.append(newName);
                    name = newName;
                    if (in < absoluteOut) {
                        if (i+1 < markers.count()) {
                            out = qMin(markers.at(i+1).time().frames(fps) - 1, absoluteOut);
                        }
                        QString filename = outputFile.section(QLatin1Char('.'), 0, -2) + QStringLiteral("-%1.").arg(name) + outputFile.section(QLatin1Char('.'), -1);
                        QDomDocument docCopy = doc.cloneNode(true).toDocument();
                        generateRenderFiles(docCopy, in, out, filename, false);
                    }
716
717
                }
            }
718
        }
719
720
721
722
    } else {
        generateRenderFiles(doc, in, out, outputFile, delayedRendering);
    }
}
723

724
725
726
727
728
729
730
731
732
733
QString RenderWidget::generatePlaylistFile(bool delayedRendering)
{
    if (delayedRendering) {
        bool ok;
        QString filename = QFileInfo(pCore->currentDoc()->url().toLocalFile()).fileName();
        const QString fileExtension = QStringLiteral(".mlt");
        if (filename.isEmpty()) {
            filename = i18n("export");
        } else {
            filename = filename.section(QLatin1Char('.'), 0, -2);
734
        }
735

736
737
738
        QDir projectFolder(pCore->currentDoc()->projectDataFolder());
        projectFolder.mkpath(QStringLiteral("kdenlive-renderqueue"));
        projectFolder.cd(QStringLiteral("kdenlive-renderqueue"));
739
740
741
742
743
744
        int ix = 1;
        QString newFilename = filename;
        // if name alrady exist, add a suffix
        while (projectFolder.exists(newFilename + fileExtension)) {
            newFilename = QStringLiteral("%1-%2").arg(filename).arg(ix);
            ix++;
745
        }
746
        filename = QInputDialog::getText(this, i18nc("@title:window", "Delayed Rendering"), i18n("Select a name for this rendering."), QLineEdit::Normal, newFilename, &ok);
747
        if (!ok) {
748
            return {};
749
        }
750
751
        if (!filename.endsWith(fileExtension)) {
            filename.append(fileExtension);
752
        }
753
754
755
        if (projectFolder.exists(newFilename)) {
            if (KMessageBox::questionYesNo(this, i18n("File %1 already exists.\nDo you want to overwrite it?", filename)) == KMessageBox::No) {
                return {};
756
757
            }
        }
758
        return projectFolder.absoluteFilePath(filename);
759
    }
760
761
762
763
764
    // No delayed rendering, we can use a temp file
    QTemporaryFile tmp(QDir::temp().absoluteFilePath(QStringLiteral("kdenlive-XXXXXX.mlt")));
    if (!tmp.open()) {
        // Something went wrong
        return {};
765
    }
766
767
768
    tmp.close();
    return tmp.fileName();
}
769

770
771
772
773
void RenderWidget::generateRenderFiles(QDomDocument doc, int in, int out, QString outputFile, bool delayedRendering)
{
    QString playlistPath = generatePlaylistFile(delayedRendering);
    QString extension = outputFile.section(QLatin1Char('.'), -1);
774

775
776
    if (playlistPath.isEmpty()) {
        return;
777
778
779
780
    }

    QString renderArgs = m_view.advanced_params->toPlainText().simplified();
    QDomElement consumer = doc.createElement(QStringLiteral("consumer"));
781
782
783
784
    consumer.setAttribute(QStringLiteral("in"), in);
    consumer.setAttribute(QStringLiteral("out"), out);
    consumer.setAttribute(QStringLiteral("mlt_service"), QStringLiteral("avformat"));

785
786
787
788
789
790
791
    QDomNodeList profiles = doc.elementsByTagName(QStringLiteral("profile"));
    if (profiles.isEmpty()) {
        doc.documentElement().insertAfter(consumer, doc.documentElement());
    } else {
        doc.documentElement().insertAfter(consumer, profiles.at(profiles.length() - 1));
    }

792
    // insert params from preset
793
794
795
    QStringList args = renderArgs.split(QLatin1Char(' '));
    for (auto &param : args) {
        if (param.contains(QLatin1Char('='))) {
796
            QString paramName = param.section(QLatin1Char('='), 0, 0);
797
            QString paramValue = param.section(QLatin1Char('='), 1);
798
            consumer.setAttribute(paramName, paramValue);
799
800
801
        }
    }

802
803
    // If we use a pix_fmt with alpha channel (ie. transparent),
    // we need to remove the black background track
Vincent Pinon's avatar
Vincent Pinon committed
804
805
806
807
808
809
810
811
812
813
814
815
    if (renderArgs.contains(QLatin1String("pix_fmt=argb"))
     || renderArgs.contains(QLatin1String("pix_fmt=abgr"))
     || renderArgs.contains(QLatin1String("pix_fmt=bgra"))
     || renderArgs.contains(QLatin1String("pix_fmt=gbra"))
     || renderArgs.contains(QLatin1String("pix_fmt=rgba"))
     || renderArgs.contains(QLatin1String("pix_fmt=yuva"))
     || renderArgs.contains(QLatin1String("pix_fmt=ya"  ))
     || renderArgs.contains(QLatin1String("pix_fmt=ayuv"))) {
        auto prods = doc.elementsByTagName(QStringLiteral("producer"));
        for (int i = 0; i < prods.count(); ++i) {
            auto prod = prods.at(i).toElement();
            if (prod.attribute(QStringLiteral("id")) == QStringLiteral("black_track")) {
816
                Xml::setXmlProperty(prod, QStringLiteral("resource"), QStringLiteral("transparent"));
Vincent Pinon's avatar
Vincent Pinon committed
817
818
819
820
821
                break;
            }
        }
    }

822
823
824
825
826
827
828
829
830
831
832
833
834
835
    QMap<QString, QString> renderFiles;
    if (renderArgs.contains("=stills/"))
    {
        // Image sequence, ensure we have a %0xd at file end.
        // Format string for counter
        QRegularExpression rx(QRegularExpression::anchoredPattern(QStringLiteral(".*%[0-9]*d.*")));
        if (!rx.match(outputFile).hasMatch()) {
            outputFile = outputFile.section(QLatin1Char('.'), 0, -2) + QStringLiteral("_%05d.") + extension;
        }
    }

    if (m_view.stemAudioExport->isChecked() && m_view.stemAudioExport->isEnabled()) {
        if (delayedRendering) {
            if (KMessageBox::warningContinueCancel(this, i18n("Script rendering and multi track audio export can not be used together.\n"
Yuri Chornoivan's avatar
Yuri Chornoivan committed
836
                                                        "Script will be saved without multi track export."))
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
                                                   == KMessageBox::Cancel) { return; };
        }
        int audioCount = 0;
        QDomNodeList orginalTractors = doc.elementsByTagName(QStringLiteral("tractor"));
        // process in reversed order to make file naming fit to UI
        for (int i = orginalTractors.size(); i >= 0; i--) {
            bool isAudio = Xml::getXmlProperty(orginalTractors.at(i).toElement(), QStringLiteral("kdenlive:audio_track")).toInt() == 1;
            QString trackName = Xml::getXmlProperty(orginalTractors.at(i).toElement(), QStringLiteral("kdenlive:track_name"));
            if (isAudio) {
                // setup filenames
                QString appendix = QString("_Audio_%1%2%3.").arg(audioCount + 1).arg(trackName.isEmpty() ? QString() : QStringLiteral("-")).arg(trackName.replace(QStringLiteral(" "), QStringLiteral("_")));
                QString playlistFile = playlistPath.section(QLatin1Char('.'), 0, -2) + appendix + playlistPath.section(QLatin1Char('.'), -1);
                QString targetFile = outputFile.section(QLatin1Char('.'), 0, -2) + appendix + extension;
                renderFiles.insert(playlistFile, targetFile);

                // init doc copy
853
                QDomDocument docCopy = doc.cloneNode(true).toDocument();
854
855
856
857
858
859
860
861
862
863
864
                QDomElement copyConsumer = docCopy.elementsByTagName(QStringLiteral("consumer")).at(0).toElement();
                copyConsumer.setAttribute(QStringLiteral("target"), targetFile);

                QDomNodeList tracktors = docCopy.elementsByTagName(QStringLiteral("tractor"));
                // the last tractor is the main tracktor, don't process it (-1)
                for (int j = 0; j < tracktors.size() - 1; j++) {
                    QDomNodeList tracks = tracktors.at(j).toElement().elementsByTagName(QStringLiteral("track"));
                    for (int l = 0; l < tracks.size(); l++) {
                        if (i != j) {
                            tracks.at(l).toElement().setAttribute(QStringLiteral("hide"), QStringLiteral("both"));
                        }
865
866
                    }
                }
867
868
869
870
871
872
873
874
875
876
877
878
879
880

                QFile file(playlistFile);
                if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
                    pCore->displayMessage(i18n("Cannot write to file %1", playlistFile), ErrorMessage);
                    return;
                }
                file.write(docCopy.toString().toUtf8());
                if (file.error() != QFile::NoError) {
                    pCore->displayMessage(i18n("Cannot write to file %1", playlistFile), ErrorMessage);
                    file.close();
                    return;
                }
                file.close();
                audioCount++;
881
            }
882

883
        }
884
    }
885

886
887
888
    QDomDocument clone;
    int passes = m_view.checkTwoPass->isChecked() ? 2 : 1;
    if (passes == 2) {
889
890
891
        // We will generate 2 files, one for each pass.
        clone = doc.cloneNode(true).toDocument();
    }
892

893
894
895
    for (int i = 0; i < passes; i++) {
        // Append consumer settings
        QDomDocument final = i > 0 ? clone : doc;
896
897
898
899
        QDomNodeList consList = final.elementsByTagName(QStringLiteral("consumer"));
        QDomElement finalConsumer = consList.at(0).toElement();
        finalConsumer.setAttribute(QStringLiteral("target"), outputFile);
        int pass = passes == 2 ? i + 1 : 0;
900
        QString playlistName = playlistPath;
901
902
        if (pass == 2) {
            playlistName = playlistName.section(QLatin1Char('.'), 0, -2) + QStringLiteral("-pass%1.").arg(2) + extension;
903
        }
904
        renderFiles.insert(playlistName, outputFile);
905

906
        // Prepare rendering args
907
        QString logFile = QStringLiteral("%1_2pass.log").arg(outputFile);
908
909
        if (renderArgs.contains(QStringLiteral("libx265"))) {
            if (pass == 1 || pass == 2) {
910
911
912
                QString x265params = finalConsumer.attribute("x265-params");
                x265params = QString(<