projectclip.cpp 46.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
#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
    m_name = clipName();
    m_duration = getStringDuration();
74
    m_inPoint = 0;
75 76
    m_date = date;
    m_description = ClipController::description();
77
    if (m_clipType == ClipType::Audio) {
78
        m_thumbnail = KoIconUtils::themedIcon(QStringLiteral("audio-x-generic"));
79 80 81
    } else {
        m_thumbnail = thumb;
    }
82 83
    // Make sure we have a hash for this clip
    hash();
84
    connect(m_markerModel.get(), &MarkerListModel::modelChanged, [&]() { setProducerProperty(QStringLiteral("kdenlive:markers"), m_markerModel->toJson()); });
85 86
    QString markers = getProducerProperty(QStringLiteral("kdenlive:markers"));
    if (!markers.isEmpty()) {
87 88
        QMetaObject::invokeMethod(m_markerModel.get(), "importFromJson", Qt::QueuedConnection, Q_ARG(const QString &, markers), Q_ARG(bool, true),
                                  Q_ARG(bool, false));
89
    }
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
90
    connectEffectStack();
91 92
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

426 427 428
void ProjectClip::createVideoMasterProducer()
{
    if (!m_videoProducer) {
429 430 431 432 433 434
        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);
        }
435 436
    }
}
437

Nicolas Carion's avatar
Nicolas Carion committed
438 439 440 441 442 443
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);
444
        m_effectStack->addService(m_disabledProducer);
Nicolas Carion's avatar
Nicolas Carion committed
445 446
    }
}
447
std::shared_ptr<Mlt::Producer> ProjectClip::getTimelineProducer(int clipId, PlaylistState::ClipState state, double speed)
448
{
449
    qDebug() << "producer request"<<clipId<<speed;
450 451 452
    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
453 454 455 456
        if (m_timewarpProducers.count(clipId) > 0) {
            m_effectStack->removeService(m_timewarpProducers[clipId]);
            m_timewarpProducers.erase(clipId);
        }
457 458 459 460 461 462
        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);
463
                m_effectStack->addService(m_audioProducers[clipId]);
464 465 466
            }
            return std::shared_ptr<Mlt::Producer>(m_audioProducers[clipId]->cut());
        }
467 468 469 470
        if (m_audioProducers.count(clipId) > 0) {
            m_effectStack->removeService(m_audioProducers[clipId]);
            m_audioProducers.erase(clipId);
        }
Nicolas Carion's avatar
Nicolas Carion committed
471 472 473
        if (state == PlaylistState::VideoOnly) {
            // we return the video producer
            createVideoMasterProducer();
474 475
            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
476 477 478
        }
        Q_ASSERT(state == PlaylistState::Disabled);
        createDisabledMasterProducer();
479 480
        int duration = m_masterProducer->get_int("kdenlive:duration");
        return std::shared_ptr<Mlt::Producer>(m_disabledProducer->cut(-1, duration > 0 ? duration: -1));
481 482 483
    }

    // in that case, we need to create a warp producer, if we don't have one
484 485 486 487
    if (m_audioProducers.count(clipId) > 0) {
        m_effectStack->removeService(m_audioProducers[clipId]);
        m_audioProducers.erase(clipId);
    }
488 489 490

    std::shared_ptr<Mlt::Producer> warpProducer;
    if (m_timewarpProducers.count(clipId) > 0) {
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
491 492
        // remove in all cases, we add it unconditionally anyways
        m_effectStack->removeService(m_timewarpProducers[clipId]);
493 494 495
        if (qFuzzyCompare(m_timewarpProducers[clipId]->get_double("warp_speed"), speed)) {
            // the producer we have is good, use it !
            warpProducer = m_timewarpProducers[clipId];
496
            qDebug() << "Reusing producer!";
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
497 498
        } else {
            m_timewarpProducers.erase(clipId);
499 500 501
        }
    }
    if (!warpProducer) {
502 503
        QLocale locale;
        QString resource = QString("timewarp:%1:%2").arg(locale.toString(speed)).arg(originalProducer()->get("resource"));
504
        warpProducer.reset(new Mlt::Producer(*originalProducer()->profile(), resource.toUtf8().constData()));
505
        qDebug() << "new producer!";
506 507 508 509
        qDebug() << "warp LENGTH before" << warpProducer->get_length();
        int original_length = originalProducer()->get_length();
        // this is a workaround to cope with Mlt erroneous rounding
        warpProducer->set("length", double(original_length) / speed);
510 511
    }

512
    qDebug() << "warp LENGTH" << warpProducer->get_length();
513 514 515 516 517 518 519 520 521
    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;
522
    m_effectStack->addService(m_timewarpProducers[clipId]);
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
523
    return std::shared_ptr<Mlt::Producer>(warpProducer->cut());
524 525 526
}

std::pair<std::shared_ptr<Mlt::Producer>, bool> ProjectClip::giveMasterAndGetTimelineProducer(int clipId, std::shared_ptr<Mlt::Producer> master,
527
                                                                                              PlaylistState::ClipState state)
528 529 530 531 532 533 534 535 536 537 538 539
{
    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;
        }
540
        if (master->parent().get_int("_loaded") == 1) {
541 542
            // we already have a clip that shares the same master

Vincent Pinon's avatar
Vincent Pinon committed
543
            if (state == PlaylistState::AudioOnly || !qFuzzyIsNull(timeWarp)) {
544
                // In that case, we must create copies
545 546
                std::shared_ptr<Mlt::Producer> prod(getTimelineProducer(clipId, state, speed)->cut(in, out));
                return {prod, false};
547 548
            }
            // 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
549
            if (state == PlaylistState::VideoOnly && !m_videoProducer) {
550 551 552 553
                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
554 555 556 557 558 559
            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"))) {
560 561 562
                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
563 564 565 566
            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};
            }
567 568 569
            // We have a good id, this clip can be used
            return {master, true};
        } else {
570
            master->parent().set("_loaded", 1);
571 572
            if (state == PlaylistState::AudioOnly) {
                m_audioProducers[clipId] = std::shared_ptr<Mlt::Producer>(&master->parent());
573
                m_effectStack->addService(m_audioProducers[clipId]);
574 575
                return {master, true};
            }
Vincent Pinon's avatar
Vincent Pinon committed
576
            if (!qFuzzyIsNull(timeWarp)) {
577
                m_timewarpProducers[clipId] = std::shared_ptr<Mlt::Producer>(&master->parent());
578
                m_effectStack->addService(m_timewarpProducers[clipId]);
579 580
                return {master, true};
            }
Nicolas Carion's avatar
Nicolas Carion committed
581
            if (state == PlaylistState::VideoOnly && !m_videoProducer) {
582 583
                // good, we found a master video producer, and we didn't have any
                m_videoProducer.reset(&master->parent());
584
                m_effectStack->addService(m_videoProducer);
585 586
                return {master, true};
            }
Nicolas Carion's avatar
Nicolas Carion committed
587 588 589
            if (state == PlaylistState::Disabled && !m_disabledProducer) {
                // good, we found a master disabled producer, and we didn't have any
                m_disabledProducer.reset(&master->parent());
590
                m_effectStack->addService(m_disabledProducer);
Nicolas Carion's avatar
Nicolas Carion committed
591 592 593
                return {master, true};
            }
            qDebug() << "Warning: weird, we found a clip whose master is not loaded but we already have a master";
594 595 596 597 598
            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";
599
        exit(1);
600 601 602 603 604 605 606 607 608 609
        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};
}
/*
610 611 612
std::shared_ptr<Mlt::Producer> ProjectClip::timelineProducer(PlaylistState::ClipState state, int track)
{
    if (!m_service.startsWith(QLatin1String("avformat"))) {
613
        std::shared_ptr<Mlt::Producer> prod(originalProducer()->cut());
614 615 616 617 618
        int length = getProducerIntProperty(QStringLiteral("kdenlive:duration"));
        if (length > 0) {
            prod->set_in_and_out(0, length);
        }
        return prod;
619 620 621
    }
    if (state == PlaylistState::VideoOnly) {
        if (m_timelineProducers.count(0) > 0) {
622
            return std::shared_ptr<Mlt::Producer>(m_timelineProducers.find(0)->second->cut());
623 624
        }
        std::shared_ptr<Mlt::Producer> videoProd = cloneProducer();
625
        videoProd->set("audio_index", -1);
626
        m_timelineProducers[0] = videoProd;
627
        return std::shared_ptr<Mlt::Producer>(videoProd->cut());
628 629 630
    }
    if (state == PlaylistState::AudioOnly) {
        if (m_timelineProducers.count(-track) > 0) {
631
            return std::shared_ptr<Mlt::Producer>(m_timelineProducers.find(-track)->second->cut());
632 633
        }
        std::shared_ptr<Mlt::Producer> audioProd = cloneProducer();
634
        audioProd->set("video_index", -1);
635
        m_timelineProducers[-track] = audioProd;
636
        return std::shared_ptr<Mlt::Producer>(audioProd->cut());
637 638
    }
    if (m_timelineProducers.count(track) > 0) {
639
        return std::shared_ptr<Mlt::Producer>(m_timelineProducers.find(track)->second->cut());
640 641 642
    }
    std::shared_ptr<Mlt::Producer> normalProd = cloneProducer();
    m_timelineProducers[track] = normalProd;
643
    return std::shared_ptr<Mlt::Producer>(normalProd->cut());
644
}*/
645

646
std::shared_ptr<Mlt::Producer> ProjectClip::cloneProducer(Mlt::Profile *destProfile)
647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665
{
    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");
666
    std::shared_ptr<Mlt::Producer> prod(new Mlt::Producer(destProfile ? *destProfile : *m_masterProducer->profile(), "xml-string", clipXml.constData()));
667 668 669
    if (strcmp(prod->get("mlt_service"), "avformat") == 0) {
        prod->set("mlt_service", "avformat-novalidate");
    }
670
    return prod;
671 672
}

673
bool ProjectClip::isReady() const
674
{
675
    return m_clipStatus == StatusReady;
676 677
}

678
/*void ProjectClip::setZone(const QPoint &zone)
679 680
{
    m_zone = zone;
681
}*/
682 683 684

QPoint ProjectClip::zone() const
{
685 686
    int x = getProducerIntProperty(QStringLiteral("kdenlive:zone_in"));
    int y = getProducerIntProperty(QStringLiteral("kdenlive:zone_out"));
687
    if (y <= x) {
688
        y = getFramePlaytime();
689
    }
690
    return QPoint(x, y);
691 692 693 694
}

const QString ProjectClip::hash()
{
695
    QString clipHash = getProducerProperty(QStringLiteral("kdenlive:file_hash"));
696 697
    if (!clipHash.isEmpty()) {
        return clipHash;
698
    }
699
    return getFileHash();
700 701
}

702
const QString ProjectClip::getFileHash()
703
{
704 705
    QByteArray fileData;
    QByteArray fileHash;
706
    switch (m_clipType) {
707
    case ClipType::SlideShow:
708
        fileData = clipUrl().toUtf8();
709 710
        fileHash = QCryptographicHash::hash(fileData, QCryptographicHash::Md5);
        break;
711
    case ClipType::Text:
712
    case ClipType::TextTemplate:
713
        fileData = getProducerProperty(QStringLiteral("xmldata")).toUtf8();
714 715
        fileHash = QCryptographicHash::hash(fileData, QCryptographicHash::Md5);
        break;
716
    case ClipType::QText:
717
        fileData = getProducerProperty(QStringLiteral("text")).toUtf8();
718 719
        fileHash = QCryptographicHash::hash(fileData, QCryptographicHash::Md5);
        break;
720
    case ClipType::Color:
721
        fileData = getProducerProperty(QStringLiteral("resource")).toUtf8();
722 723 724
        fileHash = QCryptographicHash::hash(fileData, QCryptographicHash::Md5);
        break;
    default:
725
        QFile file(clipUrl());