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