projectclip.cpp 49.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"
47

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 = QIcon::fromTheme(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
    self->m_effectStack->importEffects(producer, true);
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::ProducerType)description.attribute(QStringLiteral("type")).toInt();
114
        if (m_clipType == ClipType::Audio) {
115
            m_thumbnail = QIcon::fromTheme(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
    m_thumbMutex.lock();
142
    m_requestedThumbs.clear();
143
    m_thumbMutex.unlock();
144
    m_thumbThread.waitForFinished();
145
    audioFrameCache.clear();
146 147
}

148 149
void ProjectClip::connectEffectStack()
{
150 151
    connect(m_effectStack.get(), &EffectStackModel::modelChanged, this, &ProjectClip::updateChildProducers);
    connect(m_effectStack.get(), &EffectStackModel::dataChanged, this, &ProjectClip::updateChildProducers);
152 153 154 155 156 157
    connect(m_effectStack.get(), &EffectStackModel::dataChanged, [&](){
        if (auto ptr = m_model.lock()) {
            std::static_pointer_cast<ProjectItemModel>(ptr)->onItemUpdated(std::static_pointer_cast<ProjectClip>(shared_from_this()),
                                                                           AbstractProjectItem::IconOverlay);
        }
    });
158 159
    /*connect(m_effectStack.get(), &EffectStackModel::modelChanged, [&](){
        qDebug()<<"/ / / STACK CHANGED";
160
        updateChildProducers();
161
    });*/
162 163
}

164 165
QString ProjectClip::getToolTip() const
{
166
    return url();
167 168
}

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

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

bool ProjectClip::audioThumbCreated() const
{
194
    return (m_audioThumbCreated);
195 196
}

197
ClipType::ProducerType ProjectClip::clipType() const
198
{
199
    return m_clipType;
200 201
}

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

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

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

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

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

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

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

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

272
const QString ProjectClip::url() const
273
{
274
    return clipUrl();
275 276
}

277
GenTime ProjectClip::duration() const
278
{
279
    return getPlaytime();
280 281
}

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

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

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

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

Laurent Montel's avatar
Laurent Montel committed
327
void ProjectClip::setThumbnail(const QImage &img)
328
{
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
329 330
    QPixmap thumb = roundedPixmap(QPixmap::fromImage(img));
    if (hasProxy() && !thumb.isNull()) {
331
        // Overlay proxy icon
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
332
        QPainter p(&thumb);
333
        QColor c(220, 220, 10, 200);
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
334
        QRect r(0, 0, thumb.height() / 2.5, thumb.height() / 2.5);
335 336 337 338 339 340 341 342
        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
343
    m_thumbnail = QIcon(thumb);
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
344
    if (auto ptr = m_model.lock()) {
345 346
        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
347
    }
348 349
}

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

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

363 364 365
    // Update info
    if (m_name.isEmpty()) {
        m_name = clipName();
366
    }
367 368 369
    m_date = date;
    m_description = ClipController::description();
    m_temporaryUrl.clear();
370
    if (m_clipType == ClipType::Audio) {
371
        m_thumbnail = QIcon::fromTheme(QStringLiteral("audio-x-generic"));
372
    } else if (m_clipType == ClipType::Image) {
373
        if (getProducerIntProperty(QStringLiteral("meta.media.width")) < 8 || getProducerIntProperty(QStringLiteral("meta.media.height")) < 8) {
374 375
            KMessageBox::information(QApplication::activeWindow(),
                                     i18n("Image dimension smaller than 8 pixels.\nThis is not correctly supported by our video framework."));
376
        }
377
    }
378
    m_duration = getStringDuration();
379
    m_clipStatus = StatusReady;
380
    if (!hasProxy()) {
Nicolas Carion's avatar
Nicolas Carion committed
381
        if (auto ptr = m_model.lock()) emit std::static_pointer_cast<ProjectItemModel>(ptr)->refreshPanel(m_binId);
382
    }
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
383
    if (auto ptr = m_model.lock()) {
384 385
        std::static_pointer_cast<ProjectItemModel>(ptr)->onItemUpdated(std::static_pointer_cast<ProjectClip>(shared_from_this()),
                                                                       AbstractProjectItem::DataDuration);
386
        std::static_pointer_cast<ProjectItemModel>(ptr)->updateWatcher(std::static_pointer_cast<ProjectClip>(shared_from_this()));
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
387
    }
388
    // Make sure we have a hash for this clip
389
    getFileHash();
390 391
    // set parent again (some info need to be stored in producer)
    updateParent(parentItem().lock());
392
    if (pCore->currentDoc()->getDocumentProperty(QStringLiteral("enableproxy")).toInt() == 1) {
393 394
        QList<std::shared_ptr<ProjectClip>> clipList;
        // automatic proxy generation enabled
395
        if (m_clipType == ClipType::Image && pCore->currentDoc()->getDocumentProperty(QStringLiteral("generateimageproxy")).toInt() == 1) {
396 397 398
            if (getProducerIntProperty(QStringLiteral("meta.media.width")) >= KdenliveSettings::proxyimageminsize() && getProducerProperty(QStringLiteral("kdenlive:proxy")) == QStringLiteral()) {
                clipList << std::static_pointer_cast<ProjectClip>(shared_from_this());
            }
399
        } else if (pCore->currentDoc()->getDocumentProperty(QStringLiteral("generateproxy")).toInt() == 1 && (m_clipType == ClipType::AV || m_clipType == ClipType::Video)) {
400 401 402
            if (getProducerIntProperty(QStringLiteral("meta.media.width")) >= KdenliveSettings::proxyminsize() && getProducerProperty(QStringLiteral("kdenlive:proxy")) == QStringLiteral()) {
                clipList << std::static_pointer_cast<ProjectClip>(shared_from_this());
            }
403
        }
404 405
        if (!clipList.isEmpty()) {
            pCore->currentDoc()->slotProxyCurrentItem(true, clipList, false);
406 407 408
        }
    }
    pCore->bin()->reloadMonitorIfActive(clipId());
409 410 411 412 413 414 415 416
    if (m_videoProducer) {
        m_videoProducer.reset(m_masterProducer->cut());
        if (hasAudio()) {
            // disable audio but activate video
            m_videoProducer->set("set.test_audio", 1);
            m_videoProducer->set("set.test_image", 0);
        }
    }
417 418 419 420 421 422 423 424 425
    for (auto &p : m_audioProducers) {
        m_effectStack->removeService(p.second);
    }
    for (auto &p : m_timewarpProducers) {
        m_effectStack->removeService(p.second);
    }
    // Release audio producers
    m_audioProducers.clear();
    m_timewarpProducers.clear();
426
    replaceInTimeline();
427
    return true;
428 429
}

430
std::shared_ptr<Mlt::Producer> ProjectClip::thumbProducer()
431 432 433 434
{
    if (m_thumbsProducer) {
        return m_thumbsProducer;
    }
435
    if (clipType() == ClipType::Unknown) {
Laurent Montel's avatar
Laurent Montel committed
436
        return nullptr;
437
    }
438 439
    std::shared_ptr<Mlt::Producer> prod = originalProducer();
    if (!prod->is_valid()) {
Laurent Montel's avatar
Laurent Montel committed
440
        return nullptr;
441
    }
442
    if (KdenliveSettings::gpu_accel()) {
443
        // TODO: when the original producer changes, we must reload this thumb producer
444
        Clip clip(*prod.get());
445
        m_thumbsProducer = std::make_shared<Mlt::Producer>(clip.softClone(ClipController::getPassPropertiesList()));
446 447
        Mlt::Filter scaler(*prod->profile(), "swscale");
        Mlt::Filter converter(*prod->profile(), "avcolor_space");
448 449
        m_thumbsProducer->attach(scaler);
        m_thumbsProducer->attach(converter);
450
    } else {
451
        m_thumbsProducer = cloneProducer(pCore->thumbProfile());
452 453 454 455
    }
    return m_thumbsProducer;
}

456 457 458
void ProjectClip::createVideoMasterProducer()
{
    if (!m_videoProducer) {
459 460 461 462 463 464
        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);
        }
465 466
    }
}
467

Nicolas Carion's avatar
Nicolas Carion committed
468 469 470 471 472 473
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);
474
        m_effectStack->addService(m_disabledProducer);
Nicolas Carion's avatar
Nicolas Carion committed
475 476
    }
}
477
std::shared_ptr<Mlt::Producer> ProjectClip::getTimelineProducer(int clipId, PlaylistState::ClipState state, double speed)
478
{
479
    qDebug() << "producer request"<<clipId<<speed;
480 481 482
    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
483 484 485 486
        if (m_timewarpProducers.count(clipId) > 0) {
            m_effectStack->removeService(m_timewarpProducers[clipId]);
            m_timewarpProducers.erase(clipId);
        }
487 488 489 490 491 492
        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);
493
                m_effectStack->addService(m_audioProducers[clipId]);
494 495 496
            }
            return std::shared_ptr<Mlt::Producer>(m_audioProducers[clipId]->cut());
        }
497 498 499 500
        if (m_audioProducers.count(clipId) > 0) {
            m_effectStack->removeService(m_audioProducers[clipId]);
            m_audioProducers.erase(clipId);
        }
Nicolas Carion's avatar
Nicolas Carion committed
501 502 503
        if (state == PlaylistState::VideoOnly) {
            // we return the video producer
            createVideoMasterProducer();
504 505
            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
506 507 508
        }
        Q_ASSERT(state == PlaylistState::Disabled);
        createDisabledMasterProducer();
509 510
        int duration = m_masterProducer->get_int("kdenlive:duration");
        return std::shared_ptr<Mlt::Producer>(m_disabledProducer->cut(-1, duration > 0 ? duration: -1));
511 512 513
    }

    // in that case, we need to create a warp producer, if we don't have one
514 515 516 517
    if (m_audioProducers.count(clipId) > 0) {
        m_effectStack->removeService(m_audioProducers[clipId]);
        m_audioProducers.erase(clipId);
    }
518 519 520

    std::shared_ptr<Mlt::Producer> warpProducer;
    if (m_timewarpProducers.count(clipId) > 0) {
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
521 522
        // remove in all cases, we add it unconditionally anyways
        m_effectStack->removeService(m_timewarpProducers[clipId]);
523 524 525
        if (qFuzzyCompare(m_timewarpProducers[clipId]->get_double("warp_speed"), speed)) {
            // the producer we have is good, use it !
            warpProducer = m_timewarpProducers[clipId];
526
            qDebug() << "Reusing producer!";
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
527 528
        } else {
            m_timewarpProducers.erase(clipId);
529 530 531
        }
    }
    if (!warpProducer) {
532
        QLocale locale;
533 534 535 536 537 538 539
        QString resource(originalProducer()->get("resource"));
        if (resource.isEmpty() || resource == QLatin1String("<producer>")) {
            resource = m_service;
        }
        QString url = QString("timewarp:%1:%2").arg(locale.toString(speed)).arg(resource);
        warpProducer.reset(new Mlt::Producer(*originalProducer()->profile(), url.toUtf8().constData()));
        qDebug() << "new producer: "<<url;
540 541 542 543
        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);
544 545
    }

546
    qDebug() << "warp LENGTH" << warpProducer->get_length();
547 548 549 550 551 552 553 554 555
    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;
556
    m_effectStack->addService(m_timewarpProducers[clipId]);
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
557
    return std::shared_ptr<Mlt::Producer>(warpProducer->cut());
558 559 560
}

std::pair<std::shared_ptr<Mlt::Producer>, bool> ProjectClip::giveMasterAndGetTimelineProducer(int clipId, std::shared_ptr<Mlt::Producer> master,
561
                                                                                              PlaylistState::ClipState state)
562 563 564 565 566 567 568 569 570 571 572 573
{
    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;
        }
574
        if (master->parent().get_int("_loaded") == 1) {
575 576
            // we already have a clip that shares the same master

Vincent Pinon's avatar
Vincent Pinon committed
577
            if (state == PlaylistState::AudioOnly || !qFuzzyIsNull(timeWarp)) {
578
                // In that case, we must create copies
579 580
                std::shared_ptr<Mlt::Producer> prod(getTimelineProducer(clipId, state, speed)->cut(in, out));
                return {prod, false};
581 582
            }
            // 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
583
            if (state == PlaylistState::VideoOnly && !m_videoProducer) {
584 585 586 587
                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
588 589 590 591 592 593
            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"))) {
594 595 596
                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
597 598 599 600
            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};
            }
601 602 603
            // We have a good id, this clip can be used
            return {master, true};
        } else {
604
            master->parent().set("_loaded", 1);
605
            if (state == PlaylistState::AudioOnly) {
606
                m_audioProducers[clipId] = std::shared_ptr<Mlt::Producer>(new Mlt::Producer(&master->parent()));
607
                m_effectStack->addService(m_audioProducers[clipId]);
608 609
                return {master, true};
            }
Vincent Pinon's avatar
Vincent Pinon committed
610
            if (!qFuzzyIsNull(timeWarp)) {
611
                m_timewarpProducers[clipId] = std::shared_ptr<Mlt::Producer>(new Mlt::Producer(&master->parent()));
612
                m_effectStack->addService(m_timewarpProducers[clipId]);
613 614
                return {master, true};
            }
Nicolas Carion's avatar
Nicolas Carion committed
615
            if (state == PlaylistState::VideoOnly && !m_videoProducer) {
616
                // good, we found a master video producer, and we didn't have any
617
                m_videoProducer.reset(master->parent().cut());
618
                m_effectStack->addService(m_videoProducer);
619 620
                return {master, true};
            }
Nicolas Carion's avatar
Nicolas Carion committed
621 622
            if (state == PlaylistState::Disabled && !m_disabledProducer) {
                // good, we found a master disabled producer, and we didn't have any
623
                m_disabledProducer.reset(master->parent().cut());
624
                m_effectStack->addService(m_disabledProducer);
Nicolas Carion's avatar
Nicolas Carion committed
625 626 627
                return {master, true};
            }
            qDebug() << "Warning: weird, we found a clip whose master is not loaded but we already have a master";
628 629 630 631 632
            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";
633
        exit(1);
634 635 636 637 638 639 640 641 642 643
        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};
}
/*
644 645 646
std::shared_ptr<Mlt::Producer> ProjectClip::timelineProducer(PlaylistState::ClipState state, int track)
{
    if (!m_service.startsWith(QLatin1String("avformat"))) {
647
        std::shared_ptr<Mlt::Producer> prod(originalProducer()->cut());
648 649 650 651 652
        int length = getProducerIntProperty(QStringLiteral("kdenlive:duration"));
        if (length > 0) {
            prod->set_in_and_out(0, length);
        }
        return prod;
653 654 655
    }
    if (state == PlaylistState::VideoOnly) {
        if (m_timelineProducers.count(0) > 0) {
656
            return std::shared_ptr<Mlt::Producer>(m_timelineProducers.find(0)->second->cut());
657 658
        }
        std::shared_ptr<Mlt::Producer> videoProd = cloneProducer();
659
        videoProd->set("audio_index", -1);
660
        m_timelineProducers[0] = videoProd;
661
        return std::shared_ptr<Mlt::Producer>(videoProd->cut());
662 663 664
    }
    if (state == PlaylistState::AudioOnly) {
        if (m_timelineProducers.count(-track) > 0) {
665
            return std::shared_ptr<Mlt::Producer>(m_timelineProducers.find(-track)->second->cut());
666 667
        }
        std::shared_ptr<Mlt::Producer> audioProd = cloneProducer();
668
        audioProd->set("video_index", -1);
669
        m_timelineProducers[-track] = audioProd;
670
        return std::shared_ptr<Mlt::Producer>(audioProd->cut());
671 672
    }
    if (m_timelineProducers.count(track) > 0) {
673
        return std::shared_ptr<Mlt::Producer>(m_timelineProducers.find(track)->second->cut());
674 675 676
    }
    std::shared_ptr<Mlt::Producer> normalProd = cloneProducer();
    m_timelineProducers[track] = normalProd;
677
    return std::shared_ptr<Mlt::Producer>(normalProd->cut());
678
}*/
679

680
std::shared_ptr<Mlt::Producer> ProjectClip::cloneProducer(Mlt::Profile *destProfile)
681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699
{
    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");
700
    std::shared_ptr<Mlt::Producer> prod(new Mlt::Producer(destProfile ? *destProfile : *m_masterProducer->profile(), "xml-string", clipXml.constData()));
701 702 703
    if (strcmp(prod->get("mlt_service"), "avformat") == 0) {
        prod->set("mlt_service", "avformat-novalidate");
    }
704
    return prod;
705 706
}

707
bool ProjectClip::isReady() const
708
{
709
    return m_clipStatus == StatusReady;
710 711
}

712
/*void ProjectClip::setZone(const QPoint &zone)
713 714
{
    m_zone = zone;
715
}*/
716 717 718

QPoint ProjectClip::zone() const
{
719 720
    int x = getProducerIntProperty(QStringLiteral("kdenlive:zone_in"));
    int y = getProducerIntProperty(QStringLiteral("kdenlive:zone_out"));
721
    if (y <= x) {
722
        y = getFramePlaytime();
723
    }
724
    return QPoint(x, y);
725 726 727 728
}

const QString ProjectClip::hash()
{
729
    QString clipHash = getProducerProperty(QStringLiteral("kdenlive:file_hash"));
730 731
    if (!clipHash.isEmpty()) {
        return clipHash;
732
    }