projectclip.cpp 31.5 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 48
    AbstractProjectItem(AbstractProjectItem::ClipItem, id, parent)
    , audioFrameCache()
Vincent Pinon's avatar
Vincent Pinon committed
49
    , m_controller(controller)
50
    , m_abortAudioThumb(false)
51
    , m_thumbsProducer(NULL)
52
{
53
    m_clipStatus = StatusReady;
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
54
    m_thumbnail = thumb;
55 56
    m_name = m_controller->clipName();
    m_duration = m_controller->getStringDuration();
57
    m_date = m_controller->date;
58
    m_description = m_controller->description();
59
    m_type = m_controller->clipType();
60 61
    // Make sure we have a hash for this clip
    hash();
62
    setParent(parent);
63
    bin()->loadSubClips(id, m_controller->getPropertiesFromPrefix("kdenlive:clipzone."));
64
    if (KdenliveSettings::audiothumbnails()) {
65
        m_audioThumbsThread = QtConcurrent::run(this, &ProjectClip::slotCreateAudioThumbs);
66
    }
67 68
}

69
ProjectClip::ProjectClip(const QDomElement& description, QIcon thumb, ProjectFolder* parent) :
70
    AbstractProjectItem(AbstractProjectItem::ClipItem, description, parent)
71
    , audioFrameCache()
Vincent Pinon's avatar
Vincent Pinon committed
72
    , m_controller(NULL)
73
    , m_abortAudioThumb(false)
74
    , m_type(Unknown)
75
    , m_thumbsProducer(NULL)
76 77
{
    Q_ASSERT(description.hasAttribute("id"));
78
    m_clipStatus = StatusWaiting;
79
    m_thumbnail = thumb;
80 81 82
    if (description.hasAttribute("type")) {
        m_type = (ClipType) description.attribute("type").toInt();
    }
83
    m_temporaryUrl = QUrl::fromLocalFile(getXmlProperty(description, "resource"));
84
    QString clipName = getXmlProperty(description, "kdenlive:clipname");
85 86 87
    if (!clipName.isEmpty()) {
        m_name = clipName;
    }
88 89
    else if (m_temporaryUrl.isValid()) {
        m_name = m_temporaryUrl.fileName();
90
    }
91
    else m_name = i18n("Untitled");
92
    setParent(parent);
93 94 95 96 97
}


ProjectClip::~ProjectClip()
{
98
    // controller is deleted in bincontroller
99
    abortAudioThumbs();
100
    delete m_thumbsProducer;
101 102
}

103 104 105 106 107
QString ProjectClip::getToolTip() const
{
    return url().toLocalFile();
}

108
QString ProjectClip::getXmlProperty(const QDomElement &producer, const QString &propertyName, const QString &defaultValue)
109
{
110
    QString value = defaultValue;
111 112 113 114 115 116 117 118 119 120
    QDomNodeList props = producer.elementsByTagName("property");
    for (int i = 0; i < props.count(); ++i) {
        if (props.at(i).toElement().attribute("name") == propertyName) {
            value = props.at(i).firstChild().nodeValue();
            break;
        }
    }
    return value;
}

121
void ProjectClip::updateAudioThumbnail(QVariantList* audioLevels)
122 123
{
    ////qDebug() << "CLIPBASE RECIEDVED AUDIO DATA*********************************************";
124 125
    audioFrameCache = audioLevels;
    m_controller->audioThumbCreated = true;
126 127 128 129 130 131 132 133 134 135 136
    emit gotAudioData();
}

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

bool ProjectClip::audioThumbCreated() const
{
137
    return (m_controller && m_controller->audioThumbCreated);
138 139
}

140 141
ClipType ProjectClip::clipType() const
{
142
    return m_type;
143 144
}

145 146 147 148 149 150 151 152 153 154 155 156
bool ProjectClip::hasParent(const QString &id) const
{
    AbstractProjectItem *par = parent();
    while (par) {
	if (par->clipId() == id) {
	    return true;
	}
	par = par->parent();
    }
    return false;
}

157 158 159 160 161 162 163 164
ProjectClip* ProjectClip::clip(const QString &id)
{
    if (id == m_id) {
        return this;
    }
    return NULL;
}

165 166
ProjectFolder* ProjectClip::folder(const QString &id)
{
167
    Q_UNUSED(id)
168 169 170
    return NULL;
}

171 172 173 174 175
void ProjectClip::disableEffects(bool disable)
{
    if (m_controller) m_controller->disableEffects(disable);
}

176 177 178
ProjectSubClip* ProjectClip::getSubClip(int in, int out)
{
    for (int i = 0; i < count(); ++i) {
Vincent Pinon's avatar
Vincent Pinon committed
179
        ProjectSubClip *clip = static_cast<ProjectSubClip *>(at(i))->subClip(in, out);
180 181 182 183 184 185 186
        if (clip) {
            return clip;
        }
    }
    return NULL;
}

187 188 189 190 191 192 193 194
ProjectClip* ProjectClip::clipAt(int ix)
{
    if (ix == index()) {
        return this;
    }
    return NULL;
}

195
/*bool ProjectClip::isValid() const
196
{
197 198
    return m_controller->isValid();
}*/
199 200 201

QUrl ProjectClip::url() const
{
202
    if (m_controller) return m_controller->clipUrl();
203
    return m_temporaryUrl;
204 205 206 207
}

bool ProjectClip::hasLimitedDuration() const
{
208 209 210 211
    if (m_controller) {
        return m_controller->hasLimitedDuration();
    }
    return true;
212 213
}

214
GenTime ProjectClip::duration() const
215
{
216 217
    if (m_controller) {
	return m_controller->getPlaytime();
218
    }
219
    return GenTime();
220 221
}

222
void ProjectClip::reloadProducer(bool thumbnailOnly)
223 224 225
{
    QDomDocument doc;
    QDomElement xml = toXml(doc);
226 227 228 229
    if (thumbnailOnly) {
        // set a special flag to request thumbnail only
        xml.setAttribute("thumbnailOnly", "1");
    }
230
    bin()->reloadProducer(m_id, xml);
231 232 233 234
}

void ProjectClip::setCurrent(bool current, bool notify)
{
235
    Q_UNUSED(notify)
236
    if (current && m_controller) {
Jean-Baptiste Mardelle's avatar
cleanup  
Jean-Baptiste Mardelle committed
237
        bin()->openProducer(m_controller);
238
        bin()->editMasterEffect(m_controller);
239 240 241 242 243
    }
}

QDomElement ProjectClip::toXml(QDomDocument& document)
{
244 245 246
    if (m_controller) {
        m_controller->getProducerXML(document);
        return document.documentElement().firstChildElement("producer");
247
    }
248
    return QDomElement();
249 250 251 252
}

void ProjectClip::setThumbnail(QImage img)
{
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
253 254
    QPixmap thumb = roundedPixmap(QPixmap::fromImage(img));
    if (hasProxy() && !thumb.isNull()) {
255
        // Overlay proxy icon
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
256
        QPainter p(&thumb);
257
        QColor c(220, 220, 10, 200);
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
258
        QRect r(0, 0, thumb.height() / 2.5, thumb.height() / 2.5);
259 260 261 262 263 264 265 266
        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
267
    m_thumbnail = QIcon(thumb);
268 269 270
    bin()->emitItemUpdated(this);
}

271 272 273 274 275
QPixmap ProjectClip::thumbnail(int width, int height)
{
    return m_thumbnail.pixmap(width, height);
}

276
void ProjectClip::setProducer(ClipController *controller, bool replaceProducer)
277
{
278
    if (!replaceProducer && m_controller) {
Vincent Pinon's avatar
Vincent Pinon committed
279
        qDebug()<<"// RECEIVED PRODUCER BUT WE ALREADY HAVE ONE\n----------";
280 281
        return;
    }
282 283
    if (m_controller) {
        // Replace clip for this controller
284
        //m_controller->updateProducer(m_id, &(controller->originalProducer()));
285
       //delete controller;
286
    }
287
    else if (controller) {
288 289 290 291
        // We did not yet have the controller, update info
        m_controller = controller;
        if (m_name.isEmpty()) m_name = m_controller->clipName();
        m_duration = m_controller->getStringDuration();
292
        m_date = m_controller->date;
293
        m_description = m_controller->description();
294
        m_temporaryUrl.clear();
295
        if (m_type == Unknown) m_type = m_controller->clipType();
296
    }
297
    m_clipStatus = StatusReady;
298
    bin()->emitItemUpdated(this);
299 300
    // Make sure we have a hash for this clip
    hash();
301 302 303 304 305 306 307 308 309 310 311 312 313 314
    createAudioThumbs();
}

void ProjectClip::createAudioThumbs()
{
    if (KdenliveSettings::audiothumbnails() && !m_audioThumbsThread.isRunning()) {
        m_audioThumbsThread = QtConcurrent::run(this, &ProjectClip::slotCreateAudioThumbs);
    }
}

void ProjectClip::abortAudioThumbs()
{
    if (m_audioThumbsThread.isRunning()) {
        m_abortAudioThumb = true;
315
        m_audioThumbsThread.waitForFinished();
316
    }
317 318
}

319
Mlt::Producer *ProjectClip::originalProducer()
320
{
321 322 323 324
    if (!m_controller) {
        return NULL;
    }
    return &m_controller->originalProducer();
325 326
}

327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
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);
    m_thumbsProducer = clip.softClone(ClipController::getPassPropertiesList());
    // Check if we are using GPU accel, then we need to use alternate producer
    if (KdenliveSettings::gpu_accel()) {
        Mlt::Filter scaler(*prod.profile(), "swscale");
        Mlt::Filter converter(*prod.profile(), "avcolor_space");
        m_thumbsProducer->attach(scaler);
        m_thumbsProducer->attach(converter);
    }
    return m_thumbsProducer;
}

349 350 351 352 353
ClipController *ProjectClip::controller()
{
    return m_controller;
}

354
bool ProjectClip::isReady() const
355
{
356
    return m_controller != NULL && m_clipStatus == StatusReady;
357 358
}

359
/*void ProjectClip::setZone(const QPoint &zone)
360 361
{
    m_zone = zone;
362
}*/
363 364 365

QPoint ProjectClip::zone() const
{
366 367 368
    int x = getProducerIntProperty("kdenlive:zone_in");
    int y = getProducerIntProperty("kdenlive:zone_out");
    return QPoint(x, y);
369 370
}

Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
371 372 373 374 375 376 377 378
void ProjectClip::resetProducerProperty(const QString &name)
{
    if (m_controller) {
        m_controller->resetProperty(name);
    }
}

void ProjectClip::setProducerProperty(const QString &name, int data)
379
{
380 381
    if (m_controller) {
	m_controller->setProperty(name, data);
382 383 384
    }
}

Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
385
void ProjectClip::setProducerProperty(const QString &name, double data)
386
{
387 388
    if (m_controller) {
        m_controller->setProperty(name, data);
389 390 391
    }
}

Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
392
void ProjectClip::setProducerProperty(const QString &name, const QString &data)
393
{
394 395
    if (m_controller) {
        m_controller->setProperty(name, data);
396 397 398
    }
}

399 400 401 402 403 404 405 406 407 408 409 410 411 412
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;
}

413 414 415 416 417 418 419 420
QColor ProjectClip::getProducerColorProperty(const QString &key) const
{
    if (m_controller) {
        return m_controller->color_property(key);
    }
    return QColor();
}

421 422 423 424 425 426 427 428
int ProjectClip::getProducerIntProperty(const QString &key) const
{
    int value = 0;
    if (m_controller) {
        value = m_controller->int_property(key);
    }
    return value;
}
429

430
QString ProjectClip::getProducerProperty(const QString &key) const
431 432
{
    QString value;
433 434
    if (m_controller) {
	value = m_controller->property(key);
435 436 437 438 439 440
    }
    return value;
}

const QString ProjectClip::hash()
{
441 442
    if (m_controller) {
        QString clipHash = m_controller->property("kdenlive:file_hash");
443 444
        if (!clipHash.isEmpty()) {
            return clipHash;
445
        }
446
    }
447
    return getFileHash();
448 449
}

450
const QString ProjectClip::getFileHash() const
451
{
452 453 454 455 456 457 458 459
    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:
460 461 462
          fileData = m_controller ? m_controller->property("xmldata").toUtf8() : name().toUtf8();
          fileHash = QCryptographicHash::hash(fileData, QCryptographicHash::Md5);
          break;
463
      case Color:
464 465
          fileData = m_controller ? m_controller->property("resource").toUtf8() : name().toUtf8();
          fileHash = QCryptographicHash::hash(fileData, QCryptographicHash::Md5);
466 467 468 469 470
          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
              /*
471 472 473
               * 1 MB = 1 second per 450 files (or faster)
               * 10 MB = 9 seconds per 450 files (or faster)
               */
474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
            if (file.size() > 2000000) {
                fileData = file.read(1000000);
                if (file.seek(file.size() - 1000000))
                    fileData.append(file.readAll());
            } else
                fileData = file.readAll();
            file.close();
            if (m_controller) m_controller->setProperty("kdenlive:file_size", QString::number(file.size()));
            fileHash = QCryptographicHash::hash(fileData, QCryptographicHash::Md5);
          }
          break;
    }
    if (fileHash.isEmpty()) return QString();
    QString result = fileHash.toHex();
    if (m_controller) {
	m_controller->setProperty("kdenlive:file_hash", result);
490
    }
491
    return result;
492
}
493 494 495 496 497 498

double ProjectClip::getOriginalFps() const
{
    if (!m_controller) return 0;
    return m_controller->originalFps();
}
499 500 501

bool ProjectClip::hasProxy() const
{
502
    QString proxy = getProducerProperty("kdenlive:proxy");
503 504 505 506
    if (proxy.isEmpty() || proxy == "-") return false;
    return true;
}

507
void ProjectClip::setProperties(QMap <QString, QString> properties, bool refreshPanel)
508 509
{
    QMapIterator<QString, QString> i(properties);
510
    QMap <QString, QString> passProperties;
511
    bool refreshProducer = false;
512
    bool refreshAnalysis = false;
513 514 515
    bool reload = false;
    // Some properties also need to be passed to track producers
    QStringList timelineProperties;
516
    timelineProperties << "force_aspect_ratio" << "video_index" << "audio_index" << "set.force_full_luma"<< "full_luma" <<"threads" <<"force_colorspace"<<"force_tff"<<"force_progressive"<<"force_fps";
517 518 519 520
    QStringList keys;
    keys << "luma_duration" << "luma_file" << "fade" << "ttl" << "softness" << "crop" << "animation";
    while (i.hasNext()) {
        i.next();
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
521
        setProducerProperty(i.key(), i.value());
522 523 524
        if (m_type == SlideShow && keys.contains(i.key())) {
            reload = true;
        }
525
        if (i.key().startsWith("kdenlive:clipanalysis")) refreshAnalysis = true;
526 527 528
        if (timelineProperties.contains(i.key())) {
            passProperties.insert(i.key(), i.value());
        }
529
    }
530 531
    if (properties.contains("kdenlive:proxy")) {
        QString value = properties.value("kdenlive:proxy");
532 533 534 535 536 537
        // If value is "-", that means user manually disabled proxy on this clip
        if (value.isEmpty() || value == "-") {
            // reset proxy
            if (bin()->hasPendingJob(m_id, AbstractClipJob::PROXYJOB)) {
                bin()->discardJobs(m_id, AbstractClipJob::PROXYJOB);
            }
538 539 540
            else {
                reloadProducer();
            }
541 542
        }
        else {
543
            // A proxy was requested, make sure to keep original url
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
544
            setProducerProperty("kdenlive:originalurl", url().toLocalFile());
545
            bin()->startJob(m_id, AbstractClipJob::PROXYJOB);
546 547
        }
    }
548 549
    else if (properties.contains("resource")) {
        // Clip resource changed, update thumbnail
550
        if (m_type != Color) {
551
            reloadProducer();
552
        }
553
        reload = true;
554
    }
555
    if (properties.contains("xmldata") || !passProperties.isEmpty()) {
556 557
        refreshProducer = true;
    }
558
    if (refreshAnalysis) emit refreshAnalysisPanel();
559 560 561 562 563
    if (properties.contains("length")) {
        m_duration = m_controller->getStringDuration();
        bin()->emitItemUpdated(this);
    }

564 565 566 567
    if (properties.contains("kdenlive:clipname")) {
        m_name = properties.value("kdenlive:clipname");
        bin()->emitItemUpdated(this);
    }
568 569 570 571
    if (refreshPanel) {
        // Some of the clip properties have changed through a command, update properties panel
        emit refreshPropertiesPanel();
    }
572
    if (refreshProducer || reload) {
573
        // producer has changed, refresh monitor and thumbnail
574
        if (reload) reloadProducer(true);
575
        bin()->refreshClip(m_id);
576
    }
577 578 579
    if (!passProperties.isEmpty()) {
        bin()->updateTimelineProducers(m_id, passProperties);
    }
580 581 582 583 584 585
}

void ProjectClip::setJobStatus(AbstractClipJob::JOBTYPE jobType, ClipJobStatus status, int progress, const QString &statusMessage)
{
    m_jobType = jobType;
    if (progress > 0) {
586
        if (m_jobProgress == progress) return;
587 588 589 590 591 592
	m_jobProgress = progress;
    }
    else {
	m_jobProgress = status;
	if ((status == JobAborted || status == JobCrashed  || status == JobDone) || !statusMessage.isEmpty()) {
	    m_jobMessage = statusMessage;
593
            bin()->emitMessage(statusMessage, OperationCompletedMessage);
594 595 596 597
	}
    }
    bin()->emitItemUpdated(this);
}
598

599 600 601

ClipPropertiesController *ProjectClip::buildProperties(QWidget *parent)
{
602
    ClipPropertiesController *panel = new ClipPropertiesController(bin()->projectTimecode(), m_controller, parent);
603
    connect(this, SIGNAL(refreshPropertiesPanel()), panel, SLOT(slotReloadProperties()));
604
    connect(this, SIGNAL(refreshAnalysisPanel()), panel, SLOT(slotFillAnalysisData()));
605 606 607
    return panel;
}

608 609
void ProjectClip::updateParentInfo(const QString &folderid, const QString &foldername)
{
610
    Q_UNUSED(foldername)
611
    m_controller->setProperty("kdenlive:folderid", folderid);
612 613
}

614 615 616
bool ProjectClip::matches(QString condition)
{
    //TODO
617
    Q_UNUSED(condition)
618 619 620
    return true;
}

621
const QString ProjectClip::codec(bool audioCodec) const
622
{
623 624
    if (!m_controller) return QString();
    return m_controller->codec(audioCodec);
625
}
626

627
bool ProjectClip::rename(const QString &name, int column)
628 629 630
{
    QMap <QString, QString> newProperites;
    QMap <QString, QString> oldProperites;
631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653
    bool edited = false;
    switch (column) {
      case 0:
        if (m_name == name) return false;
        // Rename clip
        oldProperites.insert("kdenlive:clipname", m_name);
        newProperites.insert("kdenlive:clipname", name);
        m_name = name;
        edited = true;
        break;
      case 2:
        if (m_description == name) return false;
        // Rename clip
        oldProperites.insert("kdenlive:description", m_description);
        newProperites.insert("kdenlive:description", name);
        m_description = name;
        edited = true;
        break;
    }
    if (edited) {
        bin()->slotEditClipCommand(m_id, oldProperites, newProperites);
    }
    return edited;
654 655
}

656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683
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);
684
    return true;
685 686 687 688 689 690 691 692 693 694 695 696 697 698
}

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();
}
699

Vincent Pinon's avatar
Vincent Pinon committed
700
void ProjectClip::addEffect(const ProfileInfo &pInfo, QDomElement &effect)
701
{
702
    m_controller->addEffect(pInfo, effect);
703
    bin()->editMasterEffect(m_controller);
704
    bin()->emitItemUpdated(this);
705 706
}

707
void ProjectClip::removeEffect(int ix)
708
{
709
    m_controller->removeEffect(ix);
710
    bin()->editMasterEffect(m_controller);
711 712 713 714 715 716 717
    bin()->emitItemUpdated(this);
}

QVariant ProjectClip::data(DataType type) const
{
    switch (type) {
      case AbstractProjectItem::IconOverlay:
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
718
            return m_controller != NULL ? (m_controller->hasEffects() ? QVariant("kdenlive-track_has_effect") : QVariant()) : QVariant();
719 720 721 722 723
            break;
        default:
	    break;
    }
    return AbstractProjectItem::data(type);
724
}
725 726 727

void ProjectClip::slotExtractImage(QList <int> frames)
{
728
    Mlt::Producer *prod = thumbProducer();
729
    if (prod == NULL || !prod->is_valid()) return;
730 731 732 733
    int fullWidth = (int)((double) 150 * prod->profile()->dar() + 0.5);
    QDir thumbFolder(bin()->projectFolder().path() + "/thumbs/");
    for (int i = 0; i < frames.count(); i++) {
        int pos = frames.at(i);
734 735
        if (thumbFolder.exists(hash() + '#' + QString::number(pos) + ".png")) {
            emit thumbReady(pos, QImage(thumbFolder.absoluteFilePath(hash() + '#' + QString::number(pos) + ".png")));
736 737 738 739 740 741 742
            continue;
        }
	int max = prod->get_out();
	if (pos >= max) pos = max - 1;
	prod->seek(pos);
	Mlt::Frame *frame = prod->get_frame();
	if (frame && frame->is_valid()) {
743
            QImage img = KThumb::getFrame(frame, fullWidth, 150);
744 745 746 747
            emit thumbReady(frames.at(i), img);
        }
        delete frame;
    }
748
}
749

750 751
void ProjectClip::slotExtractSubImage(QList <int> frames)
{
752
    Mlt::Producer *prod = thumbProducer();
753
    if (prod == NULL || !prod->is_valid()) return;
754 755 756 757
    int fullWidth = (int)((double) 150 * prod->profile()->dar() + 0.5);
    QDir thumbFolder(bin()->projectFolder().path() + "/thumbs/");
    for (int i = 0; i < frames.count(); i++) {
        int pos = frames.at(i);
758 759
        QString path = thumbFolder.absoluteFilePath(hash() + "#" + QString::number(pos) + ".png");
        QImage img(path);
760 761
        if (!img.isNull()) {
            for (int i = 0; i < count(); ++i) {
Vincent Pinon's avatar
Vincent Pinon committed
762
                ProjectSubClip *clip = static_cast<ProjectSubClip *>(at(i));
763 764 765 766 767 768 769 770
                if (clip && clip->zone().x() == pos) {
                    clip->setThumbnail(img);
                }
            }
            continue;
        }
        int max = prod->get_out();
        if (pos >= max) pos = max - 1;
771
        if (pos < 0) pos = 0;
772 773 774
        prod->seek(pos);
        Mlt::Frame *frame = prod->get_frame();
        if (frame && frame->is_valid()) {
775
            QImage img = KThumb::getFrame(frame, fullWidth, 150);
776
            if (!img.isNull()) {
777
                img.save(path);
778
                for (int i = 0; i < count(); ++i) {
Vincent Pinon's avatar
Vincent Pinon committed
779
                    ProjectSubClip *clip = static_cast<ProjectSubClip *>(at(i));
780 781 782 783 784 785 786 787 788 789
                    if (clip && clip->zone().x() == pos) {
                        clip->setThumbnail(img);
                    }
                }
            }
        }
        delete frame;
    }
}

790 791 792 793 794 795
int ProjectClip::audioChannels() const
{
    if (!m_controller || !m_controller->audioInfo()) return 0;
    return m_controller->audioInfo()->channels();
}

796 797
void ProjectClip::slotCreateAudioThumbs()
{
798
    Mlt::Producer *prod = originalProducer();
799
    if (!prod || !prod->is_valid()) return;
800 801 802 803
    AudioStreamInfo *audioInfo = m_controller->audioInfo();
    if (audioInfo == NULL) return;
    QString clipHash = hash();
    if (clipHash.isEmpty()) return;
804
    QString audioPath = bin()->projectFolder().path() + "/thumbs/" + clipHash + "_audio.png";
805 806 807 808 809 810
    double lengthInFrames = prod->get_playtime();
    int frequency = audioInfo->samplingRate();
    if (frequency <= 0) frequency = 48000;
    int channels = audioInfo->channels();
    if (channels <= 0) channels = 2;
    double frame = 0.0;
811 812 813 814 815 816 817 818 819 820 821
    QVariantList* audioLevels = new QVariantList;
    QImage image(audioPath);
    if (!image.isNull()) {
        // convert cached image
        int n = image.width() * image.height();
        for (int i = 0; i < n; i++) {
            QRgb p = image.pixel(i / 2, i % channels);
            *audioLevels << qRed(p);
            *audioLevels << qGreen(p);
            *audioLevels << qBlue(p);
            *audioLevels << qAlpha(p);
822 823
        }
    }
824 825
    if (audioLevels->size() > 0) {
        updateAudioThumbnail(audioLevels);
826 827 828
        return;
    }
    QString service = prod->get("mlt_service");
829 830 831 832
    if (service == "avformat-novalidate")
        service = "avformat";
    else if (service.startsWith("xml"))
        service = "xml-nogl";
833 834 835
    Mlt::Producer *audioProducer = new Mlt::Producer(*prod->profile(), service.toUtf8().constData(), prod->get("resource"));
    if (!audioProducer->is_valid()) {
        delete audioProducer;
Vincent Pinon's avatar
Vincent Pinon committed
836
        delete audioLevels;
837 838
        return;
    }
839 840 841 842 843 844
    Mlt::Filter chans(*prod->profile(), "audiochannels");
    Mlt::Filter converter(*prod->profile(), "audioconvert");
    Mlt::Filter levels(*prod->profile(), "audiolevel");
    audioProducer->attach(chans);
    audioProducer->attach(converter);
    audioProducer->attach(levels);
845

846
    audioProducer->set("video_index", "-1");
847 848 849 850
    int last_val = 0;
    setJobStatus(AbstractClipJob::THUMBJOB, JobWaiting, 0, i18n("Creating audio thumbnails"));
    double framesPerSecond = audioProducer->get_fps();
    mlt_audio_format audioFormat = mlt_audio_s16;
851 852 853 854 855
    QStringList keys;
    for (int i = 0; i < channels; i++) {
        keys << "meta.media.audio_level." + QString::number(i);
    }
    for (int z = (int) frame; z < (int)(frame + lengthInFrames) && !m_abortAudioThumb; ++z) {
856 857 858 859 860 861
        int val = (int)((z - frame) / (frame + lengthInFrames) * 100.0);
        if (last_val != val && val > 1) {
            setJobStatus(AbstractClipJob::THUMBJOB, JobWorking, val);
            last_val = val;
        }
        Mlt::Frame *mlt_frame = audioProducer->get_frame();
862 863 864 865 866 867
        if (mlt_frame && mlt_frame->is_valid() && !mlt_frame->get_int("test_audio")) {
            int samples = mlt_sample_calculator(framesPerSecond, frequency, z);
            mlt_frame->get_audio(audioFormat, frequency, channels, samples);
            for (int channel = 0; channel < channels; ++channel) {
                double level = 256 * qMin(mlt_frame->get_double(keys.at(channel).toUtf8().constData()) * 0.9, 1.0);
                *audioLevels << level;
868
            }
869 870 871
        } else if (!audioLevels->isEmpty()) {
            for (int channel = 0; channel < channels; channel++)
                *audioLevels << audioLevels->last();
872 873
        }
        delete mlt_frame;
874
        if (m_abortAudioThumb) break;
875
    }
876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897

    if (!m_abortAudioThumb && audioLevels->size() > 0) {
        // Put into an image for caching.
        int count = audioLevels->size();
        QImage image((count + 3) / 4, channels, QImage::Format_ARGB32);
        int n = image.width() * image.height();
        for (int i = 0; i < n; i ++) {
            QRgb p; 
            if ((4*i + 3) < count) {
                p = qRgba(audioLevels->at(4*i).toInt(), audioLevels->at(4*i+1).toInt(), audioLevels->at(4*i+2).toInt(), audioLevels->at(4*i+3).toInt());
            } else {
                int last = audioLevels->last().toInt();
                int r = (4*i+0) < count? audioLevels->at(4*i+0).toInt() : last;
                int g = (4*i+1) < count? audioLevels->at(4*i+1).toInt() : last;
                int b = (4*i+2) < count? audioLevels->at(4*i+2).toInt() : last;
                int a = last;
                p = qRgba(r, g, b, a);
            }
            image.setPixel(i / 2, i % channels, p);
        }
        image.save(audioPath);
    }
898 899
    delete audioProducer;
    setJobStatus(AbstractClipJob::THUMBJOB, JobDone, 0, i18n("Audio thumbnails done"));
900 901
    if (!m_abortAudioThumb) {
        updateAudioThumbnail(audioLevels);
902
    }
903
    m_abortAudioThumb = false;
904
}
905 906 907 908 909 910 911

bool ProjectClip::isTransparent() const
{
    if (m_type == Text) return true;
    if (m_type == Image && m_controller->int_property("kdenlive:transparency") == 1) return true;
    return false;
}
912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927