projectclip.cpp 45.3 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
#include "jobs/jobmanager.h"
31
#include "jobs/loadjob.hpp"
32
#include "jobs/thumbjob.hpp"
33
#include "kdenlivesettings.h"
34
#include "lib/audio/audioStreamInfo.h"
35
#include "mltcontroller/clip.h"
36
#include "mltcontroller/clipcontroller.h"
37
#include "mltcontroller/clippropertiescontroller.h"
38
#include "model/markerlistmodel.hpp"
39
#include "profiles/profilemodel.hpp"
Nicolas Carion's avatar
Nicolas Carion committed
40
#include "project/projectcommands.h"
41
#include "project/projectmanager.h"
Nicolas Carion's avatar
Nicolas Carion committed
42 43 44 45
#include "projectfolder.h"
#include "projectitemmodel.h"
#include "projectsubclip.h"
#include "timecode.h"
Nicolas Carion's avatar
style  
Nicolas Carion committed
46
#include "timeline2/model/snapmodel.hpp"
Nicolas Carion's avatar
Nicolas Carion committed
47
#include "utils/KoIconUtils.h"
48
#include "utils/thumbnailcache.hpp"
49
#include "xml/xml.hpp"
50
#include <QPainter>
51
#include <jobs/proxyclipjob.h>
52
#include <kimagecache.h>
53

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

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

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

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

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

136 137
ProjectClip::~ProjectClip()
{
138
    // controller is deleted in bincontroller
139
    m_thumbMutex.lock();
140
    m_requestedThumbs.clear();
141
    m_thumbMutex.unlock();
142
    m_thumbThread.waitForFinished();
143
    audioFrameCache.clear();
144 145
}

146 147
void ProjectClip::connectEffectStack()
{
148 149 150 151
    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";
152
        updateChildProducers();
153
    });*/
154 155
}

156 157
QString ProjectClip::getToolTip() const
{
158
    return url();
159 160
}

161
QString ProjectClip::getXmlProperty(const QDomElement &producer, const QString &propertyName, const QString &defaultValue)
162
{
163
    QString value = defaultValue;
164
    QDomNodeList props = producer.elementsByTagName(QStringLiteral("property"));
165
    for (int i = 0; i < props.count(); ++i) {
166
        if (props.at(i).toElement().attribute(QStringLiteral("name")) == propertyName) {
167 168 169 170 171 172 173
            value = props.at(i).firstChild().nodeValue();
            break;
        }
    }
    return value;
}

174
void ProjectClip::updateAudioThumbnail(QVariantList audioLevels)
175
{
176
    std::swap(audioFrameCache, audioLevels); // avoid second copy
177
    m_audioThumbCreated = true;
178 179 180 181
    if (auto ptr = m_model.lock()) {
        emit std::static_pointer_cast<ProjectItemModel>(ptr)->refreshAudioThumbs(m_binId);
    }
    updateTimelineClips({TimelineModel::AudioLevelsRole});
182 183 184 185
}

bool ProjectClip::audioThumbCreated() const
{
186
    return (m_audioThumbCreated);
187 188
}

189
ClipType::ProducerType ProjectClip::clipType() const
190
{
191
    return m_clipType;
192 193
}

194 195
bool ProjectClip::hasParent(const QString &id) const
{
196 197
    std::shared_ptr<AbstractProjectItem> par = parent();
    while (par) {
198 199 200 201
        if (par->clipId() == id) {
            return true;
        }
        par = par->parent();
202 203 204 205
    }
    return false;
}

206
std::shared_ptr<ProjectClip> ProjectClip::clip(const QString &id)
207
{
Nicolas Carion's avatar
Nicolas Carion committed
208
    if (id == m_binId) {
209
        return std::static_pointer_cast<ProjectClip>(shared_from_this());
210
    }
211
    return std::shared_ptr<ProjectClip>();
212 213
}

214
std::shared_ptr<ProjectFolder> ProjectClip::folder(const QString &id)
215
{
216
    Q_UNUSED(id)
217
    return std::shared_ptr<ProjectFolder>();
218 219
}

220
std::shared_ptr<ProjectSubClip> ProjectClip::getSubClip(int in, int out)
221
{
222
    for (int i = 0; i < childCount(); ++i) {
223
        std::shared_ptr<ProjectSubClip> clip = std::static_pointer_cast<ProjectSubClip>(child(i))->subClip(in, out);
224 225 226 227
        if (clip) {
            return clip;
        }
    }
228
    return std::shared_ptr<ProjectSubClip>();
229 230
}

231 232 233
QStringList ProjectClip::subClipIds() const
{
    QStringList subIds;
234
    for (int i = 0; i < childCount(); ++i) {
235
        std::shared_ptr<AbstractProjectItem> clip = std::static_pointer_cast<AbstractProjectItem>(child(i));
236 237 238 239 240 241 242
        if (clip) {
            subIds << clip->clipId();
        }
    }
    return subIds;
}

243
std::shared_ptr<ProjectClip> ProjectClip::clipAt(int ix)
244
{
Nicolas Carion's avatar
Nicolas Carion committed
245
    if (ix == row()) {
246
        return std::static_pointer_cast<ProjectClip>(shared_from_this());
247
    }
248
    return std::shared_ptr<ProjectClip>();
249 250
}

251
/*bool ProjectClip::isValid() const
252
{
253 254
    return m_controller->isValid();
}*/
255

256 257
bool ProjectClip::hasUrl() const
{
258
    if ((m_clipType != ClipType::Color) && (m_clipType != ClipType::Unknown)) {
259
        return (!clipUrl().isEmpty());
260
    }
261 262 263
    return false;
}

264
const QString ProjectClip::url() const
265
{
266
    return clipUrl();
267 268
}

269
GenTime ProjectClip::duration() const
270
{
271
    return getPlaytime();
272 273
}

274 275 276
int ProjectClip::frameDuration() const
{
    GenTime d = duration();
277
    return d.frames(pCore->getCurrentFps());
278 279
}

280
void ProjectClip::reloadProducer(bool refreshOnly)
281
{
282 283 284
    // we find if there are some loading job on that clip
    int loadjobId = -1;
    pCore->jobManager()->hasPendingJob(clipId(), AbstractClipJob::LOADJOB, &loadjobId);
285
    if (refreshOnly) {
286 287
        // 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
288
        // Clear cache first
289
        m_thumbsProducer.reset();
290 291
        ThumbnailCache::get()->invalidateThumbsForClip(clipId());
        pCore->jobManager()->startJob<ThumbJob>({clipId()}, loadjobId, QString(), 150, -1, true, true);
292 293

    } else {
294
        // TODO: check if another load job is running?
295 296 297
        QDomDocument doc;
        QDomElement xml = toXml(doc);
        if (!xml.isNull()) {
298
            m_thumbsProducer.reset();
299
            ThumbnailCache::get()->invalidateThumbsForClip(clipId());
300
            int loadJob = pCore->jobManager()->startJob<LoadJob>({clipId()}, loadjobId, QString(), xml);
301
            pCore->jobManager()->startJob<ThumbJob>({clipId()}, loadJob, QString(), 150, -1, true, true);
302
        }
303
    }
304 305
}

306
QDomElement ProjectClip::toXml(QDomDocument &document, bool includeMeta)
307
{
308 309
    getProducerXML(document, includeMeta);
    QDomElement prod = document.documentElement().firstChildElement(QStringLiteral("producer"));
310
    if (m_clipType != ClipType::Unknown) {
311
        prod.setAttribute(QStringLiteral("type"), (int)m_clipType);
312
    }
313
    return prod;
314 315
}

Laurent Montel's avatar
Laurent Montel committed
316
void ProjectClip::setThumbnail(const QImage &img)
317
{
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
318 319
    QPixmap thumb = roundedPixmap(QPixmap::fromImage(img));
    if (hasProxy() && !thumb.isNull()) {
320
        // Overlay proxy icon
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
321
        QPainter p(&thumb);
322
        QColor c(220, 220, 10, 200);
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
323
        QRect r(0, 0, thumb.height() / 2.5, thumb.height() / 2.5);
324 325 326 327 328 329 330 331
        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
332
    m_thumbnail = QIcon(thumb);
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
333
    if (auto ptr = m_model.lock()) {
334 335
        std::static_pointer_cast<ProjectItemModel>(ptr)->onItemUpdated(std::static_pointer_cast<ProjectClip>(shared_from_this()),
                                                                       AbstractProjectItem::DataThumbnail);
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
336
    }
337 338
}

339 340 341 342 343
QPixmap ProjectClip::thumbnail(int width, int height)
{
    return m_thumbnail.pixmap(width, height);
}

344
bool ProjectClip::setProducer(std::shared_ptr<Mlt::Producer> producer, bool replaceProducer)
345
{
Vincent Pinon's avatar
Vincent Pinon committed
346
    Q_UNUSED(replaceProducer)
347
    qDebug() << "################### ProjectClip::setproducer";
348
    QMutexLocker locker(&m_producerMutex);
Nicolas Carion's avatar
Nicolas Carion committed
349
    updateProducer(std::move(producer));
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
350
    connectEffectStack();
351

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

384
std::shared_ptr<Mlt::Producer> ProjectClip::thumbProducer()
385 386 387 388
{
    if (m_thumbsProducer) {
        return m_thumbsProducer;
    }
389
    if (clipType() == ClipType::Unknown) {
Laurent Montel's avatar
Laurent Montel committed
390
        return nullptr;
391
    }
392 393
    std::shared_ptr<Mlt::Producer> prod = originalProducer();
    if (!prod->is_valid()) {
Laurent Montel's avatar
Laurent Montel committed
394
        return nullptr;
395
    }
396
    if (KdenliveSettings::gpu_accel()) {
397
        // TODO: when the original producer changes, we must reload this thumb producer
398
        Clip clip(*prod.get());
399
        m_thumbsProducer = std::make_shared<Mlt::Producer>(clip.softClone(ClipController::getPassPropertiesList()));
400 401
        Mlt::Filter scaler(*prod->profile(), "swscale");
        Mlt::Filter converter(*prod->profile(), "avcolor_space");
402 403
        m_thumbsProducer->attach(scaler);
        m_thumbsProducer->attach(converter);
404
    } else {
405
        m_thumbsProducer = cloneProducer(pCore->thumbProfile());
406 407 408 409
    }
    return m_thumbsProducer;
}

410 411 412
void ProjectClip::createVideoMasterProducer()
{
    if (!m_videoProducer) {
413 414 415 416 417 418
        m_videoProducer = std::shared_ptr<Mlt::Producer>(m_masterProducer->cut());
        if (hasAudio()) {
            // disable audio but activate video
            m_videoProducer->set("set.test_audio", 1);
            m_videoProducer->set("set.test_image", 0);
        }
419 420
    }
}
421

Nicolas Carion's avatar
Nicolas Carion committed
422 423 424 425 426 427
void ProjectClip::createDisabledMasterProducer()
{
    if (!m_disabledProducer) {
        m_disabledProducer = cloneProducer(&pCore->getCurrentProfile()->profile());
        m_disabledProducer->set("set.test_audio", 1);
        m_disabledProducer->set("set.test_image", 1);
428
        m_effectStack->addService(m_disabledProducer);
Nicolas Carion's avatar
Nicolas Carion committed
429 430
    }
}
431
std::shared_ptr<Mlt::Producer> ProjectClip::getTimelineProducer(int clipId, PlaylistState::ClipState state, double speed)
432
{
433
    qDebug() << "producer request"<<clipId<<speed;
434 435 436
    if (qFuzzyCompare(speed, 1.0)) {
        // we are requesting a normal speed producer
        // We can first cleen the speed producers we have for the current id
437 438 439 440
        if (m_timewarpProducers.count(clipId) > 0) {
            m_effectStack->removeService(m_timewarpProducers[clipId]);
            m_timewarpProducers.erase(clipId);
        }
441 442 443 444 445 446
        if (state == PlaylistState::AudioOnly) {
            // We need to get an audio producer, if none exists
            if (m_audioProducers.count(clipId) == 0) {
                m_audioProducers[clipId] = cloneProducer(&pCore->getCurrentProfile()->profile());
                m_audioProducers[clipId]->set("set.test_audio", 0);
                m_audioProducers[clipId]->set("set.test_image", 1);
447
                m_effectStack->addService(m_audioProducers[clipId]);
448 449 450
            }
            return std::shared_ptr<Mlt::Producer>(m_audioProducers[clipId]->cut());
        }
451 452 453 454
        if (m_audioProducers.count(clipId) > 0) {
            m_effectStack->removeService(m_audioProducers[clipId]);
            m_audioProducers.erase(clipId);
        }
Nicolas Carion's avatar
Nicolas Carion committed
455 456 457
        if (state == PlaylistState::VideoOnly) {
            // we return the video producer
            createVideoMasterProducer();
458 459
            int duration = m_masterProducer->get_int("kdenlive:duration");
            return std::shared_ptr<Mlt::Producer>(m_videoProducer->cut(-1, duration > 0 ? duration: -1));
Nicolas Carion's avatar
Nicolas Carion committed
460 461 462
        }
        Q_ASSERT(state == PlaylistState::Disabled);
        createDisabledMasterProducer();
463 464
        int duration = m_masterProducer->get_int("kdenlive:duration");
        return std::shared_ptr<Mlt::Producer>(m_disabledProducer->cut(-1, duration > 0 ? duration: -1));
465 466 467
    }

    // in that case, we need to create a warp producer, if we don't have one
468 469 470 471
    if (m_audioProducers.count(clipId) > 0) {
        m_effectStack->removeService(m_audioProducers[clipId]);
        m_audioProducers.erase(clipId);
    }
472 473 474

    std::shared_ptr<Mlt::Producer> warpProducer;
    if (m_timewarpProducers.count(clipId) > 0) {
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
475 476
        // remove in all cases, we add it unconditionally anyways
        m_effectStack->removeService(m_timewarpProducers[clipId]);
477 478 479
        if (qFuzzyCompare(m_timewarpProducers[clipId]->get_double("warp_speed"), speed)) {
            // the producer we have is good, use it !
            warpProducer = m_timewarpProducers[clipId];
480
            qDebug() << "Reusing producer!";
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
481 482
        } else {
            m_timewarpProducers.erase(clipId);
483 484 485
        }
    }
    if (!warpProducer) {
486 487
        QLocale locale;
        QString resource = QString("timewarp:%1:%2").arg(locale.toString(speed)).arg(originalProducer()->get("resource"));
488
        warpProducer.reset(new Mlt::Producer(*originalProducer()->profile(), resource.toUtf8().constData()));
489
        qDebug() << "new producer!";
490 491
    }

492
    qDebug() << "warp LENGTH" << warpProducer->get_length();
493 494 495 496 497 498 499 500 501
    warpProducer->set("set.test_audio", 1);
    warpProducer->set("set.test_image", 1);
    if (state == PlaylistState::AudioOnly) {
        warpProducer->set("set.test_audio", 0);
    }
    if (state == PlaylistState::VideoOnly) {
        warpProducer->set("set.test_image", 0);
    }
    m_timewarpProducers[clipId] = warpProducer;
502
    m_effectStack->addService(m_timewarpProducers[clipId]);
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
503
    return std::shared_ptr<Mlt::Producer>(warpProducer->cut());
504 505 506
}

std::pair<std::shared_ptr<Mlt::Producer>, bool> ProjectClip::giveMasterAndGetTimelineProducer(int clipId, std::shared_ptr<Mlt::Producer> master,
507
                                                                                              PlaylistState::ClipState state)
508 509 510 511 512 513 514 515 516 517 518 519
{
    int in = master->get_in();
    int out = master->get_out();
    if (master->parent().is_valid()) {
        // in that case, we have a cut
        // check whether it's a timewarp
        double speed = 1.0;
        double timeWarp = false;
        if (QString::fromUtf8(master->parent().get("mlt_service")) == QLatin1String("timewarp")) {
            speed = master->parent().get_double("warp_speed");
            timeWarp = true;
        }
520
        if (master->parent().get_int("_loaded") == 1) {
521 522
            // we already have a clip that shares the same master

Vincent Pinon's avatar
Vincent Pinon committed
523
            if (state == PlaylistState::AudioOnly || !qFuzzyIsNull(timeWarp)) {
524
                // In that case, we must create copies
525 526
                std::shared_ptr<Mlt::Producer> prod(getTimelineProducer(clipId, state, speed)->cut(in, out));
                return {prod, false};
527 528
            }
            // if it's a video or disabled clip, we must make sure that its master clip matches our video master
Nicolas Carion's avatar
Nicolas Carion committed
529
            if (state == PlaylistState::VideoOnly && !m_videoProducer) {
530 531 532 533
                qDebug() << "Warning: weird, we found a video clip whose master is already loaded but we don't have any yet";
                createVideoMasterProducer();
                return {std::shared_ptr<Mlt::Producer>(m_videoProducer->cut(in, out)), false};
            }
Nicolas Carion's avatar
Nicolas Carion committed
534 535 536 537 538 539
            if (state == PlaylistState::Disabled && !m_disabledProducer) {
                qDebug() << "Warning: weird, we found a disabled clip whose master is already loaded but we don't have any yet";
                createDisabledMasterProducer();
                return {std::shared_ptr<Mlt::Producer>(m_disabledProducer->cut(in, out)), false};
            }
            if (state == PlaylistState::VideoOnly && QString::fromUtf8(m_videoProducer->get("id")) != QString::fromUtf8(master->parent().get("id"))) {
540 541 542
                qDebug() << "Warning: weird, we found a video clip whose master is already loaded but doesn't match ours";
                return {std::shared_ptr<Mlt::Producer>(m_videoProducer->cut(in, out)), false};
            }
Nicolas Carion's avatar
Nicolas Carion committed
543 544 545 546
            if (state == PlaylistState::Disabled && QString::fromUtf8(m_disabledProducer->get("id")) != QString::fromUtf8(master->parent().get("id"))) {
                qDebug() << "Warning: weird, we found a disabled clip whose master is already loaded but doesn't match ours";
                return {std::shared_ptr<Mlt::Producer>(m_disabledProducer->cut(in, out)), false};
            }
547 548 549
            // We have a good id, this clip can be used
            return {master, true};
        } else {
550
            master->parent().set("_loaded", 1);
551 552
            if (state == PlaylistState::AudioOnly) {
                m_audioProducers[clipId] = std::shared_ptr<Mlt::Producer>(&master->parent());
553
                m_effectStack->addService(m_audioProducers[clipId]);
554 555
                return {master, true};
            }
Vincent Pinon's avatar
Vincent Pinon committed
556
            if (!qFuzzyIsNull(timeWarp)) {
557
                m_timewarpProducers[clipId] = std::shared_ptr<Mlt::Producer>(&master->parent());
558
                m_effectStack->addService(m_timewarpProducers[clipId]);
559 560
                return {master, true};
            }
Nicolas Carion's avatar
Nicolas Carion committed
561
            if (state == PlaylistState::VideoOnly && !m_videoProducer) {
562 563
                // good, we found a master video producer, and we didn't have any
                m_videoProducer.reset(&master->parent());
564
                m_effectStack->addService(m_videoProducer);
565 566
                return {master, true};
            }
Nicolas Carion's avatar
Nicolas Carion committed
567 568 569
            if (state == PlaylistState::Disabled && !m_disabledProducer) {
                // good, we found a master disabled producer, and we didn't have any
                m_disabledProducer.reset(&master->parent());
570
                m_effectStack->addService(m_disabledProducer);
Nicolas Carion's avatar
Nicolas Carion committed
571 572 573
                return {master, true};
            }
            qDebug() << "Warning: weird, we found a clip whose master is not loaded but we already have a master";
574 575 576 577 578
            return {std::shared_ptr<Mlt::Producer>(m_videoProducer->cut(in, out)), false};
        }
    } else if (master->is_valid()) {
        // in that case, we have a master
        qDebug() << "Warning: weird, we received a master clip in lieue of a cut";
579
        exit(1);
580 581 582 583 584 585 586 587 588 589
        double speed = 1.0;
        if (QString::fromUtf8(master->get("mlt_service")) == QLatin1String("timewarp")) {
            speed = master->get_double("warp_speed");
        }
        return {getTimelineProducer(clipId, state, speed), false};
    }
    // we have a problem
    return {std::shared_ptr<Mlt::Producer>(ClipController::mediaUnavailable->cut()), false};
}
/*
590 591 592
std::shared_ptr<Mlt::Producer> ProjectClip::timelineProducer(PlaylistState::ClipState state, int track)
{
    if (!m_service.startsWith(QLatin1String("avformat"))) {
593
        std::shared_ptr<Mlt::Producer> prod(originalProducer()->cut());
594 595 596 597 598
        int length = getProducerIntProperty(QStringLiteral("kdenlive:duration"));
        if (length > 0) {
            prod->set_in_and_out(0, length);
        }
        return prod;
599 600 601
    }
    if (state == PlaylistState::VideoOnly) {
        if (m_timelineProducers.count(0) > 0) {
602
            return std::shared_ptr<Mlt::Producer>(m_timelineProducers.find(0)->second->cut());
603 604
        }
        std::shared_ptr<Mlt::Producer> videoProd = cloneProducer();
605
        videoProd->set("audio_index", -1);
606
        m_timelineProducers[0] = videoProd;
607
        return std::shared_ptr<Mlt::Producer>(videoProd->cut());
608 609 610
    }
    if (state == PlaylistState::AudioOnly) {
        if (m_timelineProducers.count(-track) > 0) {
611
            return std::shared_ptr<Mlt::Producer>(m_timelineProducers.find(-track)->second->cut());
612 613
        }
        std::shared_ptr<Mlt::Producer> audioProd = cloneProducer();
614
        audioProd->set("video_index", -1);
615
        m_timelineProducers[-track] = audioProd;
616
        return std::shared_ptr<Mlt::Producer>(audioProd->cut());
617 618
    }
    if (m_timelineProducers.count(track) > 0) {
619
        return std::shared_ptr<Mlt::Producer>(m_timelineProducers.find(track)->second->cut());
620 621 622
    }
    std::shared_ptr<Mlt::Producer> normalProd = cloneProducer();
    m_timelineProducers[track] = normalProd;
623
    return std::shared_ptr<Mlt::Producer>(normalProd->cut());
624
}*/
625

626
std::shared_ptr<Mlt::Producer> ProjectClip::cloneProducer(Mlt::Profile *destProfile)
627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645
{
    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");
646
    std::shared_ptr<Mlt::Producer> prod(new Mlt::Producer(destProfile ? *destProfile : *m_masterProducer->profile(), "xml-string", clipXml.constData()));
647 648 649
    if (strcmp(prod->get("mlt_service"), "avformat") == 0) {
        prod->set("mlt_service", "avformat-novalidate");
    }
650
    return prod;
651 652
}

653
bool ProjectClip::isReady() const
654
{
655
    return m_clipStatus == StatusReady;
656 657
}

658
/*void ProjectClip::setZone(const QPoint &zone)
659 660
{
    m_zone = zone;
661
}*/
662 663 664

QPoint ProjectClip::zone() const
{
665 666
    int x = getProducerIntProperty(QStringLiteral("kdenlive:zone_in"));
    int y = getProducerIntProperty(QStringLiteral("kdenlive:zone_out"));
667
    if (y <= x) {
668
        y = getFramePlaytime();
669
    }
670
    return QPoint(x, y);
671 672 673 674
}

const QString ProjectClip::hash()
{
675
    QString clipHash = getProducerProperty(QStringLiteral("kdenlive:file_hash"));
676 677
    if (!clipHash.isEmpty()) {
        return clipHash;
678
    }
679
    return getFileHash();
680 681
}

682
const QString ProjectClip::getFileHash()
683
{
684 685
    QByteArray fileData;
    QByteArray fileHash;
686
    switch (m_clipType) {
687
    case ClipType::SlideShow:
688
        fileData = clipUrl().toUtf8();
689 690
        fileHash = QCryptographicHash::hash(fileData, QCryptographicHash::Md5);
        break;
691
    case ClipType::Text:
692
    case ClipType::TextTemplate:
693
        fileData = getProducerProperty(QStringLiteral("xmldata")).toUtf8();
694 695
        fileHash = QCryptographicHash::hash(fileData, QCryptographicHash::Md5);
        break;
696
    case ClipType::QText:
697
        fileData = getProducerProperty(QStringLiteral("text")).toUtf8();
698 699
        fileHash = QCryptographicHash::hash(fileData, QCryptographicHash::Md5);
        break;
700
    case ClipType::Color:
701
        fileData = getProducerProperty(QStringLiteral("resource")).toUtf8();
702 703 704
        fileHash = QCryptographicHash::hash(fileData, QCryptographicHash::Md5);
        break;
    default:
705
        QFile file(clipUrl());
706 707 708 709 710
        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)
             */
711 712
            if (file.size() > 2000000) {
                fileData = file.read(1000000);
713
                if (file.seek(file.size() - 1000000)) {
714
                    fileData.append(file.readAll());
715 716
                }
            } else {
717
                fileData = file.readAll();
718
            }
719
            file.close();