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