]> git.sesse.net Git - kdenlive/blob - src/clipitem.cpp
Fix clip color on cut
[kdenlive] / src / clipitem.cpp
1 /***************************************************************************
2  *   Copyright (C) 2007 by Jean-Baptiste Mardelle (jb@kdenlive.org)        *
3  *                                                                         *
4  *   This program is free software; you can redistribute it and/or modify  *
5  *   it under the terms of the GNU General Public License as published by  *
6  *   the Free Software Foundation; either version 2 of the License, or     *
7  *   (at your option) any later version.                                   *
8  *                                                                         *
9  *   This program is distributed in the hope that it will be useful,       *
10  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
11  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
12  *   GNU General Public License for more details.                          *
13  *                                                                         *
14  *   You should have received a copy of the GNU General Public License     *
15  *   along with this program; if not, write to the                         *
16  *   Free Software Foundation, Inc.,                                       *
17  *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA          *
18  ***************************************************************************/
19
20
21 #include "clipitem.h"
22 #include "customtrackview.h"
23 #include "customtrackscene.h"
24 #include "renderer.h"
25 #include "docclipbase.h"
26 #include "transition.h"
27 #include "kdenlivesettings.h"
28 #include "kthumb.h"
29 #include "profilesdialog.h"
30
31 #include <KDebug>
32 #include <KIcon>
33
34 #include <QPainter>
35 #include <QTimer>
36 #include <QStyleOptionGraphicsItem>
37 #include <QGraphicsScene>
38 #include <QMimeData>
39
40 ClipItem::ClipItem(DocClipBase *clip, ItemInfo info, double fps, double speed, int strobe, bool generateThumbs) :
41         AbstractClipItem(info, QRectF(), fps),
42         m_clip(clip),
43         m_startFade(0),
44         m_endFade(0),
45         m_audioOnly(false),
46         m_videoOnly(false),
47         m_startPix(QPixmap()),
48         m_endPix(QPixmap()),
49         m_hasThumbs(false),
50         m_selectedEffect(-1),
51         m_timeLine(0),
52         m_startThumbRequested(false),
53         m_endThumbRequested(false),
54         //m_hover(false),
55         m_speed(speed),
56         m_strobe(strobe),
57         m_framePixelWidth(0)
58 {
59     setZValue(2);
60     setRect(0, 0, (info.endPos - info.startPos).frames(fps) - 0.02, (double)(KdenliveSettings::trackheight() - 2));
61     setPos(info.startPos.frames(fps), (double)(info.track * KdenliveSettings::trackheight()) + 1);
62
63     // set speed independant info
64     m_speedIndependantInfo = m_info;
65     m_speedIndependantInfo.cropStart = GenTime((int)(m_info.cropStart.frames(m_fps) * m_speed), m_fps);
66     m_speedIndependantInfo.cropDuration = GenTime((int)(m_info.cropDuration.frames(m_fps) * m_speed), m_fps);
67
68     m_videoPix = KIcon("kdenlive-show-video").pixmap(QSize(16, 16));
69     m_audioPix = KIcon("kdenlive-show-audio").pixmap(QSize(16, 16));
70
71     if (m_speed == 1.0) m_clipName = m_clip->name();
72     else {
73         m_clipName = m_clip->name() + " - " + QString::number(m_speed * 100, 'f', 0) + '%';
74     }
75     m_producer = m_clip->getId();
76     m_clipType = m_clip->clipType();
77     //m_cropStart = info.cropStart;
78     m_maxDuration = m_clip->maxDuration();
79     setAcceptDrops(true);
80     m_audioThumbReady = m_clip->audioThumbCreated();
81     //setAcceptsHoverEvents(true);
82     connect(this , SIGNAL(prepareAudioThumb(double, int, int, int)) , this, SLOT(slotPrepareAudioThumb(double, int, int, int)));
83
84     if (m_clipType == VIDEO || m_clipType == AV || m_clipType == SLIDESHOW || m_clipType == PLAYLIST) {
85         m_baseColor = QColor(141, 166, 215);
86         m_hasThumbs = true;
87         m_startThumbTimer.setSingleShot(true);
88         connect(&m_startThumbTimer, SIGNAL(timeout()), this, SLOT(slotGetStartThumb()));
89         m_endThumbTimer.setSingleShot(true);
90         connect(&m_endThumbTimer, SIGNAL(timeout()), this, SLOT(slotGetEndThumb()));
91
92         connect(this, SIGNAL(getThumb(int, int)), m_clip->thumbProducer(), SLOT(extractImage(int, int)));
93
94         connect(m_clip->thumbProducer(), SIGNAL(thumbReady(int, QImage)), this, SLOT(slotThumbReady(int, QImage)));
95         connect(m_clip, SIGNAL(gotAudioData()), this, SLOT(slotGotAudioData()));
96         if (generateThumbs) QTimer::singleShot(200, this, SLOT(slotFetchThumbs()));
97
98     } else if (m_clipType == COLOR) {
99         QString colour = m_clip->getProperty("colour");
100         colour = colour.replace(0, 2, "#");
101         m_baseColor = QColor(colour.left(7));
102     } else if (m_clipType == IMAGE || m_clipType == TEXT) {
103         m_baseColor = QColor(141, 166, 215);
104         if (m_clipType == TEXT) {
105             connect(this, SIGNAL(getThumb(int, int)), m_clip->thumbProducer(), SLOT(extractImage(int, int)));
106             connect(m_clip->thumbProducer(), SIGNAL(thumbReady(int, QImage)), this, SLOT(slotThumbReady(int, QImage)));
107         }
108         //m_startPix = KThumb::getImage(KUrl(clip->getProperty("resource")), (int)(KdenliveSettings::trackheight() * KdenliveSettings::project_display_ratio()), KdenliveSettings::trackheight());
109     } else if (m_clipType == AUDIO) {
110         m_baseColor = QColor(141, 215, 166);
111         connect(m_clip, SIGNAL(gotAudioData()), this, SLOT(slotGotAudioData()));
112     }
113 }
114
115
116 ClipItem::~ClipItem()
117 {
118     blockSignals(true);
119     if (m_clipType == VIDEO || m_clipType == AV || m_clipType == SLIDESHOW || m_clipType == PLAYLIST) {
120         disconnect(m_clip->thumbProducer(), SIGNAL(thumbReady(int, QImage)), this, SLOT(slotThumbReady(int, QImage)));
121         disconnect(m_clip, SIGNAL(gotAudioData()), this, SLOT(slotGotAudioData()));
122     }
123     delete m_timeLine;
124 }
125
126 ClipItem *ClipItem::clone(ItemInfo info) const
127 {
128     ClipItem *duplicate = new ClipItem(m_clip, info, m_fps, m_speed, m_strobe);
129     if (m_clipType == IMAGE || m_clipType == TEXT) duplicate->slotSetStartThumb(m_startPix);
130     else if (m_clipType != COLOR) {
131         if (info.cropStart == m_info.cropStart) duplicate->slotSetStartThumb(m_startPix);
132         if (info.cropStart + (info.endPos - info.startPos) == m_info.cropStart + (m_info.endPos - m_info.startPos)) duplicate->slotSetEndThumb(m_endPix);
133     }
134     //kDebug() << "// CLoning clip: " << (info.cropStart + (info.endPos - info.startPos)).frames(m_fps) << ", CURRENT end: " << (cropStart() + duration()).frames(m_fps);
135     duplicate->setEffectList(m_effectList);
136     duplicate->setVideoOnly(m_videoOnly);
137     duplicate->setAudioOnly(m_audioOnly);
138     //duplicate->setSpeed(m_speed);
139     return duplicate;
140 }
141
142 void ClipItem::setEffectList(const EffectsList effectList)
143 {
144     m_effectList.clone(effectList);
145     m_effectNames = m_effectList.effectNames().join(" / ");
146     if (!m_effectList.isEmpty()) setSelectedEffect(0);
147 }
148
149 const EffectsList ClipItem::effectList() const
150 {
151     return m_effectList;
152 }
153
154 int ClipItem::selectedEffectIndex() const
155 {
156     return m_selectedEffect;
157 }
158
159 void ClipItem::initEffect(QDomElement effect, int diff)
160 {
161     // the kdenlive_ix int is used to identify an effect in mlt's playlist, should
162     // not be changed
163     if (effect.attribute("kdenlive_ix").toInt() == 0)
164         effect.setAttribute("kdenlive_ix", QString::number(effectsCounter()));
165
166     if (effect.attribute("id") == "freeze" && diff > 0) {
167         EffectsList::setParameter(effect, "frame", QString::number(diff));
168     }
169
170     // Init parameter value & keyframes if required
171     QDomNodeList params = effect.elementsByTagName("parameter");
172     for (int i = 0; i < params.count(); i++) {
173         QDomElement e = params.item(i).toElement();
174         kDebug() << "// init eff: " << e.attribute("name");
175
176         // Check if this effect has a variable parameter
177         if (e.attribute("default").startsWith('%')) {
178             double evaluatedValue = ProfilesDialog::getStringEval(projectScene()->profile(), e.attribute("default"));
179             e.setAttribute("default", evaluatedValue);
180             if (e.hasAttribute("value") && e.attribute("value").startsWith('%')) {
181                 e.setAttribute("value", evaluatedValue);
182             }
183         }
184
185         if (!e.isNull() && e.attribute("type") == "keyframe") {
186             QString def = e.attribute("default");
187             // Effect has a keyframe type parameter, we need to set the values
188             if (e.attribute("keyframes").isEmpty()) {
189                 e.setAttribute("keyframes", QString::number(cropStart().frames(m_fps)) + ':' + def + ';' + QString::number((cropStart() + cropDuration()).frames(m_fps) - 1) + ':' + def);
190                 //kDebug() << "///// EFFECT KEYFRAMES INITED: " << e.attribute("keyframes");
191                 break;
192             }
193         }
194     }
195     if (effect.attribute("tag") == "volume" || effect.attribute("tag") == "brightness") {
196         if (effect.attribute("id") == "fadeout" || effect.attribute("id") == "fade_to_black") {
197             int end = (cropDuration() + cropStart()).frames(m_fps);
198             int start = end;
199             if (effect.attribute("id") == "fadeout") {
200                 if (m_effectList.hasEffect(QString(), "fade_to_black") == -1) {
201                     int effectDuration = EffectsList::parameter(effect, "in").toInt();
202                     if (effectDuration > cropDuration().frames(m_fps)) {
203                         effectDuration = cropDuration().frames(m_fps) / 2;
204                     }
205                     start -= effectDuration;
206                 } else {
207                     QDomElement fadeout = m_effectList.getEffectByTag(QString(), "fade_to_black");
208                     start -= EffectsList::parameter(fadeout, "out").toInt() - EffectsList::parameter(fadeout, "in").toInt();
209                 }
210             } else if (effect.attribute("id") == "fade_to_black") {
211                 if (m_effectList.hasEffect(QString(), "fadeout") == -1) {
212                     int effectDuration = EffectsList::parameter(effect, "in").toInt();
213                     if (effectDuration > cropDuration().frames(m_fps)) {
214                         effectDuration = cropDuration().frames(m_fps) / 2;
215                     }
216                     start -= effectDuration;
217                 } else {
218                     QDomElement fadeout = m_effectList.getEffectByTag(QString(), "fadeout");
219                     start -= EffectsList::parameter(fadeout, "out").toInt() - EffectsList::parameter(fadeout, "in").toInt();
220                 }
221             }
222             EffectsList::setParameter(effect, "in", QString::number(start));
223             EffectsList::setParameter(effect, "out", QString::number(end));
224         } else if (effect.attribute("id") == "fadein" || effect.attribute("id") == "fade_from_black") {
225             int start = cropStart().frames(m_fps);
226             int end = start;
227             if (effect.attribute("id") == "fadein") {
228                 if (m_effectList.hasEffect(QString(), "fade_from_black") == -1) {
229                     int effectDuration = EffectsList::parameter(effect, "out").toInt();
230                     if (effectDuration > cropDuration().frames(m_fps)) {
231                         effectDuration = cropDuration().frames(m_fps) / 2;
232                     }
233                     end += effectDuration;
234                 } else
235                     end += EffectsList::parameter(m_effectList.getEffectByTag(QString(), "fade_from_black"), "out").toInt();
236             } else if (effect.attribute("id") == "fade_from_black") {
237                 if (m_effectList.hasEffect(QString(), "fadein") == -1) {
238                     int effectDuration = EffectsList::parameter(effect, "out").toInt();
239                     if (effectDuration > cropDuration().frames(m_fps)) {
240                         effectDuration = cropDuration().frames(m_fps) / 2;
241                     }
242                     end += effectDuration;
243                 } else
244                     end += EffectsList::parameter(m_effectList.getEffectByTag(QString(), "fadein"), "out").toInt();
245             }
246             EffectsList::setParameter(effect, "in", QString::number(start));
247             EffectsList::setParameter(effect, "out", QString::number(end));
248         }
249     }
250 }
251
252 bool ClipItem::checkKeyFrames()
253 {
254     bool clipEffectsModified = false;
255     for (int ix = 0; ix < m_effectList.count(); ix ++) {
256         QString kfr = keyframes(ix);
257         if (!kfr.isEmpty()) {
258             const QStringList keyframes = kfr.split(';', QString::SkipEmptyParts);
259             QStringList newKeyFrames;
260             bool cutKeyFrame = false;
261             bool modified = false;
262             int lastPos = -1;
263             double lastValue = -1;
264             int start = cropStart().frames(m_fps);
265             int end = (cropStart() + cropDuration()).frames(m_fps);
266             foreach(const QString &str, keyframes) {
267                 int pos = str.section(':', 0, 0).toInt();
268                 double val = str.section(':', 1, 1).toDouble();
269                 if (pos - start < 0) {
270                     // a keyframe is defined before the start of the clip
271                     cutKeyFrame = true;
272                 } else if (cutKeyFrame) {
273                     // create new keyframe at clip start, calculate interpolated value
274                     if (pos > start) {
275                         int diff = pos - lastPos;
276                         double ratio = (double)(start - lastPos) / diff;
277                         double newValue = lastValue + (val - lastValue) * ratio;
278                         newKeyFrames.append(QString::number(start) + ':' + QString::number(newValue));
279                         modified = true;
280                     }
281                     cutKeyFrame = false;
282                 }
283                 if (!cutKeyFrame) {
284                     if (pos > end) {
285                         // create new keyframe at clip end, calculate interpolated value
286                         int diff = pos - lastPos;
287                         if (diff != 0) {
288                             double ratio = (double)(end - lastPos) / diff;
289                             double newValue = lastValue + (val - lastValue) * ratio;
290                             newKeyFrames.append(QString::number(end) + ':' + QString::number(newValue));
291                             modified = true;
292                         }
293                         break;
294                     } else {
295                         newKeyFrames.append(QString::number(pos) + ':' + QString::number(val));
296                     }
297                 }
298                 lastPos = pos;
299                 lastValue = val;
300             }
301             if (modified) {
302                 // update KeyFrames
303                 setKeyframes(ix, newKeyFrames.join(";"));
304                 clipEffectsModified = true;
305             }
306         }
307     }
308     return clipEffectsModified;
309 }
310
311 void ClipItem::setKeyframes(const int ix, const QString keyframes)
312 {
313     QDomElement effect = getEffectAt(ix);
314     if (effect.attribute("disabled") == "1") return;
315     QDomNodeList params = effect.elementsByTagName("parameter");
316     for (int i = 0; i < params.count(); i++) {
317         QDomElement e = params.item(i).toElement();
318         if (!e.isNull() && e.attribute("type") == "keyframe") {
319             e.setAttribute("keyframes", keyframes);
320             if (ix == m_selectedEffect) {
321                 m_keyframes.clear();
322                 double max = e.attribute("max").toDouble();
323                 double min = e.attribute("min").toDouble();
324                 m_keyframeFactor = 100.0 / (max - min);
325                 m_keyframeDefault = e.attribute("default").toDouble();
326                 // parse keyframes
327                 const QStringList keyframes = e.attribute("keyframes").split(';', QString::SkipEmptyParts);
328                 foreach(const QString &str, keyframes) {
329                     int pos = str.section(':', 0, 0).toInt();
330                     double val = str.section(':', 1, 1).toDouble();
331                     m_keyframes[pos] = val;
332                 }
333                 update();
334                 return;
335             }
336             break;
337         }
338     }
339 }
340
341
342 void ClipItem::setSelectedEffect(const int ix)
343 {
344     m_selectedEffect = ix;
345     QDomElement effect = effectAt(m_selectedEffect);
346     if (effect.isNull() == false) {
347         QDomNodeList params = effect.elementsByTagName("parameter");
348         if (effect.attribute("disabled") != "1")
349             for (int i = 0; i < params.count(); i++) {
350                 QDomElement e = params.item(i).toElement();
351                 if (!e.isNull() && e.attribute("type") == "keyframe") {
352                     m_keyframes.clear();
353                     double max = e.attribute("max").toDouble();
354                     double min = e.attribute("min").toDouble();
355                     m_keyframeFactor = 100.0 / (max - min);
356                     m_keyframeDefault = e.attribute("default").toDouble();
357                     // parse keyframes
358                     const QStringList keyframes = e.attribute("keyframes").split(';', QString::SkipEmptyParts);
359                     foreach(const QString &str, keyframes) {
360                         int pos = str.section(':', 0, 0).toInt();
361                         double val = str.section(':', 1, 1).toDouble();
362                         m_keyframes[pos] = val;
363                     }
364                     update();
365                     return;
366                 }
367             }
368     }
369     if (!m_keyframes.isEmpty()) {
370         m_keyframes.clear();
371         update();
372     }
373 }
374
375 QString ClipItem::keyframes(const int index)
376 {
377     QString result;
378     QDomElement effect = effectAt(index);
379     QDomNodeList params = effect.elementsByTagName("parameter");
380
381     for (int i = 0; i < params.count(); i++) {
382         QDomElement e = params.item(i).toElement();
383         if (!e.isNull() && e.attribute("type") == "keyframe") {
384             result = e.attribute("keyframes");
385             break;
386         }
387     }
388     return result;
389 }
390
391 void ClipItem::updateKeyframeEffect()
392 {
393     // regenerate xml parameter from the clip keyframes
394     QDomElement effect = getEffectAt(m_selectedEffect);
395     if (effect.attribute("disabled") == "1") return;
396     QDomNodeList params = effect.elementsByTagName("parameter");
397
398     for (int i = 0; i < params.count(); i++) {
399         QDomElement e = params.item(i).toElement();
400         if (!e.isNull() && e.attribute("type") == "keyframe") {
401             QString keyframes;
402             if (m_keyframes.count() > 1) {
403                 QMap<int, int>::const_iterator i = m_keyframes.constBegin();
404                 while (i != m_keyframes.constEnd()) {
405                     keyframes.append(QString::number(i.key()) + ':' + QString::number(i.value()) + ';');
406                     ++i;
407                 }
408             }
409             // Effect has a keyframe type parameter, we need to set the values
410             //kDebug() << ":::::::::::::::   SETTING EFFECT KEYFRAMES: " << keyframes;
411             e.setAttribute("keyframes", keyframes);
412             break;
413         }
414     }
415 }
416
417 QDomElement ClipItem::selectedEffect()
418 {
419     if (m_selectedEffect == -1 || m_effectList.isEmpty()) return QDomElement();
420     return effectAt(m_selectedEffect);
421 }
422
423 void ClipItem::resetThumbs(bool clearExistingThumbs)
424 {
425     if (clearExistingThumbs) {
426         m_startPix = QPixmap();
427         m_endPix = QPixmap();
428         m_audioThumbCachePic.clear();
429     }
430     slotFetchThumbs();
431 }
432
433
434 void ClipItem::refreshClip(bool checkDuration)
435 {
436     if (checkDuration && (m_maxDuration != m_clip->maxDuration())) {
437         m_maxDuration = m_clip->maxDuration();
438         if (m_clipType != IMAGE && m_clipType != TEXT && m_clipType != COLOR) {
439             if (m_maxDuration != GenTime() && m_info.cropStart + m_info.cropDuration > m_maxDuration) {
440                 // Clip duration changed, make sure to stay in correct range
441                 if (m_info.cropStart > m_maxDuration) {
442                     m_info.cropStart = GenTime();
443                     m_info.cropDuration = qMin(m_info.cropDuration, m_maxDuration);
444                     updateRectGeometry();
445                 } else {
446                     m_info.cropDuration = m_maxDuration;
447                     updateRectGeometry();
448                 }
449             }
450         }
451     }
452     if (m_clipType == COLOR) {
453         QString colour = m_clip->getProperty("colour");
454         colour = colour.replace(0, 2, "#");
455         m_baseColor = QColor(colour.left(7));
456     } else resetThumbs(checkDuration);
457 }
458
459 void ClipItem::slotFetchThumbs()
460 {
461     if (scene() == NULL || m_clipType == AUDIO || m_clipType == COLOR) return;
462     if (m_clipType == IMAGE) {
463         if (m_startPix.isNull()) {
464             m_startPix = KThumb::getImage(KUrl(m_clip->getProperty("resource")), (int)(KdenliveSettings::trackheight() * KdenliveSettings::project_display_ratio()), KdenliveSettings::trackheight());
465             update();
466         }
467         return;
468     }
469
470     if (m_clipType == TEXT) {
471         if (m_startPix.isNull()) slotGetStartThumb();
472         return;
473     }
474
475     if (m_endPix.isNull() && m_startPix.isNull()) {
476         m_startThumbRequested = true;
477         m_endThumbRequested = true;
478         emit getThumb((int)m_speedIndependantInfo.cropStart.frames(m_fps), (int)(m_speedIndependantInfo.cropStart + m_speedIndependantInfo.cropDuration).frames(m_fps) - 1);
479     } else {
480         if (m_endPix.isNull()) {
481             slotGetEndThumb();
482         }
483         if (m_startPix.isNull()) {
484             slotGetStartThumb();
485         }
486     }
487 }
488
489 void ClipItem::slotGetStartThumb()
490 {
491     m_startThumbRequested = true;
492     emit getThumb((int)m_speedIndependantInfo.cropStart.frames(m_fps), -1);
493 }
494
495 void ClipItem::slotGetEndThumb()
496 {
497     m_endThumbRequested = true;
498     emit getThumb(-1, (int)(m_speedIndependantInfo.cropStart + m_speedIndependantInfo.cropDuration).frames(m_fps) - 1);
499 }
500
501
502 void ClipItem::slotSetStartThumb(QImage img)
503 {
504     if (!img.isNull() && img.format() == QImage::Format_ARGB32) {
505         QPixmap pix = QPixmap::fromImage(img);
506         m_startPix = pix;
507         QRectF r = sceneBoundingRect();
508         r.setRight(pix.width() + 2);
509         update(r);
510     }
511 }
512
513 void ClipItem::slotSetEndThumb(QImage img)
514 {
515     if (!img.isNull() && img.format() == QImage::Format_ARGB32) {
516         QPixmap pix = QPixmap::fromImage(img);
517         m_endPix = pix;
518         QRectF r = sceneBoundingRect();
519         r.setLeft(r.right() - pix.width() - 2);
520         update(r);
521     }
522 }
523
524 void ClipItem::slotThumbReady(int frame, QImage img)
525 {
526     if (scene() == NULL) return;
527     QRectF r = boundingRect();
528     QPixmap pix = QPixmap::fromImage(img);
529     double width = pix.width() / projectScene()->scale().x();
530     if (m_startThumbRequested && frame == m_speedIndependantInfo.cropStart.frames(m_fps)) {
531         m_startPix = pix;
532         m_startThumbRequested = false;
533         update(r.left(), r.top(), width, pix.height());
534         if (m_clipType == IMAGE || m_clipType == TEXT) {
535             update(r.right() - width, r.top(), width, pix.height());
536         }
537     } else if (m_endThumbRequested && frame == (m_speedIndependantInfo.cropStart + m_speedIndependantInfo.cropDuration).frames(m_fps) - 1) {
538         m_endPix = pix;
539         m_endThumbRequested = false;
540         update(r.right() - width, r.top(), width, pix.height());
541     }
542 }
543
544 void ClipItem::slotSetStartThumb(const QPixmap pix)
545 {
546     m_startPix = pix;
547 }
548
549 void ClipItem::slotSetEndThumb(const QPixmap pix)
550 {
551     m_endPix = pix;
552 }
553
554 QPixmap ClipItem::startThumb() const
555 {
556     return m_startPix;
557 }
558
559 QPixmap ClipItem::endThumb() const
560 {
561     return m_endPix;
562 }
563
564 void ClipItem::slotGotAudioData()
565 {
566     m_audioThumbReady = true;
567     if (m_clipType == AV && !isAudioOnly()) {
568         QRectF r = boundingRect();
569         r.setTop(r.top() + r.height() / 2 - 1);
570         update(r);
571     } else update();
572 }
573
574 int ClipItem::type() const
575 {
576     return AVWIDGET;
577 }
578
579 DocClipBase *ClipItem::baseClip() const
580 {
581     return m_clip;
582 }
583
584 QDomElement ClipItem::xml() const
585 {
586     QDomElement xml = m_clip->toXML();
587     if (m_speed != 1.0) xml.setAttribute("speed", m_speed);
588     if (m_strobe > 1) xml.setAttribute("strobe", m_strobe);
589     if (m_audioOnly) xml.setAttribute("audio_only", 1);
590     else if (m_videoOnly) xml.setAttribute("video_only", 1);
591     return xml;
592 }
593
594 int ClipItem::clipType() const
595 {
596     return m_clipType;
597 }
598
599 QString ClipItem::clipName() const
600 {
601     return m_clipName;
602 }
603
604 void ClipItem::setClipName(const QString &name)
605 {
606     m_clipName = name;
607 }
608
609 const QString ClipItem::clipProducer() const
610 {
611     return m_producer;
612 }
613
614 void ClipItem::flashClip()
615 {
616     if (m_timeLine == 0) {
617         m_timeLine = new QTimeLine(750, this);
618         m_timeLine->setUpdateInterval(80);
619         m_timeLine->setCurveShape(QTimeLine::EaseInOutCurve);
620         m_timeLine->setFrameRange(0, 100);
621         connect(m_timeLine, SIGNAL(valueChanged(qreal)), this, SLOT(animate(qreal)));
622     }
623     //m_timeLine->start();
624 }
625
626 void ClipItem::animate(qreal /*value*/)
627 {
628     QRectF r = boundingRect();
629     r.setHeight(20);
630     update(r);
631 }
632
633 // virtual
634 void ClipItem::paint(QPainter *painter,
635                      const QStyleOptionGraphicsItem *option,
636                      QWidget *)
637 {
638     QColor paintColor;
639     if (parentItem()) paintColor = QColor(255, 248, 149);
640     else paintColor = m_baseColor;
641     if (isSelected() || (parentItem() && parentItem()->isSelected())) paintColor = paintColor.darker();
642
643     painter->setMatrixEnabled(false);
644     const QRectF mapped = painter->matrix().mapRect(rect()).adjusted(0.5, 0, 0.5, 0);
645     const QRectF exposed = option->exposedRect;
646     painter->setClipRect(mapped);
647     painter->fillRect(mapped, paintColor);
648
649     // draw thumbnails
650     if (KdenliveSettings::videothumbnails() && !isAudioOnly()) {
651         QPen pen = painter->pen();
652         pen.setColor(QColor(255, 255, 255, 150));
653         const QRectF source(0.0, 0.0, (double) m_startPix.width(), (double) m_startPix.height());
654         painter->setPen(pen);
655         if ((m_clipType == IMAGE || m_clipType == TEXT) && !m_startPix.isNull()) {
656             const QPointF top = mapped.topRight() - QPointF(m_startPix.width() - 1, 0);
657             painter->drawPixmap(top, m_startPix);
658             QLineF l2(top.x(), mapped.top(), top.x(), mapped.bottom());
659             painter->drawLine(l2);
660         } else if (!m_endPix.isNull()) {
661             const QPointF top = mapped.topRight() - QPointF(m_endPix.width() - 1, 0);
662             painter->drawPixmap(top, m_endPix);
663             QLineF l2(top.x(), mapped.top(), top.x(), mapped.bottom());
664             painter->drawLine(l2);
665         }
666         if (!m_startPix.isNull()) {
667             painter->drawPixmap(mapped.topLeft(), m_startPix);
668             QLineF l2(mapped.left() + m_startPix.width(), mapped.top(), mapped.left() + m_startPix.width(), mapped.bottom());
669             painter->drawLine(l2);
670         }
671         painter->setPen(Qt::black);
672     }
673
674     // draw audio thumbnails
675     if (KdenliveSettings::audiothumbnails() && m_speed == 1.0 && !isVideoOnly() && ((m_clipType == AV && (exposed.bottom() > (rect().height() / 2) || isAudioOnly())) || m_clipType == AUDIO) && m_audioThumbReady) {
676
677         double startpixel = exposed.left();
678         if (startpixel < 0)
679             startpixel = 0;
680         double endpixel = exposed.right();
681         if (endpixel < 0)
682             endpixel = 0;
683         //kDebug()<<"///  REPAINTING AUDIO THMBS ZONE: "<<startpixel<<"x"<<endpixel;
684
685         /*QPainterPath path = m_clipType == AV ? roundRectPathLower : resultClipPath;*/
686         QRectF mappedRect;
687         if (m_clipType == AV && !isAudioOnly()) {
688             mappedRect = mapped;
689             mappedRect.setTop(mappedRect.bottom() - mapped.height() / 2);
690         } else mappedRect = mapped;
691
692         double scale = painter->matrix().m11();
693         int channels = baseClip()->getProperty("channels").toInt();
694         if (scale != m_framePixelWidth)
695             m_audioThumbCachePic.clear();
696         double cropLeft = m_info.cropStart.frames(m_fps);
697         const int clipStart = mappedRect.x();
698         const int mappedStartPixel =  painter->matrix().map(QPointF(startpixel + cropLeft, 0)).x() - clipStart;
699         const int mappedEndPixel =  painter->matrix().map(QPointF(endpixel + cropLeft, 0)).x() - clipStart;
700         cropLeft = cropLeft * scale;
701
702         if (channels >= 1) {
703             emit prepareAudioThumb(scale, mappedStartPixel, mappedEndPixel, channels);
704         }
705
706         for (int startCache = mappedStartPixel - (mappedStartPixel) % 100; startCache < mappedEndPixel; startCache += 100) {
707             if (m_audioThumbCachePic.contains(startCache) && !m_audioThumbCachePic[startCache].isNull())
708                 painter->drawPixmap(clipStart + startCache - cropLeft, mappedRect.y(),  m_audioThumbCachePic[startCache]);
709         }
710     }
711
712     // Draw effects names
713     if (!m_effectNames.isEmpty() && mapped.width() > 40) {
714         QRectF txtBounding = painter->boundingRect(mapped, Qt::AlignLeft | Qt::AlignTop, m_effectNames);
715         QColor bgColor;
716         if (m_timeLine && m_timeLine->state() == QTimeLine::Running) {
717             qreal value = m_timeLine->currentValue();
718             txtBounding.setWidth(txtBounding.width() * value);
719             bgColor.setRgb(50 + 200 *(1.0 - value), 50, 50, 100 + 50 * value);
720         } else bgColor.setRgb(50, 50, 90, 180);
721
722         QPainterPath rounded;
723         rounded.moveTo(txtBounding.bottomRight());
724         rounded.arcTo(txtBounding.right() - txtBounding.height() - 2, txtBounding.top() - txtBounding.height(), txtBounding.height() * 2, txtBounding.height() * 2, 270, 90);
725         rounded.lineTo(txtBounding.topLeft());
726         rounded.lineTo(txtBounding.bottomLeft());
727         painter->fillPath(rounded, bgColor);
728         painter->setPen(Qt::lightGray);
729         painter->drawText(txtBounding.adjusted(1, 0, 1, 0), Qt::AlignCenter, m_effectNames);
730     }
731
732     // Draw clip name
733     QColor frameColor(paintColor.darker());
734     if (isSelected() || (parentItem() && parentItem()->isSelected())) {
735         frameColor = QColor(Qt::red);
736     }
737     frameColor.setAlpha(160);
738
739     const QRectF txtBounding2 = painter->boundingRect(mapped, Qt::AlignHCenter | Qt::AlignVCenter, ' ' + m_clipName + ' ');
740     //painter->fillRect(txtBounding2, frameColor);
741     painter->setBrush(frameColor);
742     painter->setPen(Qt::NoPen);
743     painter->drawRoundedRect(txtBounding2, 3, 3);
744     painter->setBrush(QBrush(Qt::NoBrush));
745
746     //painter->setPen(QColor(0, 0, 0, 180));
747     //painter->drawText(txtBounding, Qt::AlignCenter, m_clipName);
748     if (m_videoOnly) {
749         painter->drawPixmap(txtBounding2.topLeft() - QPointF(17, -1), m_videoPix);
750     } else if (m_audioOnly) {
751         painter->drawPixmap(txtBounding2.topLeft() - QPointF(17, -1), m_audioPix);
752     }
753     painter->setPen(Qt::white);
754     painter->drawText(txtBounding2, Qt::AlignCenter, m_clipName);
755
756
757     // draw markers
758     QList < CommentedTime > markers = baseClip()->commentedSnapMarkers();
759     QList < CommentedTime >::Iterator it = markers.begin();
760     GenTime pos;
761     double framepos;
762     QBrush markerBrush(QColor(120, 120, 0, 140));
763     QPen pen = painter->pen();
764     pen.setColor(QColor(255, 255, 255, 200));
765     pen.setStyle(Qt::DotLine);
766
767     for (; it != markers.end(); ++it) {
768         pos = GenTime((int)((*it).time().frames(m_fps) / m_speed + 0.5), m_fps) - cropStart();
769         if (pos > GenTime()) {
770             if (pos > cropDuration()) break;
771             QLineF l(rect().x() + pos.frames(m_fps), rect().y(), rect().x() + pos.frames(m_fps), rect().bottom());
772             QLineF l2 = painter->matrix().map(l);
773             //framepos = scale * pos.frames(m_fps);
774             //QLineF l(framepos, 5, framepos, itemHeight - 5);
775             painter->setPen(pen);
776             painter->drawLine(l2);
777             if (KdenliveSettings::showmarkers()) {
778                 framepos = rect().x() + pos.frames(m_fps);
779                 const QRectF r1(framepos + 0.04, 10, rect().width() - framepos - 2, rect().height() - 10);
780                 const QRectF r2 = painter->matrix().mapRect(r1);
781                 const QRectF txtBounding3 = painter->boundingRect(r2, Qt::AlignLeft | Qt::AlignTop, ' ' + (*it).comment() + ' ');
782                 painter->setBrush(markerBrush);
783                 painter->setPen(Qt::NoPen);
784                 painter->drawRoundedRect(txtBounding3, 3, 3);
785                 painter->setBrush(QBrush(Qt::NoBrush));
786                 painter->setPen(Qt::white);
787                 painter->drawText(txtBounding3, Qt::AlignCenter, (*it).comment());
788             }
789             //painter->fillRect(QRect(br.x() + framepos, br.y(), 10, br.height()), QBrush(QColor(0, 0, 0, 150)));
790         }
791     }
792
793     // draw start / end fades
794     QBrush fades;
795     if (isSelected()) {
796         fades = QBrush(QColor(200, 50, 50, 150));
797     } else fades = QBrush(QColor(200, 200, 200, 200));
798
799     if (m_startFade != 0) {
800         QPainterPath fadeInPath;
801         fadeInPath.moveTo(0, 0);
802         fadeInPath.lineTo(0, rect().height());
803         fadeInPath.lineTo(m_startFade, 0);
804         fadeInPath.closeSubpath();
805         QPainterPath f1 = painter->matrix().map(fadeInPath);
806         painter->fillPath(f1/*.intersected(resultClipPath)*/, fades);
807         /*if (isSelected()) {
808             QLineF l(m_startFade * scale, 0, 0, itemHeight);
809             painter->drawLine(l);
810         }*/
811     }
812     if (m_endFade != 0) {
813         QPainterPath fadeOutPath;
814         fadeOutPath.moveTo(rect().width(), 0);
815         fadeOutPath.lineTo(rect().width(), rect().height());
816         fadeOutPath.lineTo(rect().width() - m_endFade, 0);
817         fadeOutPath.closeSubpath();
818         QPainterPath f1 = painter->matrix().map(fadeOutPath);
819         painter->fillPath(f1/*.intersected(resultClipPath)*/, fades);
820         /*if (isSelected()) {
821             QLineF l(itemWidth - m_endFade * scale, 0, itemWidth, itemHeight);
822             painter->drawLine(l);
823         }*/
824     }
825
826
827     painter->setPen(QPen(Qt::lightGray));
828     // draw effect or transition keyframes
829     if (mapped.width() > 20) drawKeyFrames(painter, exposed);
830
831     //painter->setMatrixEnabled(true);
832
833     // draw clip border
834     // expand clip rect to allow correct painting of clip border
835     QPen pen1(frameColor);
836     painter->setPen(pen1);
837     painter->setClipping(false);
838     painter->drawRect(painter->matrix().mapRect(rect()));
839 }
840
841
842 OPERATIONTYPE ClipItem::operationMode(QPointF pos)
843 {
844     if (isItemLocked()) return NONE;
845     const double scale = projectScene()->scale().x();
846     double maximumOffset = 6 / scale;
847     if (isSelected() || (parentItem() && parentItem()->isSelected())) {
848         m_editedKeyframe = mouseOverKeyFrames(pos, maximumOffset);
849         if (m_editedKeyframe != -1) return KEYFRAME;
850     }
851     QRectF rect = sceneBoundingRect();
852     int addtransitionOffset = 10;
853     // Don't allow add transition if track height is very small
854     if (rect.height() < 30) addtransitionOffset = 0;
855
856     if (qAbs((int)(pos.x() - (rect.x() + m_startFade))) < maximumOffset  && qAbs((int)(pos.y() - rect.y())) < 6) {
857         if (m_startFade == 0) setToolTip(i18n("Add audio fade"));
858         else setToolTip(i18n("Audio fade duration: %1s", GenTime(m_startFade, m_fps).seconds()));
859         return FADEIN;
860     } else if (pos.x() - rect.x() < maximumOffset && (rect.bottom() - pos.y() > addtransitionOffset)) {
861         setToolTip(i18n("Crop from start: %1s", cropStart().seconds()));
862         return RESIZESTART;
863     } else if (qAbs((int)(pos.x() - (rect.x() + rect.width() - m_endFade))) < maximumOffset && qAbs((int)(pos.y() - rect.y())) < 6) {
864         if (m_endFade == 0) setToolTip(i18n("Add audio fade"));
865         else setToolTip(i18n("Audio fade duration: %1s", GenTime(m_endFade, m_fps).seconds()));
866         return FADEOUT;
867     } else if ((rect.right() - pos.x() < maximumOffset) && (rect.bottom() - pos.y() > addtransitionOffset)) {
868         setToolTip(i18n("Clip duration: %1s", cropDuration().seconds()));
869         return RESIZEEND;
870     } else if ((pos.x() - rect.x() < 16 / scale) && (rect.bottom() - pos.y() <= addtransitionOffset)) {
871         setToolTip(i18n("Add transition"));
872         return TRANSITIONSTART;
873     } else if ((rect.right() - pos.x() < 16 / scale) && (rect.bottom() - pos.y() <= addtransitionOffset)) {
874         setToolTip(i18n("Add transition"));
875         return TRANSITIONEND;
876     }
877     setToolTip(QString());
878     return MOVE;
879 }
880
881 QList <GenTime> ClipItem::snapMarkers() const
882 {
883     QList < GenTime > snaps;
884     QList < GenTime > markers = baseClip()->snapMarkers();
885     GenTime pos;
886
887     for (int i = 0; i < markers.size(); i++) {
888
889         pos = GenTime((int)(markers.at(i).frames(m_fps) / m_speed + 0.5), m_fps) - cropStart();
890         if (pos > GenTime()) {
891             if (pos > cropDuration()) break;
892             else snaps.append(pos + startPos());
893         }
894     }
895     return snaps;
896 }
897
898 QList <CommentedTime> ClipItem::commentedSnapMarkers() const
899 {
900     QList < CommentedTime > snaps;
901     QList < CommentedTime > markers = baseClip()->commentedSnapMarkers();
902     GenTime pos;
903
904     for (int i = 0; i < markers.size(); i++) {
905         pos = GenTime((int)(markers.at(i).time().frames(m_fps) / m_speed + 0.5), m_fps) - cropStart();
906         if (pos > GenTime()) {
907             if (pos > cropDuration()) break;
908             else snaps.append(CommentedTime(pos + startPos(), markers.at(i).comment()));
909         }
910     }
911     return snaps;
912 }
913
914 void ClipItem::slotPrepareAudioThumb(double pixelForOneFrame, int startpixel, int endpixel, int channels)
915 {
916     QRectF re =  sceneBoundingRect();
917     if (m_clipType == AV && !isAudioOnly()) re.setTop(re.y() + re.height() / 2);
918
919     //kDebug() << "// PREP AUDIO THMB FRMO : scale:" << pixelForOneFrame<< ", from: " << startpixel << ", to: " << endpixel;
920     //if ( (!audioThumbWasDrawn || framePixelWidth!=pixelForOneFrame ) && !baseClip()->audioFrameChache.isEmpty()){
921
922     for (int startCache = startpixel - startpixel % 100; startCache < endpixel; startCache += 100) {
923         //kDebug() << "creating " << startCache;
924         //if (framePixelWidth!=pixelForOneFrame  ||
925         if (m_framePixelWidth == pixelForOneFrame && m_audioThumbCachePic.contains(startCache))
926             continue;
927         if (m_audioThumbCachePic[startCache].isNull() || m_framePixelWidth != pixelForOneFrame) {
928             m_audioThumbCachePic[startCache] = QPixmap(100, (int)(re.height()));
929             m_audioThumbCachePic[startCache].fill(QColor(180, 180, 200, 140));
930         }
931         bool fullAreaDraw = pixelForOneFrame < 10;
932         QMap<int, QPainterPath > positiveChannelPaths;
933         QMap<int, QPainterPath > negativeChannelPaths;
934         QPainter pixpainter(&m_audioThumbCachePic[startCache]);
935         QPen audiopen;
936         audiopen.setWidth(0);
937         pixpainter.setPen(audiopen);
938         //pixpainter.setRenderHint(QPainter::Antialiasing,true);
939         //pixpainter.drawLine(0,0,100,re.height());
940         // Bail out, if caller provided invalid data
941         if (channels <= 0) {
942             kWarning() << "Unable to draw image with " << channels << "number of channels";
943             return;
944         }
945
946         int channelHeight = m_audioThumbCachePic[startCache].height() / channels;
947
948         for (int i = 0; i < channels; i++) {
949
950             positiveChannelPaths[i].moveTo(0, channelHeight*i + channelHeight / 2);
951             negativeChannelPaths[i].moveTo(0, channelHeight*i + channelHeight / 2);
952         }
953
954         for (int samples = 0; samples <= 100; samples++) {
955             double frame = (double)(samples + startCache - 0) / pixelForOneFrame;
956             int sample = (int)((frame - (int)(frame)) * 20);   // AUDIO_FRAME_SIZE
957             if (frame < 0 || sample < 0 || sample > 19)
958                 continue;
959             QMap<int, QByteArray> frame_channel_data = baseClip()->m_audioFrameCache[(int)frame];
960
961             for (int channel = 0; channel < channels && frame_channel_data[channel].size() > 0; channel++) {
962
963                 int y = channelHeight * channel + channelHeight / 2;
964                 int delta = (int)(frame_channel_data[channel][sample] - 127 / 2)  * channelHeight / 64;
965                 if (fullAreaDraw) {
966                     positiveChannelPaths[channel].lineTo(samples, 0.1 + y + qAbs(delta));
967                     negativeChannelPaths[channel].lineTo(samples, 0.1 + y - qAbs(delta));
968                 } else {
969                     positiveChannelPaths[channel].lineTo(samples, 0.1 + y + delta);
970                     negativeChannelPaths[channel].lineTo(samples, 0.1 + y - delta);
971                 }
972             }
973             for (int channel = 0; channel < channels ; channel++)
974                 if (fullAreaDraw && samples == 100) {
975                     positiveChannelPaths[channel].lineTo(samples, channelHeight*channel + channelHeight / 2);
976                     negativeChannelPaths[channel].lineTo(samples, channelHeight*channel + channelHeight / 2);
977                     positiveChannelPaths[channel].lineTo(0, channelHeight*channel + channelHeight / 2);
978                     negativeChannelPaths[channel].lineTo(0, channelHeight*channel + channelHeight / 2);
979                 }
980
981         }
982         pixpainter.setPen(QPen(QColor(0, 0, 0)));
983         pixpainter.setBrush(QBrush(QColor(60, 60, 60)));
984
985         for (int i = 0; i < channels; i++) {
986             if (fullAreaDraw) {
987                 //pixpainter.fillPath(positiveChannelPaths[i].united(negativeChannelPaths[i]),QBrush(Qt::SolidPattern));//or singleif looks better
988                 pixpainter.drawPath(positiveChannelPaths[i].united(negativeChannelPaths[i]));//or singleif looks better
989             } else
990                 pixpainter.drawPath(positiveChannelPaths[i]);
991         }
992     }
993     //audioThumbWasDrawn=true;
994     m_framePixelWidth = pixelForOneFrame;
995
996     //}
997 }
998
999 int ClipItem::fadeIn() const
1000 {
1001     return m_startFade;
1002 }
1003
1004 int ClipItem::fadeOut() const
1005 {
1006     return m_endFade;
1007 }
1008
1009
1010 void ClipItem::setFadeIn(int pos)
1011 {
1012     if (pos == m_startFade) return;
1013     int oldIn = m_startFade;
1014     if (pos < 0) pos = 0;
1015     if (pos > cropDuration().frames(m_fps)) pos = (int)(cropDuration().frames(m_fps));
1016     m_startFade = pos;
1017     QRectF rect = boundingRect();
1018     update(rect.x(), rect.y(), qMax(oldIn, pos), rect.height());
1019 }
1020
1021 void ClipItem::setFadeOut(int pos)
1022 {
1023     if (pos == m_endFade) return;
1024     int oldOut = m_endFade;
1025     if (pos < 0) pos = 0;
1026     if (pos > cropDuration().frames(m_fps)) pos = (int)(cropDuration().frames(m_fps));
1027     m_endFade = pos;
1028     QRectF rect = boundingRect();
1029     update(rect.x() + rect.width() - qMax(oldOut, pos), rect.y(), qMax(oldOut, pos), rect.height());
1030
1031 }
1032
1033 /*
1034 //virtual
1035 void ClipItem::hoverEnterEvent(QGraphicsSceneHoverEvent *e)
1036 {
1037     //if (e->pos().x() < 20) m_hover = true;
1038     return;
1039     if (isItemLocked()) return;
1040     m_hover = true;
1041     QRectF r = boundingRect();
1042     double width = 35 / projectScene()->scale().x();
1043     double height = r.height() / 2;
1044     //WARNING: seems like it generates a full repaint of the clip, maybe not so good...
1045     update(r.x(), r.y() + height, width, height);
1046     update(r.right() - width, r.y() + height, width, height);
1047 }
1048
1049 //virtual
1050 void ClipItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *)
1051 {
1052     if (isItemLocked()) return;
1053     m_hover = false;
1054     QRectF r = boundingRect();
1055     double width = 35 / projectScene()->scale().x();
1056     double height = r.height() / 2;
1057     //WARNING: seems like it generates a full repaint of the clip, maybe not so good...
1058     update(r.x(), r.y() + height, width, height);
1059     update(r.right() - width, r.y() + height, width, height);
1060 }
1061 */
1062
1063 void ClipItem::resizeStart(int posx)
1064 {
1065     const int min = (startPos() - cropStart()).frames(m_fps);
1066     if (posx < min) posx = min;
1067     if (posx == startPos().frames(m_fps)) return;
1068     const int previous = cropStart().frames(m_fps);
1069     AbstractClipItem::resizeStart(posx);
1070
1071     // set speed independant info
1072     m_speedIndependantInfo = m_info;
1073     m_speedIndependantInfo.cropStart = GenTime((int)(m_info.cropStart.frames(m_fps) * m_speed), m_fps);
1074     m_speedIndependantInfo.cropDuration = GenTime((int)(m_info.cropDuration.frames(m_fps) * m_speed), m_fps);
1075
1076     if ((int) cropStart().frames(m_fps) != previous) {
1077         if (m_hasThumbs && KdenliveSettings::videothumbnails()) {
1078             m_startThumbTimer.start(150);
1079         }
1080     }
1081 }
1082
1083 void ClipItem::resizeEnd(int posx)
1084 {
1085     const int max = (startPos() - cropStart() + maxDuration()).frames(m_fps);
1086     if (posx > max && maxDuration() != GenTime()) posx = max;
1087     if (posx == endPos().frames(m_fps)) return;
1088     //kDebug() << "// NEW POS: " << posx << ", OLD END: " << endPos().frames(m_fps);
1089     const int previous = cropDuration().frames(m_fps);
1090     AbstractClipItem::resizeEnd(posx);
1091
1092     // set speed independant info
1093     m_speedIndependantInfo = m_info;
1094     m_speedIndependantInfo.cropStart = GenTime((int)(m_info.cropStart.frames(m_fps) * m_speed), m_fps);
1095     m_speedIndependantInfo.cropDuration = GenTime((int)(m_info.cropDuration.frames(m_fps) * m_speed), m_fps);
1096
1097     if ((int) cropDuration().frames(m_fps) != previous) {
1098         if (m_hasThumbs && KdenliveSettings::videothumbnails()) {
1099             m_endThumbTimer.start(150);
1100         }
1101     }
1102 }
1103
1104
1105 bool ClipItem::checkEffectsKeyframesPos(const int previous, const int current, bool fromStart)
1106 {
1107     bool modified = false;
1108     for (int i = 0; i < m_effectList.count(); i++) {
1109         QDomElement effect = m_effectList.at(i);
1110         QDomNodeList params = effect.elementsByTagName("parameter");
1111         for (int j = 0; j < params.count(); j++) {
1112             QDomElement e = params.item(i).toElement();
1113             if (e.attribute("type") == "keyframe") {
1114                 // parse keyframes and adjust values
1115                 const QStringList keyframes = e.attribute("keyframes").split(';', QString::SkipEmptyParts);
1116                 QMap <int, double> kfr;
1117                 int pos;
1118                 double val;
1119                 foreach(const QString &str, keyframes) {
1120                     pos = str.section(':', 0, 0).toInt();
1121                     val = str.section(':', 1, 1).toDouble();
1122                     if (pos == previous) {
1123                         kfr[current] = val;
1124                         modified = true;
1125                     } else {
1126                         if ((fromStart && pos >= current) || (!fromStart && pos <= current)) {
1127                             kfr[pos] = val;
1128                             modified = true;
1129                         }
1130                     }
1131                 }
1132                 if (modified) {
1133                     QString newkfr;
1134                     QMap<int, double>::const_iterator k = kfr.constBegin();
1135                     while (k != kfr.constEnd()) {
1136                         newkfr.append(QString::number(k.key()) + ':' + QString::number(k.value()) + ';');
1137                         ++k;
1138                     }
1139                     e.setAttribute("keyframes", newkfr);
1140                     break;
1141                 }
1142             }
1143         }
1144     }
1145     if (modified && m_selectedEffect >= 0) setSelectedEffect(m_selectedEffect);
1146     return modified;
1147 }
1148
1149 //virtual
1150 QVariant ClipItem::itemChange(GraphicsItemChange change, const QVariant &value)
1151 {
1152     if (change == ItemPositionChange && scene()) {
1153         // calculate new position.
1154         //if (parentItem()) return pos();
1155         QPointF newPos = value.toPointF();
1156         //kDebug() << "/// MOVING CLIP ITEM.------------\n++++++++++";
1157         int xpos = projectScene()->getSnapPointForPos((int) newPos.x(), KdenliveSettings::snaptopoints());
1158         xpos = qMax(xpos, 0);
1159         newPos.setX(xpos);
1160         int newTrack = newPos.y() / KdenliveSettings::trackheight();
1161         newTrack = qMin(newTrack, projectScene()->tracksCount() - 1);
1162         newTrack = qMax(newTrack, 0);
1163         newPos.setY((int)(newTrack  * KdenliveSettings::trackheight() + 1));
1164         // Only one clip is moving
1165         QRectF sceneShape = rect();
1166         sceneShape.translate(newPos);
1167         QList<QGraphicsItem*> items;
1168         if (projectScene()->editMode() == NORMALEDIT)
1169             items = scene()->items(sceneShape, Qt::IntersectsItemShape);
1170         items.removeAll(this);
1171         bool forwardMove = newPos.x() > pos().x();
1172         int offset = 0;
1173         if (!items.isEmpty()) {
1174             for (int i = 0; i < items.count(); i++) {
1175                 if (items.at(i)->type() == type()) {
1176                     // Collision!
1177                     QPointF otherPos = items.at(i)->pos();
1178                     if ((int) otherPos.y() != (int) pos().y()) {
1179                         return pos();
1180                     }
1181                     if (forwardMove) {
1182                         offset = qMax(offset, (int)(newPos.x() - (static_cast < AbstractClipItem* >(items.at(i))->startPos() - cropDuration()).frames(m_fps)));
1183                     } else {
1184                         offset = qMax(offset, (int)((static_cast < AbstractClipItem* >(items.at(i))->endPos().frames(m_fps)) - newPos.x()));
1185                     }
1186
1187                     if (offset > 0) {
1188                         if (forwardMove) {
1189                             sceneShape.translate(QPointF(-offset, 0));
1190                             newPos.setX(newPos.x() - offset);
1191                         } else {
1192                             sceneShape.translate(QPointF(offset, 0));
1193                             newPos.setX(newPos.x() + offset);
1194                         }
1195                         QList<QGraphicsItem*> subitems = scene()->items(sceneShape, Qt::IntersectsItemShape);
1196                         subitems.removeAll(this);
1197                         for (int j = 0; j < subitems.count(); j++) {
1198                             if (subitems.at(j)->type() == type()) {
1199                                 m_info.startPos = GenTime((int) pos().x(), m_fps);
1200                                 return pos();
1201                             }
1202                         }
1203                     }
1204
1205                     m_info.track = newTrack;
1206                     m_info.startPos = GenTime((int) newPos.x(), m_fps);
1207                     return newPos;
1208                 }
1209             }
1210         }
1211         m_info.track = newTrack;
1212         m_info.startPos = GenTime((int) newPos.x(), m_fps);
1213         //kDebug()<<"// ITEM NEW POS: "<<newPos.x()<<", mapped: "<<mapToScene(newPos.x(), 0).x();
1214         return newPos;
1215     }
1216     return QGraphicsItem::itemChange(change, value);
1217 }
1218
1219 // virtual
1220 /*void ClipItem::mouseMoveEvent(QGraphicsSceneMouseEvent * event) {
1221 }*/
1222
1223 int ClipItem::effectsCounter()
1224 {
1225     return effectsCount() + 1;
1226 }
1227
1228 int ClipItem::effectsCount()
1229 {
1230     return m_effectList.count();
1231 }
1232
1233 int ClipItem::hasEffect(const QString &tag, const QString &id) const
1234 {
1235     return m_effectList.hasEffect(tag, id);
1236 }
1237
1238 QStringList ClipItem::effectNames()
1239 {
1240     return m_effectList.effectNames();
1241 }
1242
1243 QDomElement ClipItem::effectAt(int ix) const
1244 {
1245     if (ix > m_effectList.count() - 1 || ix < 0 || m_effectList.at(ix).isNull()) return QDomElement();
1246     return m_effectList.at(ix).cloneNode().toElement();
1247 }
1248
1249 QDomElement ClipItem::getEffectAt(int ix) const
1250 {
1251     if (ix > m_effectList.count() - 1 || ix < 0 || m_effectList.at(ix).isNull()) return QDomElement();
1252     return m_effectList.at(ix);
1253 }
1254
1255 void ClipItem::setEffectAt(int ix, QDomElement effect)
1256 {
1257     if (ix < 0 || ix > (m_effectList.count() - 1) || effect.isNull()) {
1258         kDebug() << "Invalid effect index: " << ix;
1259         return;
1260     }
1261     //kDebug() << "CHange EFFECT AT: " << ix << ", CURR: " << m_effectList.at(ix).attribute("tag") << ", NEW: " << effect.attribute("tag");
1262     effect.setAttribute("kdenlive_ix", ix + 1);
1263     m_effectList.replace(ix, effect);
1264     m_effectNames = m_effectList.effectNames().join(" / ");
1265     QString id = effect.attribute("id");
1266     if (id == "fadein" || id == "fadeout" || id == "fade_from_black" || id == "fade_to_black")
1267         update();
1268     else {
1269         QRectF r = boundingRect();
1270         r.setHeight(20);
1271         update(r);
1272     }
1273 }
1274
1275 EffectsParameterList ClipItem::addEffect(const QDomElement effect, bool /*animate*/)
1276 {
1277     bool needRepaint = false;
1278     int ix;
1279     if (!effect.hasAttribute("kdenlive_ix")) {
1280         ix = effectsCounter();
1281     } else ix = effect.attribute("kdenlive_ix").toInt();
1282     if (!m_effectList.isEmpty() && ix <= m_effectList.count()) {
1283         needRepaint = true;
1284         m_effectList.insert(ix - 1, effect);
1285         for (int i = ix; i < m_effectList.count(); i++) {
1286             int index = m_effectList.item(i).attribute("kdenlive_ix").toInt();
1287             if (index >= ix) m_effectList.item(i).setAttribute("kdenlive_ix", index + 1);
1288         }
1289     } else m_effectList.append(effect);
1290     EffectsParameterList parameters;
1291     parameters.addParam("tag", effect.attribute("tag"));
1292     parameters.addParam("kdenlive_ix", effect.attribute("kdenlive_ix"));
1293     if (effect.hasAttribute("src")) parameters.addParam("src", effect.attribute("src"));
1294     if (effect.hasAttribute("disabled")) parameters.addParam("disabled", effect.attribute("disabled"));
1295
1296
1297     QString effectId = effect.attribute("id");
1298     if (effectId.isEmpty()) effectId = effect.attribute("tag");
1299     parameters.addParam("id", effectId);
1300
1301     QDomNodeList params = effect.elementsByTagName("parameter");
1302     int fade = 0;
1303     for (int i = 0; i < params.count(); i++) {
1304         QDomElement e = params.item(i).toElement();
1305         if (!e.isNull()) {
1306             if (e.attribute("type") == "keyframe") {
1307                 parameters.addParam("keyframes", e.attribute("keyframes"));
1308                 parameters.addParam("max", e.attribute("max"));
1309                 parameters.addParam("min", e.attribute("min"));
1310                 parameters.addParam("factor", e.attribute("factor", "1"));
1311                 parameters.addParam("starttag", e.attribute("starttag", "start"));
1312                 parameters.addParam("endtag", e.attribute("endtag", "end"));
1313             }
1314
1315             if (e.attribute("factor", "1") == "1") {
1316                 parameters.addParam(e.attribute("name"), e.attribute("value"));
1317
1318                 // check if it is a fade effect
1319                 if (effectId == "fadein") {
1320                     needRepaint = true;
1321                     if (m_effectList.hasEffect(QString(), "fade_from_black") == -1) {
1322                         if (e.attribute("name") == "out") fade += e.attribute("value").toInt();
1323                         else if (e.attribute("name") == "in") fade -= e.attribute("value").toInt();
1324                     } else {
1325                         QDomElement fadein = m_effectList.getEffectByTag(QString(), "fade_from_black");
1326                         if (fadein.attribute("name") == "out") fade += fadein.attribute("value").toInt();
1327                         else if (fadein.attribute("name") == "in") fade -= fadein.attribute("value").toInt();
1328                     }
1329                 } else if (effectId == "fade_from_black") {
1330                     needRepaint = true;
1331                     if (m_effectList.hasEffect(QString(), "fadein") == -1) {
1332                         if (e.attribute("name") == "out") fade += e.attribute("value").toInt();
1333                         else if (e.attribute("name") == "in") fade -= e.attribute("value").toInt();
1334                     } else {
1335                         QDomElement fadein = m_effectList.getEffectByTag(QString(), "fadein");
1336                         if (fadein.attribute("name") == "out") fade += fadein.attribute("value").toInt();
1337                         else if (fadein.attribute("name") == "in") fade -= fadein.attribute("value").toInt();
1338                     }
1339                 } else if (effectId == "fadeout") {
1340                     needRepaint = true;
1341                     if (m_effectList.hasEffect(QString(), "fade_to_black") == -1) {
1342                         if (e.attribute("name") == "out") fade -= e.attribute("value").toInt();
1343                         else if (e.attribute("name") == "in") fade += e.attribute("value").toInt();
1344                     } else {
1345                         QDomElement fadeout = m_effectList.getEffectByTag(QString(), "fade_to_black");
1346                         if (fadeout.attribute("name") == "out") fade -= fadeout.attribute("value").toInt();
1347                         else if (fadeout.attribute("name") == "in") fade += fadeout.attribute("value").toInt();
1348                     }
1349                 } else if (effectId == "fade_to_black") {
1350                     needRepaint = true;
1351                     if (m_effectList.hasEffect(QString(), "fadeout") == -1) {
1352                         if (e.attribute("name") == "out") fade -= e.attribute("value").toInt();
1353                         else if (e.attribute("name") == "in") fade += e.attribute("value").toInt();
1354                     } else {
1355                         QDomElement fadeout = m_effectList.getEffectByTag(QString(), "fadeout");
1356                         if (fadeout.attribute("name") == "out") fade -= fadeout.attribute("value").toInt();
1357                         else if (fadeout.attribute("name") == "in") fade += fadeout.attribute("value").toInt();
1358                     }
1359                 }
1360             } else {
1361                 double fact;
1362                 if (e.attribute("factor").startsWith('%')) {
1363                     fact = ProfilesDialog::getStringEval(projectScene()->profile(), e.attribute("factor"));
1364                 } else fact = e.attribute("factor", "1").toDouble();
1365                 parameters.addParam(e.attribute("name"), QString::number(e.attribute("value").toDouble() / fact));
1366             }
1367         }
1368     }
1369     m_effectNames = m_effectList.effectNames().join(" / ");
1370     if (fade > 0) m_startFade = fade;
1371     else if (fade < 0) m_endFade = -fade;
1372
1373     if (m_selectedEffect == -1) {
1374         setSelectedEffect(0);
1375     } else if (m_selectedEffect == ix - 1) setSelectedEffect(m_selectedEffect);
1376     if (needRepaint) update(boundingRect());
1377     /*if (animate) {
1378         flashClip();
1379     } */
1380     else { /*if (!needRepaint) */
1381         QRectF r = boundingRect();
1382         r.setHeight(20);
1383         update(r);
1384     }
1385     return parameters;
1386 }
1387
1388 EffectsParameterList ClipItem::getEffectArgs(const QDomElement effect)
1389 {
1390     EffectsParameterList parameters;
1391     parameters.addParam("tag", effect.attribute("tag"));
1392     parameters.addParam("kdenlive_ix", effect.attribute("kdenlive_ix"));
1393     parameters.addParam("id", effect.attribute("id"));
1394     if (effect.hasAttribute("src")) parameters.addParam("src", effect.attribute("src"));
1395     if (effect.hasAttribute("disabled")) parameters.addParam("disabled", effect.attribute("disabled"));
1396
1397     QDomNodeList params = effect.elementsByTagName("parameter");
1398     for (int i = 0; i < params.count(); i++) {
1399         QDomElement e = params.item(i).toElement();
1400         //kDebug() << "/ / / /SENDING EFFECT PARAM: " << e.attribute("type") << ", NAME_ " << e.attribute("tag");
1401         if (e.attribute("type") == "keyframe") {
1402             kDebug() << "/ / / /SENDING KEYFR EFFECT TYPE";
1403             parameters.addParam("keyframes", e.attribute("keyframes"));
1404             parameters.addParam("max", e.attribute("max"));
1405             parameters.addParam("min", e.attribute("min"));
1406             parameters.addParam("factor", e.attribute("factor", "1"));
1407             parameters.addParam("starttag", e.attribute("starttag", "start"));
1408             parameters.addParam("endtag", e.attribute("endtag", "end"));
1409         } else if (e.attribute("namedesc").contains(';')) {
1410             QString format = e.attribute("format");
1411             QStringList separators = format.split("%d", QString::SkipEmptyParts);
1412             QStringList values = e.attribute("value").split(QRegExp("[,:;x]"));
1413             QString neu;
1414             QTextStream txtNeu(&neu);
1415             if (values.size() > 0)
1416                 txtNeu << (int)values[0].toDouble();
1417             for (int i = 0; i < separators.size() && i + 1 < values.size(); i++) {
1418                 txtNeu << separators[i];
1419                 txtNeu << (int)(values[i+1].toDouble());
1420             }
1421             parameters.addParam("start", neu);
1422         } else {
1423             if (e.attribute("factor", "1") != "1") {
1424                 double fact;
1425                 if (e.attribute("factor").startsWith('%')) {
1426                     fact = ProfilesDialog::getStringEval(projectScene()->profile(), e.attribute("factor"));
1427                 } else fact = e.attribute("factor", "1").toDouble();
1428                 parameters.addParam(e.attribute("name"), QString::number(e.attribute("value").toDouble() / fact));
1429             } else {
1430                 parameters.addParam(e.attribute("name"), e.attribute("value"));
1431             }
1432         }
1433     }
1434     return parameters;
1435 }
1436
1437 void ClipItem::deleteEffect(QString index)
1438 {
1439     bool needRepaint = false;
1440     QString ix;
1441
1442     for (int i = 0; i < m_effectList.count(); ++i) {
1443         ix = m_effectList.at(i).attribute("kdenlive_ix");
1444         if (ix == index) {
1445             QString effectId = m_effectList.at(i).attribute("id");
1446             if ((effectId == "fadein" && hasEffect(QString(), "fade_from_black") == -1) ||
1447                     (effectId == "fade_from_black" && hasEffect(QString(), "fadein") == -1)) {
1448                 m_startFade = 0;
1449                 needRepaint = true;
1450             } else if ((effectId == "fadeout" && hasEffect(QString(), "fade_to_black") == -1) ||
1451                        (effectId == "fade_to_black" && hasEffect(QString(), "fadeout") == -1)) {
1452                 m_endFade = 0;
1453                 needRepaint = true;
1454             } else if (EffectsList::hasKeyFrames(m_effectList.at(i))) needRepaint = true;
1455             m_effectList.removeAt(i);
1456             i--;
1457         } else if (ix.toInt() > index.toInt()) {
1458             m_effectList.item(i).setAttribute("kdenlive_ix", ix.toInt() - 1);
1459         }
1460     }
1461     m_effectNames = m_effectList.effectNames().join(" / ");
1462
1463     if (m_effectList.isEmpty() || m_selectedEffect + 1 == index.toInt()) {
1464         // Current effect was removed
1465         if (index.toInt() > m_effectList.count() - 1) {
1466             setSelectedEffect(m_effectList.count() - 1);
1467         } else setSelectedEffect(index.toInt());
1468     }
1469     if (needRepaint) update(boundingRect());
1470     else {
1471         QRectF r = boundingRect();
1472         r.setHeight(20);
1473         update(r);
1474     }
1475     //if (!m_effectList.isEmpty()) flashClip();
1476 }
1477
1478 double ClipItem::speed() const
1479 {
1480     return m_speed;
1481 }
1482
1483 int ClipItem::strobe() const
1484 {
1485     return m_strobe;
1486 }
1487
1488 void ClipItem::setSpeed(const double speed, const int strobe)
1489 {
1490     m_speed = speed;
1491     m_strobe = strobe;
1492     if (m_speed == 1.0) m_clipName = baseClip()->name();
1493     else m_clipName = baseClip()->name() + " - " + QString::number(speed * 100, 'f', 0) + '%';
1494     m_info.cropStart = GenTime((int)(m_speedIndependantInfo.cropStart.frames(m_fps) / m_speed + 0.5), m_fps);
1495     m_info.cropDuration = GenTime((int)(m_speedIndependantInfo.cropDuration.frames(m_fps) / m_speed + 0.5), m_fps);
1496     //update();
1497 }
1498
1499 GenTime ClipItem::maxDuration() const
1500 {
1501     return GenTime((int)(m_maxDuration.frames(m_fps) / m_speed + 0.5), m_fps);
1502 }
1503
1504 GenTime ClipItem::speedIndependantCropStart() const
1505 {
1506     return m_speedIndependantInfo.cropStart;
1507 }
1508
1509 GenTime ClipItem::speedIndependantCropDuration() const
1510 {
1511     return m_speedIndependantInfo.cropDuration;
1512 }
1513
1514
1515 const ItemInfo ClipItem::speedIndependantInfo() const
1516 {
1517     return m_speedIndependantInfo;
1518 }
1519
1520 //virtual
1521 void ClipItem::dropEvent(QGraphicsSceneDragDropEvent * event)
1522 {
1523     const QString effects = QString(event->mimeData()->data("kdenlive/effectslist"));
1524     QDomDocument doc;
1525     doc.setContent(effects, true);
1526     const QDomElement e = doc.documentElement();
1527     if (scene() && !scene()->views().isEmpty()) {
1528         event->accept();
1529         CustomTrackView *view = (CustomTrackView *) scene()->views()[0];
1530         if (view) view->slotAddEffect(e, m_info.startPos, track());
1531     }
1532 }
1533
1534 //virtual
1535 void ClipItem::dragEnterEvent(QGraphicsSceneDragDropEvent *event)
1536 {
1537     if (isItemLocked()) event->setAccepted(false);
1538     else event->setAccepted(event->mimeData()->hasFormat("kdenlive/effectslist"));
1539 }
1540
1541 void ClipItem::dragLeaveEvent(QGraphicsSceneDragDropEvent *event)
1542 {
1543     Q_UNUSED(event);
1544 }
1545
1546 void ClipItem::addTransition(Transition* t)
1547 {
1548     m_transitionsList.append(t);
1549     //CustomTrackView *view = (CustomTrackView *) scene()->views()[0];
1550     QDomDocument doc;
1551     QDomElement e = doc.documentElement();
1552     //if (view) view->slotAddTransition(this, t->toXML() , t->startPos(), track());
1553 }
1554
1555 void ClipItem::setVideoOnly(bool force)
1556 {
1557     m_videoOnly = force;
1558 }
1559
1560 void ClipItem::setAudioOnly(bool force)
1561 {
1562     m_audioOnly = force;
1563     if (m_audioOnly) m_baseColor = QColor(141, 215, 166);
1564     else {
1565         if (m_clipType == COLOR) {
1566             QString colour = m_clip->getProperty("colour");
1567             colour = colour.replace(0, 2, "#");
1568             m_baseColor = QColor(colour.left(7));
1569         } else if (m_clipType == AUDIO) m_baseColor = QColor(141, 215, 166);
1570         else m_baseColor = QColor(141, 166, 215);
1571     }
1572     m_audioThumbCachePic.clear();
1573 }
1574
1575 bool ClipItem::isAudioOnly() const
1576 {
1577     return m_audioOnly;
1578 }
1579
1580 bool ClipItem::isVideoOnly() const
1581 {
1582     return m_videoOnly;
1583 }
1584
1585
1586 #include "clipitem.moc"