projectclip.cpp 36.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
/*
Copyright (C) 2012  Till Theato <root@ttill.de>
Copyright (C) 2014  Jean-Baptiste Mardelle <jb@kdenlive.org>
This file is part of Kdenlive. See www.kdenlive.org.

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 2 of
the License or (at your option) version 3 or any later version
accepted by the membership of KDE e.V. (or its successor approved
11
by the membership of KDE e.V.), which shall act as a proxy
12 13 14 15 16 17 18 19 20 21 22 23
defined in Section 14 of version 3 of the license.

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/>.
*/

#include "projectclip.h"
24
#include "bin.h"
Nicolas Carion's avatar
Nicolas Carion committed
25
#include "core.h"
26 27
#include "doc/docundostack.hpp"
#include "doc/kdenlivedoc.h"
28
#include "doc/kthumb.h"
Nicolas Carion's avatar
Nicolas Carion committed
29
#include "effects/effectstack/model/effectstackmodel.hpp"
30 31
#include "jobs/jobmanager.h"
#include "jobs/thumbjob.hpp"
32 33
#include "jobs/loadjob.hpp"
#include <jobs/proxyclipjob.h>
34
#include "kdenlivesettings.h"
35
#include "lib/audio/audioStreamInfo.h"
36
#include "mltcontroller/clip.h"
37
#include "mltcontroller/clipcontroller.h"
38
#include "mltcontroller/clippropertiescontroller.h"
39
#include "model/markerlistmodel.hpp"
40
#include "profiles/profilemodel.hpp"
Nicolas Carion's avatar
Nicolas Carion committed
41
#include "project/projectcommands.h"
42
#include "project/projectmanager.h"
Nicolas Carion's avatar
Nicolas Carion committed
43 44 45 46
#include "projectfolder.h"
#include "projectitemmodel.h"
#include "projectsubclip.h"
#include "timecode.h"
Nicolas Carion's avatar
style  
Nicolas Carion committed
47
#include "timeline2/model/snapmodel.hpp"
Nicolas Carion's avatar
Nicolas Carion committed
48
#include "utils/KoIconUtils.h"
49
#include "utils/thumbnailcache.hpp"
50
#include "xml/xml.hpp"
51
#include <QPainter>
52
#include <kimagecache.h>
53

Laurent Montel's avatar
Laurent Montel committed
54
#include "kdenlive_debug.h"
55
#include <KLocalizedString>
56
#include <KMessageBox>
Nicolas Carion's avatar
Nicolas Carion committed
57 58 59 60 61
#include <QCryptographicHash>
#include <QDir>
#include <QDomElement>
#include <QFile>
#include <QtConcurrent>
Nicolas Carion's avatar
Nicolas Carion committed
62
#include <utility>
63

64 65
ProjectClip::ProjectClip(const QString &id, const QIcon &thumb, std::shared_ptr<ProjectItemModel> model, std::shared_ptr<Mlt::Producer> producer)
    : AbstractProjectItem(AbstractProjectItem::ClipItem, id, model)
66
    , ClipController(id, producer)
67
    , m_thumbsProducer(nullptr)
68
{
69
    m_markerModel = std::make_shared<MarkerListModel>(id, pCore->projectManager()->undoStack());
70
    m_clipStatus = StatusReady;
71 72 73 74
    m_name = clipName();
    m_duration = getStringDuration();
    m_date = date;
    m_description = ClipController::description();
75
    if (m_clipType == ClipType::Audio) {
76
        m_thumbnail = KoIconUtils::themedIcon(QStringLiteral("audio-x-generic"));
77 78 79
    } else {
        m_thumbnail = thumb;
    }
80 81 82
    if (m_clipType == ClipType::AV || m_clipType == ClipType::Audio || m_clipType == ClipType::Image || m_clipType == ClipType::Video || m_clipType == ClipType::Playlist || m_clipType == ClipType::TextTemplate) {
        pCore->bin()->addWatchFile(id, clipUrl());
    }
83 84
    // Make sure we have a hash for this clip
    hash();
85
    connect(m_markerModel.get(), &MarkerListModel::modelChanged, [&]() { setProducerProperty(QStringLiteral("kdenlive:markers"), m_markerModel->toJson()); });
86 87
    QString markers = getProducerProperty(QStringLiteral("kdenlive:markers"));
    if (!markers.isEmpty()) {
88 89
        QMetaObject::invokeMethod(m_markerModel.get(), "importFromJson", Qt::QueuedConnection, Q_ARG(const QString &, markers), Q_ARG(bool, true),
                                  Q_ARG(bool, false));
90
    }
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
91
    connectEffectStack();
92 93
}

94 95
// static
std::shared_ptr<ProjectClip> ProjectClip::construct(const QString &id, const QIcon &thumb, std::shared_ptr<ProjectItemModel> model,
96
                                                    std::shared_ptr<Mlt::Producer> producer)
97
{
98
    std::shared_ptr<ProjectClip> self(new ProjectClip(id, thumb, model, producer));
99
    baseFinishConstruct(self);
100
    model->loadSubClips(id, self->getPropertiesFromPrefix(QStringLiteral("kdenlive:clipzone.")));
101 102 103
    return self;
}

104
ProjectClip::ProjectClip(const QString &id, const QDomElement &description, const QIcon &thumb, std::shared_ptr<ProjectItemModel> model)
105
    : AbstractProjectItem(AbstractProjectItem::ClipItem, id, model)
106
    , ClipController(id)
107
    , m_thumbsProducer(nullptr)
108
{
109
    m_clipStatus = StatusWaiting;
110
    m_thumbnail = thumb;
111
    m_markerModel = std::make_shared<MarkerListModel>(m_binId, pCore->projectManager()->undoStack());
112
    if (description.hasAttribute(QStringLiteral("type"))) {
113
        m_clipType = (ClipType)description.attribute(QStringLiteral("type")).toInt();
114
        if (m_clipType == ClipType::Audio) {
115
            m_thumbnail = KoIconUtils::themedIcon(QStringLiteral("audio-x-generic"));
116
        }
117
    }
118
    m_temporaryUrl = getXmlProperty(description, QStringLiteral("resource"));
119
    QString clipName = getXmlProperty(description, QStringLiteral("kdenlive:clipname"));
120 121
    if (!clipName.isEmpty()) {
        m_name = clipName;
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
122
    } else if (!m_temporaryUrl.isEmpty()) {
123
        m_name = QFileInfo(m_temporaryUrl).fileName();
124 125
    } else {
        m_name = i18n("Untitled");
126
    }
127
    connect(m_markerModel.get(), &MarkerListModel::modelChanged, [&]() { setProducerProperty(QStringLiteral("kdenlive:markers"), m_markerModel->toJson()); });
128 129
}

130 131
std::shared_ptr<ProjectClip> ProjectClip::construct(const QString &id, const QDomElement &description, const QIcon &thumb,
                                                    std::shared_ptr<ProjectItemModel> model)
132
{
133
    std::shared_ptr<ProjectClip> self(new ProjectClip(id, description, thumb, model));
134 135 136 137
    baseFinishConstruct(self);
    return self;
}

138 139
ProjectClip::~ProjectClip()
{
140
    // controller is deleted in bincontroller
141 142 143
    if (m_clipType == ClipType::AV || m_clipType == ClipType::Audio || m_clipType == ClipType::Image || m_clipType == ClipType::Video || m_clipType == ClipType::Playlist || m_clipType == ClipType::TextTemplate) {
        pCore->bin()->removeWatchFile(clipId(), clipUrl());
    }
144
    m_thumbMutex.lock();
145
    m_requestedThumbs.clear();
146
    m_thumbMutex.unlock();
147
    m_thumbThread.waitForFinished();
148
    audioFrameCache.clear();
149 150 151 152 153
    // delete all timeline producers
    std::map<int, std::shared_ptr<Mlt::Producer>>::iterator itr = m_timelineProducers.begin();
    while (itr != m_timelineProducers.end()) {
        itr = m_timelineProducers.erase(itr);
    }
154 155
}

156 157
void ProjectClip::connectEffectStack()
{
158 159 160 161
    connect(m_effectStack.get(), &EffectStackModel::modelChanged, this, &ProjectClip::updateChildProducers);
    connect(m_effectStack.get(), &EffectStackModel::dataChanged, this, &ProjectClip::updateChildProducers);
    /*connect(m_effectStack.get(), &EffectStackModel::modelChanged, [&](){
        qDebug()<<"/ / / STACK CHANGED";
162
        updateChildProducers();
163
    });*/
164 165
}

166 167
QString ProjectClip::getToolTip() const
{
168
    return url();
169 170
}

171
QString ProjectClip::getXmlProperty(const QDomElement &producer, const QString &propertyName, const QString &defaultValue)
172
{
173
    QString value = defaultValue;
174
    QDomNodeList props = producer.elementsByTagName(QStringLiteral("property"));
175
    for (int i = 0; i < props.count(); ++i) {
176
        if (props.at(i).toElement().attribute(QStringLiteral("name")) == propertyName) {
177 178 179 180 181 182 183
            value = props.at(i).firstChild().nodeValue();
            break;
        }
    }
    return value;
}

184
void ProjectClip::updateAudioThumbnail(QVariantList audioLevels)
185
{
186
    std::swap(audioFrameCache, audioLevels); // avoid second copy
187
    m_audioThumbCreated = true;
188 189 190 191
    if (auto ptr = m_model.lock()) {
        emit std::static_pointer_cast<ProjectItemModel>(ptr)->refreshAudioThumbs(m_binId);
    }
    updateTimelineClips({TimelineModel::AudioLevelsRole});
192 193 194 195
}

bool ProjectClip::audioThumbCreated() const
{
196
    return (m_audioThumbCreated);
197 198
}

199 200
ClipType ProjectClip::clipType() const
{
201
    return m_clipType;
202 203
}

204 205
bool ProjectClip::hasParent(const QString &id) const
{
206 207
    std::shared_ptr<AbstractProjectItem> par = parent();
    while (par) {
208 209 210 211
        if (par->clipId() == id) {
            return true;
        }
        par = par->parent();
212 213 214 215
    }
    return false;
}

216
std::shared_ptr<ProjectClip> ProjectClip::clip(const QString &id)
217
{
Nicolas Carion's avatar
Nicolas Carion committed
218
    if (id == m_binId) {
219
        return std::static_pointer_cast<ProjectClip>(shared_from_this());
220
    }
221
    return std::shared_ptr<ProjectClip>();
222 223
}

224
std::shared_ptr<ProjectFolder> ProjectClip::folder(const QString &id)
225
{
226
    Q_UNUSED(id)
227
    return std::shared_ptr<ProjectFolder>();
228 229
}

230
std::shared_ptr<ProjectSubClip> ProjectClip::getSubClip(int in, int out)
231
{
232
    for (int i = 0; i < childCount(); ++i) {
233
        std::shared_ptr<ProjectSubClip> clip = std::static_pointer_cast<ProjectSubClip>(child(i))->subClip(in, out);
234 235 236 237
        if (clip) {
            return clip;
        }
    }
238
    return std::shared_ptr<ProjectSubClip>();
239 240
}

241 242 243
QStringList ProjectClip::subClipIds() const
{
    QStringList subIds;
244
    for (int i = 0; i < childCount(); ++i) {
245
        std::shared_ptr<AbstractProjectItem> clip = std::static_pointer_cast<AbstractProjectItem>(child(i));
246 247 248 249 250 251 252
        if (clip) {
            subIds << clip->clipId();
        }
    }
    return subIds;
}

253
std::shared_ptr<ProjectClip> ProjectClip::clipAt(int ix)
254
{
Nicolas Carion's avatar
Nicolas Carion committed
255
    if (ix == row()) {
256
        return std::static_pointer_cast<ProjectClip>(shared_from_this());
257
    }
258
    return std::shared_ptr<ProjectClip>();
259 260
}

261
/*bool ProjectClip::isValid() const
262
{
263 264
    return m_controller->isValid();
}*/
265

266 267
bool ProjectClip::hasUrl() const
{
268
    if ((m_clipType != ClipType::Color) && (m_clipType != ClipType::Unknown)) {
269
        return (!clipUrl().isEmpty());
270
    }
271 272 273
    return false;
}

274
const QString ProjectClip::url() const
275
{
276
    return clipUrl();
277 278
}

279
GenTime ProjectClip::duration() const
280
{
281
    return getPlaytime();
282 283
}

284 285 286
int ProjectClip::frameDuration() const
{
    GenTime d = duration();
287
    return d.frames(pCore->getCurrentFps());
288 289
}

290
void ProjectClip::reloadProducer(bool refreshOnly)
291
{
292 293 294
    // we find if there are some loading job on that clip
    int loadjobId = -1;
    pCore->jobManager()->hasPendingJob(clipId(), AbstractClipJob::LOADJOB, &loadjobId);
295
    if (refreshOnly) {
296 297
        // In that case, we only want a new thumbnail.
        // We thus set up a thumb job. We must make sure that there is no pending LOADJOB
298
        // Clear cache first
299
        m_thumbsProducer.reset();
300 301
        ThumbnailCache::get()->invalidateThumbsForClip(clipId());
        pCore->jobManager()->startJob<ThumbJob>({clipId()}, loadjobId, QString(), 150, -1, true, true);
302 303

    } else {
304 305 306 307
        //TODO: check if another load job is running?
        QDomDocument doc;
        QDomElement xml = toXml(doc);
        if (!xml.isNull()) {
308
            m_thumbsProducer.reset();
309
            ThumbnailCache::get()->invalidateThumbsForClip(clipId());
310
            int loadJob = pCore->jobManager()->startJob<LoadJob>({clipId()}, loadjobId, QString(), xml);
311
            pCore->jobManager()->startJob<ThumbJob>({clipId()}, loadJob, QString(), 150, -1, true, true);
312
        }
313
    }
314 315
}

316
QDomElement ProjectClip::toXml(QDomDocument &document, bool includeMeta)
317
{
318 319
    getProducerXML(document, includeMeta);
    QDomElement prod = document.documentElement().firstChildElement(QStringLiteral("producer"));
320
    if (m_clipType != ClipType::Unknown) {
321
        prod.setAttribute(QStringLiteral("type"), (int)m_clipType);
322
    }
323
    return prod;
324 325
}

Laurent Montel's avatar
Laurent Montel committed
326
void ProjectClip::setThumbnail(const QImage &img)
327
{
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
328 329
    QPixmap thumb = roundedPixmap(QPixmap::fromImage(img));
    if (hasProxy() && !thumb.isNull()) {
330
        // Overlay proxy icon
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
331
        QPainter p(&thumb);
332
        QColor c(220, 220, 10, 200);
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
333
        QRect r(0, 0, thumb.height() / 2.5, thumb.height() / 2.5);
334 335 336 337 338 339 340 341
        p.fillRect(r, c);
        QFont font = p.font();
        font.setPixelSize(r.height());
        font.setBold(true);
        p.setFont(font);
        p.setPen(Qt::black);
        p.drawText(r, Qt::AlignCenter, i18nc("The first letter of Proxy, used as abbreviation", "P"));
    }
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
342
    m_thumbnail = QIcon(thumb);
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
343 344 345
    if (auto ptr = m_model.lock()) {
        std::static_pointer_cast<ProjectItemModel>(ptr)->onItemUpdated(std::static_pointer_cast<ProjectClip>(shared_from_this()), AbstractProjectItem::DataThumbnail);
    }
346 347
}

348 349 350 351 352
QPixmap ProjectClip::thumbnail(int width, int height)
{
    return m_thumbnail.pixmap(width, height);
}

353
bool ProjectClip::setProducer(std::shared_ptr<Mlt::Producer> producer, bool replaceProducer)
354
{
Vincent Pinon's avatar
Vincent Pinon committed
355
    Q_UNUSED(replaceProducer)
356
    qDebug() << "################### ProjectClip::setproducer";
357
    QMutexLocker locker(&m_producerMutex);
Nicolas Carion's avatar
Nicolas Carion committed
358
    updateProducer(std::move(producer));
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
359
    connectEffectStack();
360

361 362 363
    // Update info
    if (m_name.isEmpty()) {
        m_name = clipName();
364
    }
365 366 367
    m_date = date;
    m_description = ClipController::description();
    m_temporaryUrl.clear();
368
    if (m_clipType == ClipType::Audio) {
369
        m_thumbnail = KoIconUtils::themedIcon(QStringLiteral("audio-x-generic"));
370
    } else if (m_clipType == ClipType::Image) {
371
        if (getProducerIntProperty(QStringLiteral("meta.media.width")) < 8 || getProducerIntProperty(QStringLiteral("meta.media.height")) < 8) {
372 373
            KMessageBox::information(QApplication::activeWindow(),
                                     i18n("Image dimension smaller than 8 pixels.\nThis is not correctly supported by our video framework."));
374
        }
375
    }
376
    m_duration = getStringDuration();
377
    m_clipStatus = StatusReady;
378
    if (!hasProxy()) {
Nicolas Carion's avatar
Nicolas Carion committed
379
        if (auto ptr = m_model.lock()) emit std::static_pointer_cast<ProjectItemModel>(ptr)->refreshPanel(m_binId);
380
    }
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
381
    if (auto ptr = m_model.lock()) {
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
382
        std::static_pointer_cast<ProjectItemModel>(ptr)->onItemUpdated(std::static_pointer_cast<ProjectClip>(shared_from_this()), AbstractProjectItem::DataDuration);
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
383
    }
384
    // Make sure we have a hash for this clip
385
    getFileHash();
386 387 388
    if (m_clipType == ClipType::AV || m_clipType == ClipType::Audio || m_clipType == ClipType::Image || m_clipType == ClipType::Video || m_clipType == ClipType::Playlist || m_clipType == ClipType::TextTemplate) {
        pCore->bin()->addWatchFile(clipId(), clipUrl());
    }
389 390
    // set parent again (some info need to be stored in producer)
    updateParent(parentItem().lock());
391
    return true;
392 393
}

394
std::shared_ptr<Mlt::Producer> ProjectClip::thumbProducer()
395 396 397 398 399
{
    QMutexLocker locker(&m_producerMutex);
    if (m_thumbsProducer) {
        return m_thumbsProducer;
    }
400
    if (clipType() == ClipType::Unknown) {
Laurent Montel's avatar
Laurent Montel committed
401
        return nullptr;
402
    }
403 404
    std::shared_ptr<Mlt::Producer> prod = originalProducer();
    if (!prod->is_valid()) {
Laurent Montel's avatar
Laurent Montel committed
405
        return nullptr;
406
    }
407
    if (KdenliveSettings::gpu_accel()) {
408
        //TODO: when the original producer changes, we must reload this thumb producer
409
        Clip clip(*prod.get());
410
        m_thumbsProducer = std::make_shared<Mlt::Producer>(clip.softClone(ClipController::getPassPropertiesList()));
411 412
        Mlt::Filter scaler(*prod->profile(), "swscale");
        Mlt::Filter converter(*prod->profile(), "avcolor_space");
413 414
        m_thumbsProducer->attach(scaler);
        m_thumbsProducer->attach(converter);
415
    } else {
416
        m_thumbsProducer = cloneProducer(pCore->thumbProfile());
417 418 419 420
    }
    return m_thumbsProducer;
}

421 422 423
std::shared_ptr<Mlt::Producer> ProjectClip::timelineProducer(PlaylistState::ClipState state, int track)
{
    if (!m_service.startsWith(QLatin1String("avformat"))) {
424
        std::shared_ptr<Mlt::Producer> prod(originalProducer()->cut());
425 426 427 428 429
        int length = getProducerIntProperty(QStringLiteral("kdenlive:duration"));
        if (length > 0) {
            prod->set_in_and_out(0, length);
        }
        return prod;
430 431 432
    }
    if (state == PlaylistState::VideoOnly) {
        if (m_timelineProducers.count(0) > 0) {
433
            return std::shared_ptr<Mlt::Producer>(m_timelineProducers.find(0)->second->cut());
434 435
        }
        std::shared_ptr<Mlt::Producer> videoProd = cloneProducer();
436
        videoProd->set("audio_index", -1);
437
        m_timelineProducers[0] = videoProd;
438
        return std::shared_ptr<Mlt::Producer>(videoProd->cut());
439 440 441
    }
    if (state == PlaylistState::AudioOnly) {
        if (m_timelineProducers.count(-track) > 0) {
442
            return std::shared_ptr<Mlt::Producer>(m_timelineProducers.find(-track)->second->cut());
443 444
        }
        std::shared_ptr<Mlt::Producer> audioProd = cloneProducer();
445
        audioProd->set("video_index", -1);
446
        m_timelineProducers[-track] = audioProd;
447
        return std::shared_ptr<Mlt::Producer>(audioProd->cut());
448 449
    }
    if (m_timelineProducers.count(track) > 0) {
450
        return std::shared_ptr<Mlt::Producer>(m_timelineProducers.find(track)->second->cut());
451 452 453
    }
    std::shared_ptr<Mlt::Producer> normalProd = cloneProducer();
    m_timelineProducers[track] = normalProd;
454
    return std::shared_ptr<Mlt::Producer>(normalProd->cut());
455 456
}

457
std::shared_ptr<Mlt::Producer> ProjectClip::cloneProducer(Mlt::Profile *destProfile)
458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476
{
    Mlt::Consumer c(*m_masterProducer->profile(), "xml", "string");
    Mlt::Service s(m_masterProducer->get_service());
    int ignore = s.get_int("ignore_points");
    if (ignore) {
        s.set("ignore_points", 0);
    }
    c.connect(s);
    c.set("time_format", "frames");
    c.set("no_meta", 1);
    c.set("no_root", 1);
    c.set("no_profile", 1);
    c.set("root", "/");
    c.set("store", "kdenlive");
    c.start();
    if (ignore) {
        s.set("ignore_points", ignore);
    }
    const QByteArray clipXml = c.get("string");
477
    std::shared_ptr<Mlt::Producer> prod(new Mlt::Producer(destProfile ? *destProfile : *m_masterProducer->profile(), "xml-string", clipXml.constData()));
478 479 480
    if (strcmp(prod->get("mlt_service"), "avformat") == 0) {
        prod->set("mlt_service", "avformat-novalidate");
    }
481
    return prod;
482 483
}

484
bool ProjectClip::isReady() const
485
{
486
    return m_clipStatus == StatusReady;
487 488
}

489
/*void ProjectClip::setZone(const QPoint &zone)
490 491
{
    m_zone = zone;
492
}*/
493 494 495

QPoint ProjectClip::zone() const
{
496 497
    int x = getProducerIntProperty(QStringLiteral("kdenlive:zone_in"));
    int y = getProducerIntProperty(QStringLiteral("kdenlive:zone_out"));
498 499 500
    if (y <= x) {
        y = getFramePlaytime() - 1;
    }
501
    return QPoint(x, y);
502 503 504 505
}

const QString ProjectClip::hash()
{
506
    QString clipHash = getProducerProperty(QStringLiteral("kdenlive:file_hash"));
507 508
    if (!clipHash.isEmpty()) {
        return clipHash;
509
    }
510
    return getFileHash();
511 512
}

513
const QString ProjectClip::getFileHash()
514
{
515 516
    QByteArray fileData;
    QByteArray fileHash;
517
    switch (m_clipType) {
518
    case ClipType::SlideShow:
519
        fileData = clipUrl().toUtf8();
520 521
        fileHash = QCryptographicHash::hash(fileData, QCryptographicHash::Md5);
        break;
522
    case ClipType::Text:
523
    case ClipType::TextTemplate:
524
        fileData = getProducerProperty(QStringLiteral("xmldata")).toUtf8();
525 526
        fileHash = QCryptographicHash::hash(fileData, QCryptographicHash::Md5);
        break;
527
    case ClipType::QText:
528
        fileData = getProducerProperty(QStringLiteral("text")).toUtf8();
529 530
        fileHash = QCryptographicHash::hash(fileData, QCryptographicHash::Md5);
        break;
531
    case ClipType::Color:
532
        fileData = getProducerProperty(QStringLiteral("resource")).toUtf8();
533 534 535
        fileHash = QCryptographicHash::hash(fileData, QCryptographicHash::Md5);
        break;
    default:
536
        QFile file(clipUrl());
537 538 539 540 541
        if (file.open(QIODevice::ReadOnly)) { // write size and hash only if resource points to a file
            /*
             * 1 MB = 1 second per 450 files (or faster)
             * 10 MB = 9 seconds per 450 files (or faster)
             */
542 543
            if (file.size() > 2000000) {
                fileData = file.read(1000000);
544
                if (file.seek(file.size() - 1000000)) {
545
                    fileData.append(file.readAll());
546 547
                }
            } else {
548
                fileData = file.readAll();
549
            }
550
            file.close();
Nicolas Carion's avatar
Nicolas Carion committed
551
            ClipController::setProducerProperty(QStringLiteral("kdenlive:file_size"), QString::number(file.size()));
552
            fileHash = QCryptographicHash::hash(fileData, QCryptographicHash::Md5);
553 554 555 556
        }
        break;
    }
    if (fileHash.isEmpty()) {
557
        qDebug()<<"// WARNING EMPTY CLIP HASH: ";
558
        return QString();
559 560
    }
    QString result = fileHash.toHex();
Nicolas Carion's avatar
Nicolas Carion committed
561
    ClipController::setProducerProperty(QStringLiteral("kdenlive:file_hash"), result);
562
    return result;
563
}
564 565 566

double ProjectClip::getOriginalFps() const
{
567
    return originalFps();
568
}
569 570 571

bool ProjectClip::hasProxy() const
{
572
    QString proxy = getProducerProperty(QStringLiteral("kdenlive:proxy"));
573
    return proxy.size() > 2;
574 575
}

Laurent Montel's avatar
Laurent Montel committed
576
void ProjectClip::setProperties(const QMap<QString, QString> &properties, bool refreshPanel)
577 578
{
    QMapIterator<QString, QString> i(properties);
Laurent Montel's avatar
Laurent Montel committed
579
    QMap<QString, QString> passProperties;
580
    bool refreshAnalysis = false;
581
    bool reload = false;
582
    bool refreshOnly = true;
583 584
    // Some properties also need to be passed to track producers
    QStringList timelineProperties;
Laurent Montel's avatar
Laurent Montel committed
585 586
    if (properties.contains(QStringLiteral("templatetext"))) {
        m_description = properties.value(QStringLiteral("templatetext"));
587
        if (auto ptr = m_model.lock())
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
588
            std::static_pointer_cast<ProjectItemModel>(ptr)->onItemUpdated(std::static_pointer_cast<ProjectClip>(shared_from_this()), AbstractProjectItem::ClipStatus);
589 590
        refreshPanel = true;
    }
Nicolas Carion's avatar
Nicolas Carion committed
591 592 593 594
    timelineProperties << QStringLiteral("force_aspect_ratio") << QStringLiteral("video_index") << QStringLiteral("audio_index")
                       << QStringLiteral("set.force_full_luma") << QStringLiteral("full_luma") << QStringLiteral("threads")
                       << QStringLiteral("force_colorspace") << QStringLiteral("force_tff") << QStringLiteral("force_progressive")
                       << QStringLiteral("force_fps");
595
    QStringList keys;
Nicolas Carion's avatar
Nicolas Carion committed
596 597
    keys << QStringLiteral("luma_duration") << QStringLiteral("luma_file") << QStringLiteral("fade") << QStringLiteral("ttl") << QStringLiteral("softness")
         << QStringLiteral("crop") << QStringLiteral("animation");
598 599
    while (i.hasNext()) {
        i.next();
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
600
        setProducerProperty(i.key(), i.value());
601
        if (m_clipType == ClipType::SlideShow && keys.contains(i.key())) {
602
            reload = true;
603
            refreshOnly = false;
604
        }
605 606 607
        if (i.key().startsWith(QLatin1String("kdenlive:clipanalysis"))) {
            refreshAnalysis = true;
        }
608 609 610
        if (timelineProperties.contains(i.key())) {
            passProperties.insert(i.key(), i.value());
        }
611
    }
612 613
    if (properties.contains(QStringLiteral("kdenlive:proxy"))) {
        QString value = properties.value(QStringLiteral("kdenlive:proxy"));
614
        // If value is "-", that means user manually disabled proxy on this clip
615
        if (value.isEmpty() || value == QLatin1String("-")) {
616
            // reset proxy
617 618
            pCore->jobManager()->discardJobs(clipId(), AbstractClipJob::PROXYJOB);
            reloadProducer();
619
        } else {
620
            // A proxy was requested, make sure to keep original url
621
            setProducerProperty(QStringLiteral("kdenlive:originalurl"), url());
622
            pCore->jobManager()->startJob<ProxyJob>({clipId()}, -1, QString());
623
        }
Nicolas Carion's avatar
Nicolas Carion committed
624 625
    } else if (properties.contains(QStringLiteral("resource")) || properties.contains(QStringLiteral("templatetext")) ||
               properties.contains(QStringLiteral("autorotate"))) {
626
        // Clip resource changed, update thumbnail
627
        if (m_clipType != ClipType::Color) {
628
            reloadProducer();
629 630
        } else {
            reload = true;
631
        }
632
    }
633
    if (properties.contains(QStringLiteral("xmldata")) || !passProperties.isEmpty()) {
634
        reload = true;
635
    }
636 637 638
    if (refreshAnalysis) {
        emit refreshAnalysisPanel();
    }
639
    if (properties.contains(QStringLiteral("length")) || properties.contains(QStringLiteral("kdenlive:duration"))) {
640
        m_duration = getStringDuration();
641
        if (auto ptr = m_model.lock())
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
642
            std::static_pointer_cast<ProjectItemModel>(ptr)->onItemUpdated(std::static_pointer_cast<ProjectClip>(shared_from_this()), AbstractProjectItem::DataDuration);
643 644
        refreshOnly = false;
        reload = true;
645 646
    }

647 648
    if (properties.contains(QStringLiteral("kdenlive:clipname"))) {
        m_name = properties.value(QStringLiteral("kdenlive:clipname"));
649
        refreshPanel = true;
650
        if (auto ptr = m_model.lock()) {
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
651
            std::static_pointer_cast<ProjectItemModel>(ptr)->onItemUpdated(std::static_pointer_cast<ProjectClip>(shared_from_this()), AbstractProjectItem::DataName);
652 653 654
        }
        // update timeline clips
        updateTimelineClips(QVector<int>() << TimelineModel::NameRole);
655
    }
656 657 658 659
    if (refreshPanel) {
        // Some of the clip properties have changed through a command, update properties panel
        emit refreshPropertiesPanel();
    }
660
    if (reload) {
661
        // producer has changed, refresh monitor and thumbnail
662
        reloadProducer(refreshOnly);
663
        if (auto ptr = m_model.lock()) emit std::static_pointer_cast<ProjectItemModel>(ptr)->refreshClip(m_binId);
664
    }
665
    if (!passProperties.isEmpty()) {
666
        if (auto ptr = m_model.lock()) emit std::static_pointer_cast<ProjectItemModel>(ptr)->updateTimelineProducers(m_binId, passProperties);
667
    }
668 669
}

670 671
ClipPropertiesController *ProjectClip::buildProperties(QWidget *parent)
{
672 673
    auto ptr = m_model.lock();
    Q_ASSERT(ptr);
674
    ClipPropertiesController *panel = new ClipPropertiesController(static_cast<ClipController *>(this), parent);
Laurent Montel's avatar
Laurent Montel committed
675 676
    connect(this, &ProjectClip::refreshPropertiesPanel, panel, &ClipPropertiesController::slotReloadProperties);
    connect(this, &ProjectClip::refreshAnalysisPanel, panel, &ClipPropertiesController::slotFillAnalysisData);
677