renderpresetmodel.cpp 18 KB
Newer Older
1
2
/*
   SPDX-FileCopyrightText: 2017 Nicolas Carion
3
   SPDX-FileCopyrightText: 2022 Julius Künzel <jk.kdedev@smartlab.uber.space>
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
   SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
   This file is part of Kdenlive. See www.kdenlive.org.
*/

#include "renderpresetmodel.hpp"
#include "renderpresetrepository.hpp"
#include "core.h"
#include "kdenlive_debug.h"
#include "kdenlivesettings.h"
#include "profiles/profilerepository.hpp"
#include "profiles/profilemodel.hpp"

#include <KLocalizedString>
#include <KMessageWidget>
#include <QDir>
#include <QFile>
#include <QRegularExpression>
#include <memory>

RenderPresetModel::RenderPresetModel(QDomElement preset, const QString &presetFile, bool editable, const QString &groupName, const QString &renderer)
    : m_presetFile(presetFile)
    , m_editable(editable)
    , m_name(preset.attribute(QStringLiteral("name")))
    , m_note()
    , m_standard(preset.attribute(QStringLiteral("standard")))
    , m_params()
    , m_groupName(preset.attribute(QStringLiteral("category"), groupName))
    , m_renderer(renderer)
    , m_url(preset.attribute(QStringLiteral("url")))
    , m_speeds(preset.attribute(QStringLiteral("speeds")))
    , m_topFieldFirst(preset.attribute(QStringLiteral("top_field_first")))
{
    if (m_groupName.isEmpty()) {
        m_groupName = i18nc("Category Name", "Custom");
    }

    QTextDocument docConvert;
    docConvert.setHtml(preset.attribute(QStringLiteral("args")));
    m_params = docConvert.toPlainText().simplified();

    m_extension = preset.attribute(QStringLiteral("extension"));

    if (getParam(QStringLiteral("f")).isEmpty() && !m_extension.isEmpty() && RenderPresetRepository::supportedFormats().contains(m_extension)) {
        m_params.append(QStringLiteral(" f=%1").arg(m_extension));
    }

    m_vQualities = preset.attribute(QStringLiteral("qualities"));
    m_defaultVQuality = preset.attribute(QStringLiteral("defaultquality"));
    m_vBitrates = preset.attribute(QStringLiteral("bitrates"));
    m_defaultVBitrate = preset.attribute(QStringLiteral("defaultbitrate"));

    m_aQualities = preset.attribute(QStringLiteral("audioqualities"));
    m_defaultAQuality = preset.attribute(QStringLiteral("defaultaudioquality"));
    m_aBitrates = preset.attribute(QStringLiteral("audiobitrates"));
    m_defaultABitrate = preset.attribute(QStringLiteral("defaultaudiobitrate"));

    checkPreset();
}

RenderPresetModel::RenderPresetModel(const QString &groupName, const QString &path, QString presetName, const QString &params, bool codecInName)
    : m_editable(false)
    , m_params(params)
    , m_groupName(groupName)
    , m_renderer(QStringLiteral("avformat"))
{
    KConfig config(path, KConfig::SimpleConfig);
    KConfigGroup group = config.group(QByteArray());
    QString vcodec = group.readEntry("vcodec");
    QString acodec = group.readEntry("acodec");
    m_extension = group.readEntry("meta.preset.extension");
    if (getParam(QStringLiteral("f")).isEmpty() && !m_extension.isEmpty() && RenderPresetRepository::supportedFormats().contains(m_extension)) {
        m_params.append(QStringLiteral(" f=%1").arg(m_extension));
    }
    m_note = group.readEntry("meta.preset.note");

    if (codecInName && (!vcodec.isEmpty() || !acodec.isEmpty())) {
        presetName.append(" (");
        if (!vcodec.isEmpty()) {
            presetName.append(vcodec);
            if (!acodec.isEmpty()) {
                presetName.append("+" + acodec);
            }
        } else if (!acodec.isEmpty()) {
            presetName.append(acodec);
        }
        presetName.append(QLatin1Char(')'));
    }
    m_name = presetName;
    checkPreset();
}

RenderPresetModel::RenderPresetModel(const QString &name, const QString &groupName, const QString &params, const QString &defaultVBitrate, const QString &defaultVQuality,
                                       const QString &defaultABitrate, const QString &defaultAQuality, const QString &speeds)
    : m_presetFile()
    , m_editable()
    , m_name(name)
    , m_note()
    , m_standard()
    , m_params(params)
    , m_extension()
    , m_groupName(groupName)
    , m_renderer(QStringLiteral("avformat"))
    , m_url()
    , m_speeds(speeds)
    , m_topFieldFirst()
    , m_vBitrates()
    , m_defaultVBitrate(defaultVBitrate)
    , m_vQualities()
    , m_defaultVQuality(defaultVQuality)
    , m_aBitrates()
    , m_defaultABitrate(defaultABitrate)
    , m_aQualities()
    , m_defaultAQuality(defaultAQuality)
{
    if (m_groupName.isEmpty()) {
        m_groupName = i18nc("Category Name", "Custom");
    }

    checkPreset();
}

void RenderPresetModel::checkPreset() {
    QStringList acodecs = RenderPresetRepository::acodecs();
    QStringList vcodecs = RenderPresetRepository::vcodecs();
    QStringList supportedFormats = RenderPresetRepository::supportedFormats();

    bool replaceVorbisCodec = acodecs.contains(QStringLiteral("libvorbis"));
    bool replaceLibfaacCodec = acodecs.contains(QStringLiteral("libfaac"));

    if (replaceVorbisCodec && m_params.contains(QStringLiteral("acodec=vorbis"))) {
        // replace vorbis with libvorbis
        m_params = m_params.replace(QLatin1String("=vorbis"), QLatin1String("=libvorbis"));
    }
    if (replaceLibfaacCodec && m_params.contains(QStringLiteral("acodec=aac"))) {
        // replace libfaac with aac
        m_params = m_params.replace(QLatin1String("aac"), QLatin1String("libfaac"));
    }

    // We borrow a reference to the profile's pointer to query it more easily
    std::unique_ptr<ProfileModel> &profile = pCore->getCurrentProfile();
    double project_framerate = double(profile->frame_rate_num()) / profile->frame_rate_den();

    if (m_standard.isEmpty() ||
        (m_standard.contains(QStringLiteral("PAL"), Qt::CaseInsensitive) && profile->frame_rate_num() == 25 && profile->frame_rate_den() == 1) ||
        (m_standard.contains(QStringLiteral("NTSC"), Qt::CaseInsensitive) && profile->frame_rate_num() == 30000 && profile->frame_rate_den() == 1001)) {
        // Standard OK
    } else {
        m_errors = i18n("Standard (%1) not compatible with project profile (%2)", m_standard, project_framerate);
        return;
    }

    if (m_params.contains(QStringLiteral("mlt_profile="))) {
        QString profile_str = getParam(QStringLiteral("mlt_profile"));
        std::unique_ptr<ProfileModel> &target_profile = ProfileRepository::get()->getProfile(profile_str);
        if (target_profile->frame_rate_den() > 0) {
            double profile_rate = double(target_profile->frame_rate_num()) / target_profile->frame_rate_den();
            if (int(1000.0 * profile_rate) != int(1000.0 * project_framerate)) {
                m_errors = i18n("Frame rate (%1) not compatible with project profile (%2)", profile_rate, project_framerate);
                return;
            }
        }
    }

    // Make sure the selected preset uses an installed avformat codec / format
    QString format;
    format = getParam(QStringLiteral("f")).toLower();
    if (!format.isEmpty() && !supportedFormats.contains(format)) {
        m_errors = i18n("Unsupported video format: %1", format);
        return;
    }

    // check for missing audio codecs
    format = getParam(QStringLiteral("acodec")).toLower();
    if (!format.isEmpty() && !acodecs.contains(format)) {
        m_errors = i18n("Unsupported audio codec: %1", format);
        return;
    }
    // check for missing video codecs
    format = getParam(QStringLiteral("vcodec")).toLower();
    if (!format.isEmpty() && !vcodecs.contains(format)) {
        m_errors = i18n("Unsupported video codec: %1", format);
        return;
    }

    if (hasParam(QStringLiteral("profile"))) {
        m_warnings = i18n("This render preset uses a 'profile' parameter.<br />Unless you know what you are doing you will probably "
                               "have to change it to 'mlt_profile'.");
        return;
    }
}

QDomElement RenderPresetModel::toXml()
{
    QDomDocument doc;
    QDomElement profileElement = doc.createElement(QStringLiteral("profile"));
    doc.appendChild(profileElement);

    profileElement.setAttribute(QStringLiteral("name"), m_name);
    profileElement.setAttribute(QStringLiteral("category"), m_groupName);
    if (!m_extension.isEmpty()) {
        profileElement.setAttribute(QStringLiteral("extension"), m_extension);
    }
    profileElement.setAttribute(QStringLiteral("args"), m_params);
    if (!m_defaultVBitrate.isEmpty()) {
        profileElement.setAttribute(QStringLiteral("defaultbitrate"), m_defaultVBitrate);
    }
    if (!m_vBitrates.isEmpty()) {
        profileElement.setAttribute(QStringLiteral("bitrates"), m_vBitrates);
    }
    if (!m_defaultVQuality.isEmpty()) {
        profileElement.setAttribute(QStringLiteral("defaultquality"), m_defaultVQuality);
    }
    if (!m_vQualities.isEmpty()) {
        profileElement.setAttribute(QStringLiteral("qualities"), m_vQualities);
    }
    if (!m_defaultABitrate.isEmpty()) {
        profileElement.setAttribute(QStringLiteral("defaultaudiobitrate"), m_defaultABitrate);
    }
    if (!m_aBitrates.isEmpty()) {
        profileElement.setAttribute(QStringLiteral("audiobitrates"), m_aBitrates);
    }
    if (!m_defaultAQuality.isEmpty()) {
        profileElement.setAttribute(QStringLiteral("defaultaudioquality"), m_defaultAQuality);
    }
    if (!m_aQualities.isEmpty()) {
        profileElement.setAttribute(QStringLiteral("audioqualities"), m_aQualities);
    }
231
    if (!m_speeds.isEmpty()) {
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
        // profile has a variable speed
        profileElement.setAttribute(QStringLiteral("speeds"), m_speeds);
    }
    return doc.documentElement();
}

QString RenderPresetModel::params(QStringList removeParams) const
{
    QString params = m_params;
    for (auto p : removeParams) {
        params.remove(QRegularExpression(QStringLiteral("((^|\\s)%1=\\S*)").arg(p)));
    }
    return params.simplified();
}

QString RenderPresetModel::extension() const {
    if (!m_extension.isEmpty()) {
            return m_extension;
    }
    return getParam(QStringLiteral("f"));
};


QStringList RenderPresetModel::audioBitrates() const
{
#if QT_VERSION < QT_VERSION_CHECK(5, 15, 0)
    return m_aBitrates.split(QLatin1Char(','), QString::SkipEmptyParts);
#else
    return m_aBitrates.split(QLatin1Char(','), Qt::SkipEmptyParts);
#endif
}

QString RenderPresetModel::defaultABitrate() const
{
    return m_defaultABitrate;
}

QStringList RenderPresetModel::audioQualities() const
{
    if (!m_aQualities.isEmpty()) {
#if QT_VERSION < QT_VERSION_CHECK(5, 15, 0)
        return m_aQualities.split(QLatin1Char(','), QString::SkipEmptyParts);
#else
        return m_aQualities.split(QLatin1Char(','), Qt::SkipEmptyParts);
#endif
    } else {
278
        // ATTENTION: historically qualities are sorted from best to worse for some reason
279
280
        QString acodec = getParam(QStringLiteral("acodec")).toLower();
        if (acodec == "libmp3lame") {
281
            return {"0", "9"};
282
        } else if (acodec == "libvorbis" || acodec == "vorbis") {
283
            return {"10", "0"};
284
        } else {
285
            return {"500", "0"};
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
        }
    }
}

QString RenderPresetModel::defaultAQuality() const
{
    return m_defaultAQuality;
}

QStringList RenderPresetModel::videoBitrates() const
{
#if QT_VERSION < QT_VERSION_CHECK(5, 15, 0)
    return m_vBitrates.split(QLatin1Char(','), QString::SkipEmptyParts);
#else
    return m_vBitrates.split(QLatin1Char(','), Qt::SkipEmptyParts);
#endif
}

QString RenderPresetModel::defaultVBitrate() const
{
    return m_defaultVBitrate;
}

QStringList RenderPresetModel::videoQualities() const
{
    if (!m_vQualities.isEmpty()) {
#if QT_VERSION < QT_VERSION_CHECK(5, 15, 0)
        return m_vQualities.split(QLatin1Char(','), QString::SkipEmptyParts);
#else
        return m_vQualities.split(QLatin1Char(','), Qt::SkipEmptyParts);
#endif
    } else {
318
        // ATTENTION: historically qualities are sorted from best to worse for some reason
319
320
        QString vcodec = getParam(QStringLiteral("vcodec")).toLower();
        if (vcodec == "libx265" || vcodec.contains("nvenc") || vcodec.endsWith("_amf") || vcodec.startsWith("libx264") || vcodec.endsWith("_vaapi") || vcodec.endsWith("_qsv")) {
321
            return {"0", "51"};
322
        } else if (vcodec.startsWith("libvpx") || vcodec.startsWith("libaom-")) {
323
            return {"0", "63"};
324
        } else if (vcodec.startsWith("libwebp")) {
325
            return {"100", "0"};
326
        } else {
327
            return {"1", "31"};
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
        }
    }
}

QString RenderPresetModel::defaultVQuality() const
{
    return m_defaultVQuality;
}

bool RenderPresetModel::editable() const
{
    return m_editable;
}

QStringList RenderPresetModel::speeds() const
{
#if QT_VERSION < QT_VERSION_CHECK(5, 15, 0)
    return m_speeds.split(QLatin1Char(';'), QString::SkipEmptyParts);
#else
    return m_speeds.split(QLatin1Char(';'), Qt::SkipEmptyParts);
#endif
}

QString RenderPresetModel::getParam(const QString &name) const
{
    if (m_params.startsWith(QStringLiteral("%1=").arg(name))) {
        return m_params.section(QStringLiteral("%1=").arg(name), 1, 1).section(QLatin1Char(' '), 0, 0);
    } else if (m_params.contains(QStringLiteral(" %1=").arg(name))) {
        return m_params.section(QStringLiteral(" %1=").arg(name), 1, 1).section(QLatin1Char(' '), 0, 0);
    }
    return {};
}

bool RenderPresetModel::hasParam(const QString &name) const
{
    return !getParam(name).isEmpty();
}

RenderPresetModel::RateControl RenderPresetModel::videoRateControl() const
{
    QString vbufsize = getParam(QStringLiteral("vbufsize"));
    QString vcodec = getParam(QStringLiteral("vcodec"));
    if (!getParam(QStringLiteral("crf")).isEmpty()) {
        return !vbufsize.isEmpty()
                ? (vcodec.endsWith("_ videotoolbox") ? RateControl::Average : RateControl::Quality)
                : RateControl::Constrained;
    }
    if (!getParam(QStringLiteral("vq")).isEmpty()
            || !getParam(QStringLiteral("vglobal_quality")).isEmpty()
            || !getParam(QStringLiteral("qscale")).isEmpty()) {
        return vbufsize.isEmpty() ? RateControl::Quality : RateControl::Constrained;
    } else if (!vbufsize.isEmpty()) {
        return RateControl::Constant;
    }
    QString param = getParam(QStringLiteral("vb"));
    if (!param.isEmpty()) {
        return param.toInt() > 0 ? RateControl::Average : RateControl::Quality;
    }
    return RateControl::Unknown;
}

RenderPresetModel::RateControl RenderPresetModel::audioRateControl() const
{
    QString value = getParam(QStringLiteral("vbr"));
    if (!value.isEmpty()) {
        // libopus rate mode
        if (value == QStringLiteral("off")) {
            return RateControl::Constant;
        }
        if (value == QStringLiteral("constrained")) {
            return RateControl::Average;
        }
        return RateControl::Quality;
    }
    if (!getParam(QStringLiteral("aq")).isEmpty() || !getParam(QStringLiteral("compression_level")).isEmpty()) {
        return RateControl::Quality;
    }
    return RateControl::Constant;
}

QString RenderPresetModel::x265Params() const
{
    QString x265Params = getParam(QStringLiteral("x265-params"));
    QStringList newX265Params;
    if (hasParam(QStringLiteral("crf"))) {
        newX265Params.append(QStringLiteral("crf=%1").arg(getParam(QStringLiteral("crf"))));
    }
    if (videoRateControl() == RateControl::Constant && hasParam(QStringLiteral("vb"))) {
        QString vb = getParam(QStringLiteral("vb"));
        QString newVal;
        if (vb == QStringLiteral("%bitrate") || vb == QStringLiteral("%bitrate+'k")) {
            newVal = QStringLiteral("%bitrate");
        } else {
            newVal = vb.replace('k', QLatin1String("")).replace('M', QStringLiteral("000"));
        }
        newX265Params.append(QStringLiteral("bitrate=%1").arg(newVal));
        newX265Params.append(QStringLiteral("vbv-maxrate=%1").arg(newVal));
    } else if (videoRateControl() == RateControl::Constrained && hasParam(QStringLiteral("vmaxrate"))) {
        QString vmax = getParam(QStringLiteral("vmaxrate"));
        QString newVal;
        if (vmax == QStringLiteral("%bitrate") || vmax == QStringLiteral("%bitrate+'k")) {
            newVal = QStringLiteral("%bitrate");
        } else {
            newVal = vmax.replace('k', QLatin1String("")).replace('M', QStringLiteral("000"));
        }
        newX265Params.append(QStringLiteral("vbv-maxrate=%1").arg(newVal));
    }
    if (hasParam(QStringLiteral("vbufsize"))) {
        int val = getParam(QStringLiteral("vbufsize")).toInt();
        newX265Params.append(QStringLiteral("vbv-bufsize=%1").arg(val / 1024));
    }
    if (hasParam(QStringLiteral("bf"))) {
        newX265Params.append(QStringLiteral("bframes=%1").arg(getParam(QStringLiteral("bf"))));
    }
    if (hasParam(QStringLiteral("g"))) {
        newX265Params.append(QStringLiteral("keyint=%1").arg(getParam(QStringLiteral("g"))));
    }
    if (hasParam(QStringLiteral("top_field_first")) && getParam(QStringLiteral("progressive")).toInt() == 0) {
        int val = getParam(QStringLiteral("top_field_first")).toInt();
        newX265Params.append(QStringLiteral("interlace=%1").arg(val == 1 ? QStringLiteral("tff") : QStringLiteral("bff")));
    }
    if (hasParam(QStringLiteral("sc_threshold")) && getParam(QStringLiteral("sc_threshold")).toInt() == 0) {
        newX265Params.append(QStringLiteral("scenecut=0"));
    }
    if (!x265Params.isEmpty()) {
        newX265Params.append(x265Params);
    }
    return newX265Params.join(QStringLiteral(":"));
}

RenderPresetModel::InstallType RenderPresetModel::installType() const
{
    if (m_editable) {
        if (m_presetFile.endsWith(QLatin1String("customprofiles.xml"))) {
            return InstallType::Custom;
        } else {
            return InstallType::Download;
        }
    }
    return InstallType::BuildIn;
}

bool RenderPresetModel::hasFixedSize() const
{
    // TODO
    return hasParam(QStringLiteral("s"))
            || m_params.contains(QLatin1String("%dv_standard"));
}

QString RenderPresetModel::error() const
{
    return m_errors;
}

QString RenderPresetModel::warning() const
{
    return m_warnings;
}

int RenderPresetModel::estimateFileSize(int length)
{
489
    Q_UNUSED(length)
490
491
492
493
494
495
496
497
    // TODO
    /*RateControl vrc = videoRateControl();
    if (vrc == Average || vrc == Constant) {

        return m_defaultVBitrate.toInt() * length;
    }*/
    return -1;
}