projectclip.cpp 46.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
/*
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
by the membership of KDE e.V.), which shall act as a proxy 
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"
#include "projectfolder.h"
25
#include "projectsubclip.h"
26
#include "bin.h"
27
#include "timecode.h"
28 29
#include "doc/kthumb.h"
#include "kdenlivesettings.h"
30
#include "timeline/clip.h"
31
#include "project/projectcommands.h"
32
#include "mltcontroller/clipcontroller.h"
33
#include "lib/audio/audioStreamInfo.h"
34
#include "mltcontroller/clippropertiescontroller.h"
35 36 37

#include <QDomElement>
#include <QFile>
38
#include <QDir>
39 40
#include <QDebug>
#include <QCryptographicHash>
41
#include <QtConcurrent>
42
#include <KLocalizedString>
43
#include <KMessageBox>
44 45


Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
46
ProjectClip::ProjectClip(const QString &id, QIcon thumb, ClipController *controller, ProjectFolder* parent) :
47
    AbstractProjectItem(AbstractProjectItem::ClipItem, id, parent)
48
    , m_abortAudioThumb(false)
Vincent Pinon's avatar
Vincent Pinon committed
49
    , m_controller(controller)
50
    , m_thumbsProducer(NULL)
51
{
52
    m_clipStatus = StatusReady;
53 54
    m_name = m_controller->clipName();
    m_duration = m_controller->getStringDuration();
55
    m_date = m_controller->date;
56
    m_description = m_controller->description();
57
    m_type = m_controller->clipType();
58 59 60 61 62
    if (m_type == Audio) {
        m_thumbnail = QIcon::fromTheme(QStringLiteral("audio-x-generic"));
    } else {
        m_thumbnail = thumb;
    }
63 64
    // Make sure we have a hash for this clip
    hash();
65
    setParent(parent);
66
    connect(this, &ProjectClip::updateJobStatus, this, &ProjectClip::setJobStatus);
67
    bin()->loadSubClips(id, m_controller->getPropertiesFromPrefix(QStringLiteral("kdenlive:clipzone.")));
68
    connect(this, &ProjectClip::updateThumbProgress, bin(), &Bin::doUpdateThumbsProgress);
69
    createAudioThumbs();
70 71
}

72
ProjectClip::ProjectClip(const QDomElement& description, QIcon thumb, ProjectFolder* parent) :
73
    AbstractProjectItem(AbstractProjectItem::ClipItem, description, parent)
74
    , m_abortAudioThumb(false)
Vincent Pinon's avatar
Vincent Pinon committed
75
    , m_controller(NULL)
76
    , m_type(Unknown)
77
    , m_thumbsProducer(NULL)
78 79
{
    Q_ASSERT(description.hasAttribute("id"));
80
    m_clipStatus = StatusWaiting;
81
    m_thumbnail = thumb;
82 83
    if (description.hasAttribute(QStringLiteral("type"))) {
        m_type = (ClipType) description.attribute(QStringLiteral("type")).toInt();
84 85 86
        if (m_type == Audio) {
            m_thumbnail = QIcon::fromTheme(QStringLiteral("audio-x-generic"));
        }
87
    }
88 89
    m_temporaryUrl = QUrl::fromLocalFile(getXmlProperty(description, QStringLiteral("resource")));
    QString clipName = getXmlProperty(description, QStringLiteral("kdenlive:clipname"));
90 91 92
    if (!clipName.isEmpty()) {
        m_name = clipName;
    }
93 94
    else if (m_temporaryUrl.isValid()) {
        m_name = m_temporaryUrl.fileName();
95
    }
96
    else m_name = i18n("Untitled");
97
    connect(this, &ProjectClip::updateJobStatus, this, &ProjectClip::setJobStatus);
98
    setParent(parent);
99
    connect(this, &ProjectClip::updateThumbProgress, bin(), &Bin::doUpdateThumbsProgress);
100 101 102 103 104
}


ProjectClip::~ProjectClip()
{
105
    // controller is deleted in bincontroller
106
    abortAudioThumbs();
107
    bin()->slotAbortAudioThumb(m_id, duration().ms());
108 109
    QMutexLocker audioLock(&m_audioMutex);
    m_thumbMutex.lock();
110
    m_requestedThumbs.clear();
111
    m_thumbMutex.unlock();
112
    m_thumbThread.waitForFinished();
113
    delete m_thumbsProducer;
114
    audioFrameCache.clear();
115 116
}

117 118 119
void ProjectClip::abortAudioThumbs()
{
    m_abortAudioThumb = true;
120
    emit doAbortAudioThumbs();
121 122
}

123 124 125 126 127
QString ProjectClip::getToolTip() const
{
    return url().toLocalFile();
}

128
QString ProjectClip::getXmlProperty(const QDomElement &producer, const QString &propertyName, const QString &defaultValue)
129
{
130
    QString value = defaultValue;
131
    QDomNodeList props = producer.elementsByTagName(QStringLiteral("property"));
132
    for (int i = 0; i < props.count(); ++i) {
133
        if (props.at(i).toElement().attribute(QStringLiteral("name")) == propertyName) {
134 135 136 137 138 139 140
            value = props.at(i).firstChild().nodeValue();
            break;
        }
    }
    return value;
}

141
void ProjectClip::updateAudioThumbnail(QVariantList audioLevels)
142
{
143
    audioFrameCache = audioLevels;
144
    m_controller->audioThumbCreated = true;
145
    bin()->emitRefreshAudioThumbs(m_id);
146 147 148 149 150 151 152 153 154
    emit gotAudioData();
}

QList < CommentedTime > ProjectClip::commentedSnapMarkers() const
{
    if (m_controller) return m_controller->commentedSnapMarkers();
    return QList < CommentedTime > ();
}

155 156 157 158 159 160
QStringList ProjectClip::markersText(GenTime in, GenTime out) const
{
    if (m_controller) return m_controller->markerComments(in, out);
    return QStringList();
}

161 162
bool ProjectClip::audioThumbCreated() const
{
163
    return (m_controller && m_controller->audioThumbCreated);
164 165
}

166 167
ClipType ProjectClip::clipType() const
{
168
    return m_type;
169 170
}

171 172 173 174 175 176 177 178 179 180 181 182
bool ProjectClip::hasParent(const QString &id) const
{
    AbstractProjectItem *par = parent();
    while (par) {
	if (par->clipId() == id) {
	    return true;
	}
	par = par->parent();
    }
    return false;
}

183 184 185 186 187 188 189 190
ProjectClip* ProjectClip::clip(const QString &id)
{
    if (id == m_id) {
        return this;
    }
    return NULL;
}

191 192
ProjectFolder* ProjectClip::folder(const QString &id)
{
193
    Q_UNUSED(id)
194 195 196
    return NULL;
}

197 198 199 200 201
void ProjectClip::disableEffects(bool disable)
{
    if (m_controller) m_controller->disableEffects(disable);
}

202 203 204
ProjectSubClip* ProjectClip::getSubClip(int in, int out)
{
    for (int i = 0; i < count(); ++i) {
Vincent Pinon's avatar
Vincent Pinon committed
205
        ProjectSubClip *clip = static_cast<ProjectSubClip *>(at(i))->subClip(in, out);
206 207 208 209 210 211 212
        if (clip) {
            return clip;
        }
    }
    return NULL;
}

213 214 215 216 217 218 219 220 221 222 223 224
QStringList ProjectClip::subClipIds() const
{
    QStringList subIds;
    for (int i = 0; i < count(); ++i) {
        AbstractProjectItem *clip = at(i);
        if (clip) {
            subIds << clip->clipId();
        }
    }
    return subIds;
}

225 226 227 228 229 230 231 232
ProjectClip* ProjectClip::clipAt(int ix)
{
    if (ix == index()) {
        return this;
    }
    return NULL;
}

233
/*bool ProjectClip::isValid() const
234
{
235 236
    return m_controller->isValid();
}*/
237

238 239 240 241 242 243
bool ProjectClip::hasUrl() const
{
    if (m_controller && (m_type != Color) && (m_type != Unknown)) return (m_controller->clipUrl().isValid());
    return false;
}

244 245
QUrl ProjectClip::url() const
{
246
    if (m_controller) return m_controller->clipUrl();
247
    return m_temporaryUrl;
248 249 250 251
}

bool ProjectClip::hasLimitedDuration() const
{
252 253 254 255
    if (m_controller) {
        return m_controller->hasLimitedDuration();
    }
    return true;
256 257
}

258
GenTime ProjectClip::duration() const
259
{
260 261
    if (m_controller) {
	return m_controller->getPlaytime();
262
    }
263
    return GenTime();
264 265
}

266
void ProjectClip::reloadProducer(bool thumbnailOnly)
267 268 269
{
    QDomDocument doc;
    QDomElement xml = toXml(doc);
270 271
    if (thumbnailOnly) {
        // set a special flag to request thumbnail only
272
        xml.setAttribute(QStringLiteral("thumbnailOnly"), QStringLiteral("1"));
273
    }
274
    bin()->reloadProducer(m_id, xml);
275 276 277 278
}

void ProjectClip::setCurrent(bool current, bool notify)
{
279
    Q_UNUSED(notify)
280
    if (current && m_controller) {
Jean-Baptiste Mardelle's avatar
cleanup  
Jean-Baptiste Mardelle committed
281
        bin()->openProducer(m_controller);
282
        bin()->editMasterEffect(m_controller);
283 284 285
    }
}

286
QDomElement ProjectClip::toXml(QDomDocument& document, bool includeMeta)
287
{
288
    if (m_controller) {
289
        m_controller->getProducerXML(document, includeMeta);
290
        return document.documentElement().firstChildElement(QStringLiteral("producer"));
291 292 293 294 295 296 297 298 299 300
    } else {
        // We only have very basic infos, ike id and url, pass them
        QDomElement prod = document.createElement(QStringLiteral("producer"));
        prod.setAttribute(QStringLiteral("id"), m_id);
        EffectsList::setProperty(prod, QStringLiteral("resource"), m_temporaryUrl.path());
        if (m_type != Unknown) {
            prod.setAttribute(QStringLiteral("type"), (int) m_type);
        }
        document.appendChild(prod);
        return prod;
301 302 303 304 305
    }
}

void ProjectClip::setThumbnail(QImage img)
{
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
306 307
    QPixmap thumb = roundedPixmap(QPixmap::fromImage(img));
    if (hasProxy() && !thumb.isNull()) {
308
        // Overlay proxy icon
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
309
        QPainter p(&thumb);
310
        QColor c(220, 220, 10, 200);
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
311
        QRect r(0, 0, thumb.height() / 2.5, thumb.height() / 2.5);
312 313 314 315 316 317 318 319
        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
320
    m_thumbnail = QIcon(thumb);
321
    emit thumbUpdated(img);
322 323 324
    bin()->emitItemUpdated(this);
}

325 326 327 328 329
QPixmap ProjectClip::thumbnail(int width, int height)
{
    return m_thumbnail.pixmap(width, height);
}

330
bool ProjectClip::setProducer(ClipController *controller, bool replaceProducer)
331
{
332
    if (!replaceProducer && m_controller) {
Vincent Pinon's avatar
Vincent Pinon committed
333
        qDebug()<<"// RECEIVED PRODUCER BUT WE ALREADY HAVE ONE\n----------";
334
        return false;
335
    }
336
    bool isNewProducer = true;
337 338
    if (m_controller) {
        // Replace clip for this controller
339 340
        resetProducerProperty("kdenlive:file_hash");
        isNewProducer = false;
341
    }
342
    else if (controller) {
343 344 345
        // We did not yet have the controller, update info
        m_controller = controller;
        if (m_name.isEmpty()) m_name = m_controller->clipName();
346
        m_date = m_controller->date;
347
        m_description = m_controller->description();
348
        m_temporaryUrl.clear();
349 350 351 352 353 354
        if (m_type == Unknown) {
            m_type = m_controller->clipType();
            if (m_type == Audio) {
                m_thumbnail = QIcon::fromTheme(QStringLiteral("audio-x-generic"));
            }
        }
355
    }
Vincent Pinon's avatar
Vincent Pinon committed
356 357
    if (m_controller)
        m_duration = m_controller->getStringDuration();
358
    m_clipStatus = StatusReady;
359
    if (!hasProxy()) bin()->emitRefreshPanel(m_id);
360
    bin()->emitItemUpdated(this);
361 362
    // Make sure we have a hash for this clip
    hash();
363
    createAudioThumbs();
364
    return isNewProducer;
365 366 367 368
}

void ProjectClip::createAudioThumbs()
{
369
    if (KdenliveSettings::audiothumbnails() && (m_type == AV || m_type == Audio || m_type == Playlist)) {
370 371
        bin()->requestAudioThumbs(m_id, duration().ms());
        emit updateJobStatus(AbstractClipJob::THUMBJOB, JobWaiting, 0);
372
    }
373 374
}

375
Mlt::Producer *ProjectClip::originalProducer()
376
{
377 378 379 380
    if (!m_controller) {
        return NULL;
    }
    return &m_controller->originalProducer();
381 382
}

383 384 385 386 387 388 389 390 391 392 393 394
Mlt::Producer *ProjectClip::thumbProducer()
{
    QMutexLocker locker(&m_producerMutex);
    if (m_thumbsProducer) {
        return m_thumbsProducer;
    }
    if (!m_controller) {
        return NULL;
    }
    Mlt::Producer prod = m_controller->originalProducer();
    Clip clip(prod);
    if (KdenliveSettings::gpu_accel()) {
395
        m_thumbsProducer = clip.softClone(ClipController::getPassPropertiesList());
396 397 398 399
        Mlt::Filter scaler(*prod.profile(), "swscale");
        Mlt::Filter converter(*prod.profile(), "avcolor_space");
        m_thumbsProducer->attach(scaler);
        m_thumbsProducer->attach(converter);
400 401
    } else {
        m_thumbsProducer = clip.clone();
402 403 404 405
    }
    return m_thumbsProducer;
}

406 407 408 409 410
ClipController *ProjectClip::controller()
{
    return m_controller;
}

411
bool ProjectClip::isReady() const
412
{
413
    return m_controller != NULL && m_clipStatus == StatusReady;
414 415
}

416
/*void ProjectClip::setZone(const QPoint &zone)
417 418
{
    m_zone = zone;
419
}*/
420 421 422

QPoint ProjectClip::zone() const
{
423 424
    int x = getProducerIntProperty(QStringLiteral("kdenlive:zone_in"));
    int y = getProducerIntProperty(QStringLiteral("kdenlive:zone_out"));
425
    return QPoint(x, y);
426 427
}

Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
428 429 430 431 432 433 434 435
void ProjectClip::resetProducerProperty(const QString &name)
{
    if (m_controller) {
        m_controller->resetProperty(name);
    }
}

void ProjectClip::setProducerProperty(const QString &name, int data)
436
{
437 438
    if (m_controller) {
	m_controller->setProperty(name, data);
439 440 441
    }
}

Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
442
void ProjectClip::setProducerProperty(const QString &name, double data)
443
{
444 445
    if (m_controller) {
        m_controller->setProperty(name, data);
446 447 448
    }
}

Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
449
void ProjectClip::setProducerProperty(const QString &name, const QString &data)
450
{
451 452
    if (m_controller) {
        m_controller->setProperty(name, data);
453 454 455
    }
}

456 457 458 459 460 461 462 463 464 465 466 467 468 469
QMap <QString, QString> ProjectClip::currentProperties(const QMap <QString, QString> &props)
{
    QMap <QString, QString> currentProps;
    if (!m_controller) {
        return currentProps;
    }
    QMap<QString, QString>::const_iterator i = props.constBegin();
    while (i != props.constEnd()) {
        currentProps.insert(i.key(), m_controller->property(i.key()));
        ++i;
    }
    return currentProps;
}

470 471 472 473 474 475 476 477
QColor ProjectClip::getProducerColorProperty(const QString &key) const
{
    if (m_controller) {
        return m_controller->color_property(key);
    }
    return QColor();
}

478 479 480 481 482 483 484 485
int ProjectClip::getProducerIntProperty(const QString &key) const
{
    int value = 0;
    if (m_controller) {
        value = m_controller->int_property(key);
    }
    return value;
}
486

487 488 489 490 491 492 493 494 495
qint64 ProjectClip::getProducerInt64Property(const QString &key) const
{
    qint64 value = 0;
    if (m_controller) {
        value = m_controller->int64_property(key);
    }
    return value;
}

496 497 498 499 500 501 502 503 504
double ProjectClip::getDoubleProducerProperty(const QString &key) const
{
    double value = 0;
    if (m_controller) {
        value = m_controller->double_property(key);
    }
    return value;
}

505
QString ProjectClip::getProducerProperty(const QString &key) const
506 507
{
    QString value;
508 509
    if (m_controller) {
	value = m_controller->property(key);
510 511 512 513 514 515
    }
    return value;
}

const QString ProjectClip::hash()
{
516
    if (m_controller) {
517
        QString clipHash = m_controller->property(QStringLiteral("kdenlive:file_hash"));
518 519
        if (!clipHash.isEmpty()) {
            return clipHash;
520
        }
521
    }
522
    return getFileHash();
523 524
}

525
const QString ProjectClip::getFileHash() const
526
{
527 528 529 530 531 532 533 534
    QByteArray fileData;
    QByteArray fileHash;
    switch (m_type) {
      case SlideShow:
          fileData = m_controller ? m_controller->clipUrl().toLocalFile().toUtf8() : m_temporaryUrl.toLocalFile().toUtf8();
          fileHash = QCryptographicHash::hash(fileData, QCryptographicHash::Md5);
          break;
      case Text:
535
          fileData = m_controller ? m_controller->property(QStringLiteral("xmldata")).toUtf8() : name().toUtf8();
536 537
          fileHash = QCryptographicHash::hash(fileData, QCryptographicHash::Md5);
          break;
Vincent Pinon's avatar
Vincent Pinon committed
538 539 540 541
      case QText:
          fileData = m_controller ? m_controller->property(QStringLiteral("text")).toUtf8() : name().toUtf8();
          fileHash = QCryptographicHash::hash(fileData, QCryptographicHash::Md5);
          break;
542
      case Color:
543
          fileData = m_controller ? m_controller->property(QStringLiteral("resource")).toUtf8() : name().toUtf8();
544
          fileHash = QCryptographicHash::hash(fileData, QCryptographicHash::Md5);
545 546 547 548 549
          break;
      default:
          QFile file(m_controller ? m_controller->clipUrl().toLocalFile() : m_temporaryUrl.toLocalFile());
          if (file.open(QIODevice::ReadOnly)) { // write size and hash only if resource points to a file
              /*
550 551 552
               * 1 MB = 1 second per 450 files (or faster)
               * 10 MB = 9 seconds per 450 files (or faster)
               */
553 554 555 556 557 558 559
            if (file.size() > 2000000) {
                fileData = file.read(1000000);
                if (file.seek(file.size() - 1000000))
                    fileData.append(file.readAll());
            } else
                fileData = file.readAll();
            file.close();
560
            if (m_controller) m_controller->setProperty(QStringLiteral("kdenlive:file_size"), QString::number(file.size()));
561 562 563 564 565 566 567
            fileHash = QCryptographicHash::hash(fileData, QCryptographicHash::Md5);
          }
          break;
    }
    if (fileHash.isEmpty()) return QString();
    QString result = fileHash.toHex();
    if (m_controller) {
568
	m_controller->setProperty(QStringLiteral("kdenlive:file_hash"), result);
569
    }
570
    return result;
571
}
572 573 574 575 576 577

double ProjectClip::getOriginalFps() const
{
    if (!m_controller) return 0;
    return m_controller->originalFps();
}
578 579 580

bool ProjectClip::hasProxy() const
{
581 582
    QString proxy = getProducerProperty(QStringLiteral("kdenlive:proxy"));
    if (proxy.isEmpty() || proxy == QLatin1String("-")) return false;
583 584 585
    return true;
}

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

647 648
    if (properties.contains(QStringLiteral("kdenlive:clipname"))) {
        m_name = properties.value(QStringLiteral("kdenlive:clipname"));
649
        refreshPanel = true;
650 651
        bin()->emitItemUpdated(this);
    }
652 653 654 655
    if (refreshPanel) {
        // Some of the clip properties have changed through a command, update properties panel
        emit refreshPropertiesPanel();
    }
656
    if (reload) {
657
        // producer has changed, refresh monitor and thumbnail
658
        reloadProducer(true);
659
        bin()->refreshClip(m_id);
660
    }
661 662 663
    if (!passProperties.isEmpty()) {
        bin()->updateTimelineProducers(m_id, passProperties);
    }
664 665
}

666
void ProjectClip::setJobStatus(int jobType, int status, int progress, const QString &statusMessage)
667
{
668
    m_jobType = (AbstractClipJob::JOBTYPE) jobType;
669
    if (progress > 0) {
670
        if (m_jobProgress == progress) return;
671
        m_jobProgress = progress;
672 673
    }
    else {
674 675 676
        m_jobProgress = status;
        if ((status == JobAborted || status == JobCrashed  || status == JobDone) && !statusMessage.isEmpty()) {
            m_jobMessage = statusMessage;
677
            bin()->emitMessage(statusMessage, 100, OperationCompletedMessage);
678
        }
679 680 681
    }
    bin()->emitItemUpdated(this);
}
682

683 684 685

ClipPropertiesController *ProjectClip::buildProperties(QWidget *parent)
{
686
    ClipPropertiesController *panel = new ClipPropertiesController(bin()->projectTimecode(), m_controller, parent);
687
    connect(this, SIGNAL(refreshPropertiesPanel()), panel, SLOT(slotReloadProperties()));
688
    connect(this, SIGNAL(refreshAnalysisPanel()), panel, SLOT(slotFillAnalysisData()));
689 690 691
    return panel;
}

692 693
void ProjectClip::updateParentInfo(const QString &folderid, const QString &foldername)
{
694
    Q_UNUSED(foldername)
695
    m_controller->setProperty(QStringLiteral("kdenlive:folderid"), folderid);
696 697
}

698 699 700
bool ProjectClip::matches(QString condition)
{
    //TODO
701
    Q_UNUSED(condition)
702 703 704
    return true;
}

705
const QString ProjectClip::codec(bool audioCodec) const
706
{
707 708
    if (!m_controller) return QString();
    return m_controller->codec(audioCodec);
709
}
710

711
bool ProjectClip::rename(const QString &name, int column)
712 713 714
{
    QMap <QString, QString> newProperites;
    QMap <QString, QString> oldProperites;
715 716 717 718 719
    bool edited = false;
    switch (column) {
      case 0:
        if (m_name == name) return false;
        // Rename clip
720 721
        oldProperites.insert(QStringLiteral("kdenlive:clipname"), m_name);
        newProperites.insert(QStringLiteral("kdenlive:clipname"), name);
722 723 724 725 726 727
        m_name = name;
        edited = true;
        break;
      case 2:
        if (m_description == name) return false;
        // Rename clip
728 729 730 731 732 733 734
        if (m_type == TextTemplate) {
            oldProperites.insert(QStringLiteral("templatetext"), m_description);
            newProperites.insert(QStringLiteral("templatetext"), name);
        } else {
            oldProperites.insert(QStringLiteral("kdenlive:description"), m_description);
            newProperites.insert(QStringLiteral("kdenlive:description"), name);
        }
735 736 737 738 739 740 741 742
        m_description = name;
        edited = true;
        break;
    }
    if (edited) {
        bin()->slotEditClipCommand(m_id, oldProperites, newProperites);
    }
    return edited;
743 744
}

745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772
void ProjectClip::addClipMarker(QList <CommentedTime> newMarkers, QUndoCommand *groupCommand)
{
    if (!m_controller) return;
    QList <CommentedTime> oldMarkers;
    for (int i = 0; i < newMarkers.count(); ++i) {
        CommentedTime oldMarker = m_controller->markerAt(newMarkers.at(i).time());
        if (oldMarker == CommentedTime()) {
            oldMarker = newMarkers.at(i);
            oldMarker.setMarkerType(-1);
        }
        oldMarkers << oldMarker;
    }
    (void) new AddMarkerCommand(this, oldMarkers, newMarkers, groupCommand);
}

bool ProjectClip::deleteClipMarkers(QUndoCommand *command)
{
    QList <CommentedTime> markers = commentedSnapMarkers();
    if (markers.isEmpty()) {
        return false;
    }
    QList <CommentedTime> newMarkers;
    for (int i = 0; i < markers.size(); ++i) {
        CommentedTime marker = markers.at(i);
        marker.setMarkerType(-1);
        newMarkers << marker;
    }
    new AddMarkerCommand(this, markers, newMarkers, command);
773
    return true;
774 775 776 777 778 779 780 781 782 783 784 785 786 787
}

void ProjectClip::addMarkers(QList <CommentedTime> &markers)
{
    if (!m_controller) return;
    for (int i = 0; i < markers.count(); ++i) {
      if (markers.at(i).markerType() < 0) m_controller->deleteSnapMarker(markers.at(i).time());
      else m_controller->addSnapMarker(markers.at(i));
    }
    // refresh markers in clip monitor
    bin()->refreshClipMarkers(m_id);
    // refresh markers in timeline clips
    emit refreshClipDisplay();
}
788

Vincent Pinon's avatar
Vincent Pinon committed
789
void ProjectClip::addEffect(const ProfileInfo &pInfo, QDomElement &effect)
790
{
791
    m_controller->addEffect(pInfo, effect);
792
    bin()->updateMasterEffect(m_controller);
793
    bin()->emitItemUpdated(this);
794 795
}

796
void ProjectClip::removeEffect(int ix)
797
{
798
    m_controller->removeEffect(ix);
799
    bin()->updateMasterEffect(m_controller);
800 801 802 803 804 805 806
    bin()->emitItemUpdated(this);
}

QVariant ProjectClip::data(DataType type) const
{
    switch (type) {
      case AbstractProjectItem::IconOverlay:
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
807
            return m_controller != NULL ? (m_controller->hasEffects() ? QVariant("kdenlive-track_has_effect") : QVariant()) : QVariant();
808 809 810 811 812
            break;
        default:
	    break;
    }
    return AbstractProjectItem::data(type);
813
}
814

815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858
void ProjectClip::slotQueryIntraThumbs(QList <int> frames)
{
    QMutexLocker lock(&m_intraThumbMutex);
    for (int i = 0; i < frames.count(); i++) {
        if (!m_intraThumbs.contains(frames.at(i))) {
            m_intraThumbs << frames.at(i);
        }
    }
    qSort(m_intraThumbs);
    if (!m_intraThread.isRunning()) {
        m_intraThread = QtConcurrent::run(this, &ProjectClip::doExtractIntra);
    }
}

void ProjectClip::doExtractIntra()
{
    Mlt::Producer *prod = thumbProducer();
    if (prod == NULL || !prod->is_valid()) return;
    int fullWidth = (int)((double) 150 * prod->profile()->dar() + 0.5);
    int max = prod->get_length();
    int pos;
    while (!m_intraThumbs.isEmpty()) {
        m_intraThumbMutex.lock();
        pos = m_intraThumbs.takeFirst();
        m_intraThumbMutex.unlock();
        if (pos >= max) pos = max - 1;
        const QString path = url().path() + '_' + QString::number(pos);
        QImage img = bin()->findCachedPixmap(path);
        if (!img.isNull()) {
            // Cache already contains image
            continue;
        }
	prod->seek(pos);
	Mlt::Frame *frame = prod->get_frame();
	if (frame && frame->is_valid()) {
            img = KThumb::getFrame(frame, fullWidth, 150);
            bin()->cachePixmap(path, img);
            emit thumbReady(pos, img);
        }
        delete frame;
    }
}


859
void ProjectClip::slotExtractImage(QList <int> frames)
860 861 862 863 864 865 866 867 868 869 870 871 872 873
{
    QMutexLocker lock(&m_thumbMutex);
    for (int i = 0; i < frames.count(); i++) {
        if (!m_requestedThumbs.contains(frames.at(i))) {
            m_requestedThumbs << frames.at(i);
        }
    }
    qSort(m_requestedThumbs);
    if (!m_thumbThread.isRunning()) {
        m_thumbThread = QtConcurrent::run(this, &ProjectClip::doExtractImage);
    }
}

void ProjectClip::doExtractImage()
874
{
875
    Mlt::Producer *prod = thumbProducer();
876
    if (prod == NULL || !prod->is_valid()) return;
877
    int fullWidth = (int)((double) 150 * prod->profile()->dar() + 0.5);
878 879
    bool ok = false;
    QDir thumbFolder = bin()->getCacheDir(CacheThumbs, &ok);
880 881 882
    int max = prod->get_length();
    while (!<