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