]> git.sesse.net Git - kdenlive/blob - src/clipitem.cpp
- Fix resize start allowing to go further than duration = 0 (inverted the clip)
[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                 } else {
508                     m_info.cropDuration = m_maxDuration;
509                 }
510                 updateRectGeometry();
511             }
512         }
513     }
514     if (m_clipType == COLOR) {
515         QString colour = m_clip->getProperty("colour");
516         colour = colour.replace(0, 2, "#");
517         m_baseColor = QColor(colour.left(7));
518     } else resetThumbs(checkDuration);
519 }
520
521 void ClipItem::slotFetchThumbs()
522 {
523     if (scene() == NULL || m_clipType == AUDIO || m_clipType == COLOR) return;
524     if (m_clipType == IMAGE) {
525         if (m_startPix.isNull()) {
526             m_startPix = KThumb::getImage(KUrl(m_clip->getProperty("resource")), (int)(KdenliveSettings::trackheight() * KdenliveSettings::project_display_ratio()), KdenliveSettings::trackheight());
527             update();
528         }
529         return;
530     }
531
532     if (m_clipType == TEXT) {
533         if (m_startPix.isNull()) slotGetStartThumb();
534         return;
535     }
536
537     if (m_endPix.isNull() && m_startPix.isNull()) {
538         m_startThumbRequested = true;
539         m_endThumbRequested = true;
540         emit getThumb((int)m_speedIndependantInfo.cropStart.frames(m_fps), (int)(m_speedIndependantInfo.cropStart + m_speedIndependantInfo.cropDuration).frames(m_fps) - 1);
541     } else {
542         if (m_endPix.isNull()) {
543             slotGetEndThumb();
544         }
545         if (m_startPix.isNull()) {
546             slotGetStartThumb();
547         }
548     }
549 }
550
551 void ClipItem::slotGetStartThumb()
552 {
553     m_startThumbRequested = true;
554     emit getThumb((int)m_speedIndependantInfo.cropStart.frames(m_fps), -1);
555 }
556
557 void ClipItem::slotGetEndThumb()
558 {
559     m_endThumbRequested = true;
560     emit getThumb(-1, (int)(m_speedIndependantInfo.cropStart + m_speedIndependantInfo.cropDuration).frames(m_fps) - 1);
561 }
562
563
564 void ClipItem::slotSetStartThumb(QImage img)
565 {
566     if (!img.isNull() && img.format() == QImage::Format_ARGB32) {
567         QPixmap pix = QPixmap::fromImage(img);
568         m_startPix = pix;
569         QRectF r = sceneBoundingRect();
570         r.setRight(pix.width() + 2);
571         update(r);
572     }
573 }
574
575 void ClipItem::slotSetEndThumb(QImage img)
576 {
577     if (!img.isNull() && img.format() == QImage::Format_ARGB32) {
578         QPixmap pix = QPixmap::fromImage(img);
579         m_endPix = pix;
580         QRectF r = sceneBoundingRect();
581         r.setLeft(r.right() - pix.width() - 2);
582         update(r);
583     }
584 }
585
586 void ClipItem::slotThumbReady(int frame, QImage img)
587 {
588     if (scene() == NULL) return;
589     QRectF r = boundingRect();
590     QPixmap pix = QPixmap::fromImage(img);
591     double width = pix.width() / projectScene()->scale().x();
592     if (m_startThumbRequested && frame == m_speedIndependantInfo.cropStart.frames(m_fps)) {
593         m_startPix = pix;
594         m_startThumbRequested = false;
595         update(r.left(), r.top(), width, pix.height());
596         if (m_clipType == IMAGE || m_clipType == TEXT) {
597             update(r.right() - width, r.top(), width, pix.height());
598         }
599     } else if (m_endThumbRequested && frame == (m_speedIndependantInfo.cropStart + m_speedIndependantInfo.cropDuration).frames(m_fps) - 1) {
600         m_endPix = pix;
601         m_endThumbRequested = false;
602         update(r.right() - width, r.top(), width, pix.height());
603     }
604 }
605
606 void ClipItem::slotSetStartThumb(const QPixmap pix)
607 {
608     m_startPix = pix;
609 }
610
611 void ClipItem::slotSetEndThumb(const QPixmap pix)
612 {
613     m_endPix = pix;
614 }
615
616 QPixmap ClipItem::startThumb() const
617 {
618     return m_startPix;
619 }
620
621 QPixmap ClipItem::endThumb() const
622 {
623     return m_endPix;
624 }
625
626 void ClipItem::slotGotAudioData()
627 {
628     m_audioThumbReady = true;
629     if (m_clipType == AV && !isAudioOnly()) {
630         QRectF r = boundingRect();
631         r.setTop(r.top() + r.height() / 2 - 1);
632         update(r);
633     } else update();
634 }
635
636 int ClipItem::type() const
637 {
638     return AVWIDGET;
639 }
640
641 DocClipBase *ClipItem::baseClip() const
642 {
643     return m_clip;
644 }
645
646 QDomElement ClipItem::xml() const
647 {
648     return itemXml();
649 }
650
651 QDomElement ClipItem::itemXml() const
652 {
653     QDomElement xml = m_clip->toXML();
654     if (m_speed != 1.0) xml.setAttribute("speed", m_speed);
655     if (m_strobe > 1) xml.setAttribute("strobe", m_strobe);
656     if (m_audioOnly) xml.setAttribute("audio_only", 1);
657     else if (m_videoOnly) xml.setAttribute("video_only", 1);
658     return xml;
659 }
660
661 int ClipItem::clipType() const
662 {
663     return m_clipType;
664 }
665
666 QString ClipItem::clipName() const
667 {
668     return m_clipName;
669 }
670
671 void ClipItem::setClipName(const QString &name)
672 {
673     m_clipName = name;
674 }
675
676 const QString ClipItem::clipProducer() const
677 {
678     return m_producer;
679 }
680
681 void ClipItem::flashClip()
682 {
683     if (m_timeLine == 0) {
684         m_timeLine = new QTimeLine(750, this);
685         m_timeLine->setUpdateInterval(80);
686         m_timeLine->setCurveShape(QTimeLine::EaseInOutCurve);
687         m_timeLine->setFrameRange(0, 100);
688         connect(m_timeLine, SIGNAL(valueChanged(qreal)), this, SLOT(animate(qreal)));
689     }
690     //m_timeLine->start();
691 }
692
693 void ClipItem::animate(qreal /*value*/)
694 {
695     QRectF r = boundingRect();
696     r.setHeight(20);
697     update(r);
698 }
699
700 // virtual
701 void ClipItem::paint(QPainter *painter,
702                      const QStyleOptionGraphicsItem *option,
703                      QWidget *)
704 {
705     QColor paintColor;
706     if (parentItem()) paintColor = QColor(255, 248, 149);
707     else paintColor = m_baseColor;
708     if (isSelected() || (parentItem() && parentItem()->isSelected())) paintColor = paintColor.darker();
709
710     painter->setMatrixEnabled(false);
711     const QRectF mapped = painter->matrix().mapRect(rect()).adjusted(0.5, 0, 0.5, 0);
712     const QRectF exposed = option->exposedRect;
713     painter->setClipRect(mapped);
714     painter->fillRect(mapped, paintColor);
715
716     // draw thumbnails
717     if (KdenliveSettings::videothumbnails() && !isAudioOnly()) {
718         QPen pen = painter->pen();
719         pen.setColor(QColor(255, 255, 255, 150));
720         painter->setPen(pen);
721         if ((m_clipType == IMAGE || m_clipType == TEXT) && !m_startPix.isNull()) {
722             const QPointF top = mapped.topRight() - QPointF(m_startPix.width() - 1, 0);
723             painter->drawPixmap(top, m_startPix);
724             QLineF l2(top.x(), mapped.top(), top.x(), mapped.bottom());
725             painter->drawLine(l2);
726         } else if (!m_endPix.isNull()) {
727             const QPointF top = mapped.topRight() - QPointF(m_endPix.width() - 1, 0);
728             painter->drawPixmap(top, m_endPix);
729             QLineF l2(top.x(), mapped.top(), top.x(), mapped.bottom());
730             painter->drawLine(l2);
731         }
732         if (!m_startPix.isNull()) {
733             painter->drawPixmap(mapped.topLeft(), m_startPix);
734             QLineF l2(mapped.left() + m_startPix.width(), mapped.top(), mapped.left() + m_startPix.width(), mapped.bottom());
735             painter->drawLine(l2);
736         }
737         if (painter->matrix().m11() == FRAME_SIZE) {
738             int offset = (m_info.startPos - m_info.cropStart).frames(m_fps);
739             int left = qMax((int) m_info.startPos.frames(m_fps) + 1, (int) mapToScene(exposed.left(), 0).x());
740             int right = qMin((int)(m_info.startPos + m_info.cropDuration).frames(m_fps) - 1, (int) mapToScene(exposed.right(), 0).x());
741             doGetIntraThumbs(painter, mapped.topLeft(), m_info.cropStart.frames(m_fps), left - offset, right - offset);
742         }
743         painter->setPen(Qt::black);
744     }
745
746     // draw audio thumbnails
747     if (KdenliveSettings::audiothumbnails() && m_speed == 1.0 && !isVideoOnly() && ((m_clipType == AV && (exposed.bottom() > (rect().height() / 2) || isAudioOnly())) || m_clipType == AUDIO) && m_audioThumbReady) {
748
749         double startpixel = exposed.left();
750         if (startpixel < 0)
751             startpixel = 0;
752         double endpixel = exposed.right();
753         if (endpixel < 0)
754             endpixel = 0;
755         //kDebug()<<"///  REPAINTING AUDIO THMBS ZONE: "<<startpixel<<"x"<<endpixel;
756
757         /*QPainterPath path = m_clipType == AV ? roundRectPathLower : resultClipPath;*/
758         QRectF mappedRect;
759         if (m_clipType == AV && !isAudioOnly()) {
760             mappedRect = mapped;
761             mappedRect.setTop(mappedRect.bottom() - mapped.height() / 2);
762         } else mappedRect = mapped;
763
764         double scale = painter->matrix().m11();
765         int channels = 0;
766         if (isEnabled() && m_clip) channels = m_clip->getProperty("channels").toInt();
767         if (scale != m_framePixelWidth)
768             m_audioThumbCachePic.clear();
769         double cropLeft = m_info.cropStart.frames(m_fps);
770         const int clipStart = mappedRect.x();
771         const int mappedStartPixel =  painter->matrix().map(QPointF(startpixel + cropLeft, 0)).x() - clipStart;
772         const int mappedEndPixel =  painter->matrix().map(QPointF(endpixel + cropLeft, 0)).x() - clipStart;
773         cropLeft = cropLeft * scale;
774
775
776         if (channels >= 1) {
777             emit prepareAudioThumb(scale, mappedStartPixel, mappedEndPixel, channels);
778         }
779
780         for (int startCache = mappedStartPixel - (mappedStartPixel) % 100; startCache < mappedEndPixel; startCache += 100) {
781             if (m_audioThumbCachePic.contains(startCache) && !m_audioThumbCachePic[startCache].isNull())
782                 painter->drawPixmap(clipStart + startCache - cropLeft, mappedRect.y(),  m_audioThumbCachePic[startCache]);
783         }
784     }
785
786     // Draw effects names
787     if (!m_effectNames.isEmpty() && mapped.width() > 40) {
788         QRectF txtBounding = painter->boundingRect(mapped, Qt::AlignLeft | Qt::AlignTop, m_effectNames);
789         QColor bgColor;
790         if (m_timeLine && m_timeLine->state() == QTimeLine::Running) {
791             qreal value = m_timeLine->currentValue();
792             txtBounding.setWidth(txtBounding.width() * value);
793             bgColor.setRgb(50 + 200 *(1.0 - value), 50, 50, 100 + 50 * value);
794         } else bgColor.setRgb(50, 50, 90, 180);
795
796         QPainterPath rounded;
797         rounded.moveTo(txtBounding.bottomRight());
798         rounded.arcTo(txtBounding.right() - txtBounding.height() - 2, txtBounding.top() - txtBounding.height(), txtBounding.height() * 2, txtBounding.height() * 2, 270, 90);
799         rounded.lineTo(txtBounding.topLeft());
800         rounded.lineTo(txtBounding.bottomLeft());
801         painter->fillPath(rounded, bgColor);
802         painter->setPen(Qt::lightGray);
803         painter->drawText(txtBounding.adjusted(1, 0, 1, 0), Qt::AlignCenter, m_effectNames);
804     }
805
806     // Draw clip name
807     QColor frameColor(paintColor.darker());
808     if (isSelected() || (parentItem() && parentItem()->isSelected())) {
809         frameColor = QColor(Qt::red);
810     }
811     frameColor.setAlpha(160);
812
813     const QRectF txtBounding2 = painter->boundingRect(mapped, Qt::AlignHCenter | Qt::AlignVCenter, ' ' + m_clipName + ' ');
814     //painter->fillRect(txtBounding2, frameColor);
815     painter->setBrush(frameColor);
816     painter->setPen(Qt::NoPen);
817     painter->drawRoundedRect(txtBounding2, 3, 3);
818     painter->setBrush(QBrush(Qt::NoBrush));
819
820     //painter->setPen(QColor(0, 0, 0, 180));
821     //painter->drawText(txtBounding, Qt::AlignCenter, m_clipName);
822     if (m_videoOnly) {
823         painter->drawPixmap(txtBounding2.topLeft() - QPointF(17, -1), m_videoPix);
824     } else if (m_audioOnly) {
825         painter->drawPixmap(txtBounding2.topLeft() - QPointF(17, -1), m_audioPix);
826     }
827     painter->setPen(Qt::white);
828     painter->drawText(txtBounding2, Qt::AlignCenter, m_clipName);
829
830
831     // draw markers
832     if (isEnabled() && m_clip) {
833         QList < CommentedTime > markers = m_clip->commentedSnapMarkers();
834         QList < CommentedTime >::Iterator it = markers.begin();
835         GenTime pos;
836         double framepos;
837         QBrush markerBrush(QColor(120, 120, 0, 140));
838         QPen pen = painter->pen();
839         pen.setColor(QColor(255, 255, 255, 200));
840         pen.setStyle(Qt::DotLine);
841
842         for (; it != markers.end(); ++it) {
843             pos = GenTime((int)((*it).time().frames(m_fps) / qAbs(m_speed) + 0.5), m_fps) - cropStart();
844             if (pos > GenTime()) {
845                 if (pos > cropDuration()) break;
846                 QLineF l(rect().x() + pos.frames(m_fps), rect().y(), rect().x() + pos.frames(m_fps), rect().bottom());
847                 QLineF l2 = painter->matrix().map(l);
848                 painter->setPen(pen);
849                 painter->drawLine(l2);
850                 if (KdenliveSettings::showmarkers()) {
851                     framepos = rect().x() + pos.frames(m_fps);
852                     const QRectF r1(framepos + 0.04, 10, rect().width() - framepos - 2, rect().height() - 10);
853                     const QRectF r2 = painter->matrix().mapRect(r1);
854                     const QRectF txtBounding3 = painter->boundingRect(r2, Qt::AlignLeft | Qt::AlignTop, ' ' + (*it).comment() + ' ');
855                     painter->setBrush(markerBrush);
856                     painter->setPen(Qt::NoPen);
857                     painter->drawRoundedRect(txtBounding3, 3, 3);
858                     painter->setBrush(QBrush(Qt::NoBrush));
859                     painter->setPen(Qt::white);
860                     painter->drawText(txtBounding3, Qt::AlignCenter, (*it).comment());
861                 }
862                 //painter->fillRect(QRect(br.x() + framepos, br.y(), 10, br.height()), QBrush(QColor(0, 0, 0, 150)));
863             }
864         }
865     }
866
867     // draw start / end fades
868     QBrush fades;
869     if (isSelected()) {
870         fades = QBrush(QColor(200, 50, 50, 150));
871     } else fades = QBrush(QColor(200, 200, 200, 200));
872
873     if (m_startFade != 0) {
874         QPainterPath fadeInPath;
875         fadeInPath.moveTo(0, 0);
876         fadeInPath.lineTo(0, rect().height());
877         fadeInPath.lineTo(m_startFade, 0);
878         fadeInPath.closeSubpath();
879         QPainterPath f1 = painter->matrix().map(fadeInPath);
880         painter->fillPath(f1/*.intersected(resultClipPath)*/, fades);
881         /*if (isSelected()) {
882             QLineF l(m_startFade * scale, 0, 0, itemHeight);
883             painter->drawLine(l);
884         }*/
885     }
886     if (m_endFade != 0) {
887         QPainterPath fadeOutPath;
888         fadeOutPath.moveTo(rect().width(), 0);
889         fadeOutPath.lineTo(rect().width(), rect().height());
890         fadeOutPath.lineTo(rect().width() - m_endFade, 0);
891         fadeOutPath.closeSubpath();
892         QPainterPath f1 = painter->matrix().map(fadeOutPath);
893         painter->fillPath(f1/*.intersected(resultClipPath)*/, fades);
894         /*if (isSelected()) {
895             QLineF l(itemWidth - m_endFade * scale, 0, itemWidth, itemHeight);
896             painter->drawLine(l);
897         }*/
898     }
899
900
901     painter->setPen(QPen(Qt::lightGray));
902     // draw effect or transition keyframes
903     if (mapped.width() > 20) drawKeyFrames(painter, exposed);
904
905     //painter->setMatrixEnabled(true);
906
907     // draw clip border
908     // expand clip rect to allow correct painting of clip border
909     QPen pen1(frameColor);
910     painter->setPen(pen1);
911     painter->setClipping(false);
912     painter->drawRect(painter->matrix().mapRect(rect()));
913 }
914
915
916 OPERATIONTYPE ClipItem::operationMode(QPointF pos)
917 {
918     if (isItemLocked()) return NONE;
919     const double scale = projectScene()->scale().x();
920     double maximumOffset = 6 / scale;
921     if (isSelected() || (parentItem() && parentItem()->isSelected())) {
922         int kf = mouseOverKeyFrames(pos, maximumOffset);
923         if (kf != -1) {
924             m_editedKeyframe = kf;
925             return KEYFRAME;
926         }
927     }
928     QRectF rect = sceneBoundingRect();
929     int addtransitionOffset = 10;
930     // Don't allow add transition if track height is very small
931     if (rect.height() < 30) addtransitionOffset = 0;
932
933     if (qAbs((int)(pos.x() - (rect.x() + m_startFade))) < maximumOffset  && qAbs((int)(pos.y() - rect.y())) < 6) {
934         if (m_startFade == 0) setToolTip(i18n("Add audio fade"));
935         // xgettext:no-c-format
936         else setToolTip(i18n("Audio fade duration: %1s", GenTime(m_startFade, m_fps).seconds()));
937         return FADEIN;
938     } else if (pos.x() - rect.x() < maximumOffset && (rect.bottom() - pos.y() > addtransitionOffset)) {
939         // xgettext:no-c-format
940         setToolTip(i18n("Crop from start: %1s", cropStart().seconds()));
941         return RESIZESTART;
942     } else if (qAbs((int)(pos.x() - (rect.x() + rect.width() - m_endFade))) < maximumOffset && qAbs((int)(pos.y() - rect.y())) < 6) {
943         if (m_endFade == 0) setToolTip(i18n("Add audio fade"));
944         // xgettext:no-c-format
945         else setToolTip(i18n("Audio fade duration: %1s", GenTime(m_endFade, m_fps).seconds()));
946         return FADEOUT;
947     } else if ((rect.right() - pos.x() < maximumOffset) && (rect.bottom() - pos.y() > addtransitionOffset)) {
948         // xgettext:no-c-format
949         setToolTip(i18n("Clip duration: %1s", cropDuration().seconds()));
950         return RESIZEEND;
951     } else if ((pos.x() - rect.x() < 16 / scale) && (rect.bottom() - pos.y() <= addtransitionOffset)) {
952         setToolTip(i18n("Add transition"));
953         return TRANSITIONSTART;
954     } else if ((rect.right() - pos.x() < 16 / scale) && (rect.bottom() - pos.y() <= addtransitionOffset)) {
955         setToolTip(i18n("Add transition"));
956         return TRANSITIONEND;
957     }
958     QString tooltip = "<b>" + m_clipName + "</b>";
959     if (!baseClip()->fileURL().isEmpty())
960         tooltip.append("<br />" + baseClip()->fileURL().path());
961     if (!baseClip()->description().isEmpty())
962         tooltip.append("<br />" + baseClip()->description());
963     setToolTip(tooltip);
964     return MOVE;
965 }
966
967 QList <GenTime> ClipItem::snapMarkers() const
968 {
969     QList < GenTime > snaps;
970     QList < GenTime > markers = baseClip()->snapMarkers();
971     GenTime pos;
972
973     for (int i = 0; i < markers.size(); i++) {
974         pos = GenTime((int)(markers.at(i).frames(m_fps) / qAbs(m_speed) + 0.5), m_fps) - cropStart();
975         if (pos > GenTime()) {
976             if (pos > cropDuration()) break;
977             else snaps.append(pos + startPos());
978         }
979     }
980     return snaps;
981 }
982
983 QList <CommentedTime> ClipItem::commentedSnapMarkers() const
984 {
985     QList < CommentedTime > snaps;
986     QList < CommentedTime > markers = baseClip()->commentedSnapMarkers();
987     GenTime pos;
988
989     for (int i = 0; i < markers.size(); i++) {
990         pos = GenTime((int)(markers.at(i).time().frames(m_fps) / qAbs(m_speed) + 0.5), m_fps) - cropStart();
991         if (pos > GenTime()) {
992             if (pos > cropDuration()) break;
993             else snaps.append(CommentedTime(pos + startPos(), markers.at(i).comment()));
994         }
995     }
996     return snaps;
997 }
998
999 void ClipItem::slotPrepareAudioThumb(double pixelForOneFrame, int startpixel, int endpixel, int channels)
1000 {
1001     QRectF re =  sceneBoundingRect();
1002     if (m_clipType == AV && !isAudioOnly()) re.setTop(re.y() + re.height() / 2);
1003
1004     //kDebug() << "// PREP AUDIO THMB FRMO : scale:" << pixelForOneFrame<< ", from: " << startpixel << ", to: " << endpixel;
1005     //if ( (!audioThumbWasDrawn || framePixelWidth!=pixelForOneFrame ) && !baseClip()->audioFrameChache.isEmpty()){
1006
1007     for (int startCache = startpixel - startpixel % 100; startCache < endpixel; startCache += 100) {
1008         //kDebug() << "creating " << startCache;
1009         //if (framePixelWidth!=pixelForOneFrame  ||
1010         if (m_framePixelWidth == pixelForOneFrame && m_audioThumbCachePic.contains(startCache))
1011             continue;
1012         if (m_audioThumbCachePic[startCache].isNull() || m_framePixelWidth != pixelForOneFrame) {
1013             m_audioThumbCachePic[startCache] = QPixmap(100, (int)(re.height()));
1014             m_audioThumbCachePic[startCache].fill(QColor(180, 180, 200, 140));
1015         }
1016         bool fullAreaDraw = pixelForOneFrame < 10;
1017         QMap<int, QPainterPath > positiveChannelPaths;
1018         QMap<int, QPainterPath > negativeChannelPaths;
1019         QPainter pixpainter(&m_audioThumbCachePic[startCache]);
1020         QPen audiopen;
1021         audiopen.setWidth(0);
1022         pixpainter.setPen(audiopen);
1023         //pixpainter.setRenderHint(QPainter::Antialiasing,true);
1024         //pixpainter.drawLine(0,0,100,re.height());
1025         // Bail out, if caller provided invalid data
1026         if (channels <= 0) {
1027             kWarning() << "Unable to draw image with " << channels << "number of channels";
1028             return;
1029         }
1030
1031         int channelHeight = m_audioThumbCachePic[startCache].height() / channels;
1032
1033         for (int i = 0; i < channels; i++) {
1034
1035             positiveChannelPaths[i].moveTo(0, channelHeight*i + channelHeight / 2);
1036             negativeChannelPaths[i].moveTo(0, channelHeight*i + channelHeight / 2);
1037         }
1038
1039         for (int samples = 0; samples <= 100; samples++) {
1040             double frame = (double)(samples + startCache - 0) / pixelForOneFrame;
1041             int sample = (int)((frame - (int)(frame)) * 20);   // AUDIO_FRAME_SIZE
1042             if (frame < 0 || sample < 0 || sample > 19)
1043                 continue;
1044             QMap<int, QByteArray> frame_channel_data = baseClip()->m_audioFrameCache[(int)frame];
1045
1046             for (int channel = 0; channel < channels && frame_channel_data[channel].size() > 0; channel++) {
1047
1048                 int y = channelHeight * channel + channelHeight / 2;
1049                 int delta = (int)(frame_channel_data[channel][sample] - 127 / 2)  * channelHeight / 64;
1050                 if (fullAreaDraw) {
1051                     positiveChannelPaths[channel].lineTo(samples, 0.1 + y + qAbs(delta));
1052                     negativeChannelPaths[channel].lineTo(samples, 0.1 + y - qAbs(delta));
1053                 } else {
1054                     positiveChannelPaths[channel].lineTo(samples, 0.1 + y + delta);
1055                     negativeChannelPaths[channel].lineTo(samples, 0.1 + y - delta);
1056                 }
1057             }
1058             for (int channel = 0; channel < channels ; channel++)
1059                 if (fullAreaDraw && samples == 100) {
1060                     positiveChannelPaths[channel].lineTo(samples, channelHeight*channel + channelHeight / 2);
1061                     negativeChannelPaths[channel].lineTo(samples, channelHeight*channel + channelHeight / 2);
1062                     positiveChannelPaths[channel].lineTo(0, channelHeight*channel + channelHeight / 2);
1063                     negativeChannelPaths[channel].lineTo(0, channelHeight*channel + channelHeight / 2);
1064                 }
1065
1066         }
1067         pixpainter.setPen(QPen(QColor(0, 0, 0)));
1068         pixpainter.setBrush(QBrush(QColor(60, 60, 60)));
1069
1070         for (int i = 0; i < channels; i++) {
1071             if (fullAreaDraw) {
1072                 //pixpainter.fillPath(positiveChannelPaths[i].united(negativeChannelPaths[i]),QBrush(Qt::SolidPattern));//or singleif looks better
1073                 pixpainter.drawPath(positiveChannelPaths[i].united(negativeChannelPaths[i]));//or singleif looks better
1074             } else
1075                 pixpainter.drawPath(positiveChannelPaths[i]);
1076         }
1077     }
1078     //audioThumbWasDrawn=true;
1079     m_framePixelWidth = pixelForOneFrame;
1080
1081     //}
1082 }
1083
1084 int ClipItem::fadeIn() const
1085 {
1086     return m_startFade;
1087 }
1088
1089 int ClipItem::fadeOut() const
1090 {
1091     return m_endFade;
1092 }
1093
1094
1095 void ClipItem::setFadeIn(int pos)
1096 {
1097     if (pos == m_startFade) return;
1098     int oldIn = m_startFade;
1099     if (pos < 0) pos = 0;
1100     if (pos > cropDuration().frames(m_fps)) pos = (int)(cropDuration().frames(m_fps));
1101     m_startFade = pos;
1102     QRectF rect = boundingRect();
1103     update(rect.x(), rect.y(), qMax(oldIn, pos), rect.height());
1104 }
1105
1106 void ClipItem::setFadeOut(int pos)
1107 {
1108     if (pos == m_endFade) return;
1109     int oldOut = m_endFade;
1110     if (pos < 0) pos = 0;
1111     if (pos > cropDuration().frames(m_fps)) pos = (int)(cropDuration().frames(m_fps));
1112     m_endFade = pos;
1113     QRectF rect = boundingRect();
1114     update(rect.x() + rect.width() - qMax(oldOut, pos), rect.y(), qMax(oldOut, pos), rect.height());
1115
1116 }
1117
1118 void ClipItem::setFades(int in, int out)
1119 {
1120     m_startFade = in;
1121     m_endFade = out;
1122 }
1123
1124 /*
1125 //virtual
1126 void ClipItem::hoverEnterEvent(QGraphicsSceneHoverEvent *e)
1127 {
1128     //if (e->pos().x() < 20) m_hover = true;
1129     return;
1130     if (isItemLocked()) return;
1131     m_hover = true;
1132     QRectF r = boundingRect();
1133     double width = 35 / projectScene()->scale().x();
1134     double height = r.height() / 2;
1135     //WARNING: seems like it generates a full repaint of the clip, maybe not so good...
1136     update(r.x(), r.y() + height, width, height);
1137     update(r.right() - width, r.y() + height, width, height);
1138 }
1139
1140 //virtual
1141 void ClipItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *)
1142 {
1143     if (isItemLocked()) return;
1144     m_hover = false;
1145     QRectF r = boundingRect();
1146     double width = 35 / projectScene()->scale().x();
1147     double height = r.height() / 2;
1148     //WARNING: seems like it generates a full repaint of the clip, maybe not so good...
1149     update(r.x(), r.y() + height, width, height);
1150     update(r.right() - width, r.y() + height, width, height);
1151 }
1152 */
1153
1154 void ClipItem::resizeStart(int posx, bool /*size*/)
1155 {
1156     bool sizeLimit = false;
1157     if (clipType() != IMAGE && clipType() != COLOR && clipType() != TEXT) {
1158         const int min = (startPos() - cropStart()).frames(m_fps);
1159         if (posx < min) posx = min;
1160         sizeLimit = true;
1161     }
1162
1163     if (posx == startPos().frames(m_fps)) return;
1164     const int previous = cropStart().frames(m_fps);
1165     AbstractClipItem::resizeStart(posx, sizeLimit);
1166
1167     // set speed independant info
1168     m_speedIndependantInfo = m_info;
1169     m_speedIndependantInfo.cropStart = GenTime((int)(m_info.cropStart.frames(m_fps) * qAbs(m_speed)), m_fps);
1170     m_speedIndependantInfo.cropDuration = GenTime((int)(m_info.cropDuration.frames(m_fps) * qAbs(m_speed)), m_fps);
1171
1172     if ((int) cropStart().frames(m_fps) != previous) {
1173         if (m_hasThumbs && KdenliveSettings::videothumbnails()) {
1174             m_startThumbTimer.start(150);
1175         }
1176     }
1177 }
1178
1179 void ClipItem::resizeEnd(int posx)
1180 {
1181     const int max = (startPos() - cropStart() + maxDuration()).frames(m_fps);
1182     if (posx > max && maxDuration() != GenTime()) posx = max;
1183     if (posx == endPos().frames(m_fps)) return;
1184     //kDebug() << "// NEW POS: " << posx << ", OLD END: " << endPos().frames(m_fps);
1185     const int previous = cropDuration().frames(m_fps);
1186     AbstractClipItem::resizeEnd(posx);
1187
1188     // set speed independant info
1189     m_speedIndependantInfo = m_info;
1190     m_speedIndependantInfo.cropStart = GenTime((int)(m_info.cropStart.frames(m_fps) * qAbs(m_speed)), m_fps);
1191     m_speedIndependantInfo.cropDuration = GenTime((int)(m_info.cropDuration.frames(m_fps) * qAbs(m_speed)), m_fps);
1192
1193     if ((int) cropDuration().frames(m_fps) != previous) {
1194         if (m_hasThumbs && KdenliveSettings::videothumbnails()) {
1195             m_endThumbTimer.start(150);
1196         }
1197     }
1198 }
1199
1200
1201 bool ClipItem::checkEffectsKeyframesPos(const int previous, const int current, bool fromStart)
1202 {
1203     bool modified = false;
1204     for (int i = 0; i < m_effectList.count(); i++) {
1205         QDomElement effect = m_effectList.at(i);
1206         QDomNodeList params = effect.elementsByTagName("parameter");
1207         for (int j = 0; j < params.count(); j++) {
1208             QDomElement e = params.item(i).toElement();
1209             if (!e.isNull() && (e.attribute("type") == "keyframe" || e.attribute("type") == "simplekeyframe")) {
1210                 // parse keyframes and adjust values
1211                 const QStringList keyframes = e.attribute("keyframes").split(';', QString::SkipEmptyParts);
1212                 QMap <int, double> kfr;
1213                 int pos;
1214                 double val;
1215                 foreach(const QString &str, keyframes) {
1216                     pos = str.section(':', 0, 0).toInt();
1217                     val = str.section(':', 1, 1).toDouble();
1218                     if (pos == previous) {
1219                         // first or last keyframe
1220                         kfr[current] = val;
1221                         modified = true;
1222                     } else {
1223                         if ((fromStart && pos >= current) || (!fromStart && pos <= current)) {
1224                             // only keyframes in range
1225                             kfr[pos] = val;
1226                             modified = true;
1227                         }
1228                     }
1229                 }
1230                 if (modified) {
1231                     QString newkfr;
1232                     QMap<int, double>::const_iterator k = kfr.constBegin();
1233                     while (k != kfr.constEnd()) {
1234                         newkfr.append(QString::number(k.key()) + ':' + QString::number(k.value()) + ';');
1235                         ++k;
1236                     }
1237                     e.setAttribute("keyframes", newkfr);
1238                     break;
1239                 }
1240             }
1241         }
1242     }
1243     if (modified && m_selectedEffect >= 0) setSelectedEffect(m_selectedEffect);
1244     return modified;
1245 }
1246
1247 //virtual
1248 QVariant ClipItem::itemChange(GraphicsItemChange change, const QVariant &value)
1249 {
1250     if (change == QGraphicsItem::ItemSelectedChange) {
1251         if (value.toBool()) setZValue(10);
1252         else setZValue(2);
1253     }
1254     if (change == ItemPositionChange && scene()) {
1255         // calculate new position.
1256         //if (parentItem()) return pos();
1257         QPointF newPos = value.toPointF();
1258         //kDebug() << "/// MOVING CLIP ITEM.------------\n++++++++++";
1259         int xpos = projectScene()->getSnapPointForPos((int) newPos.x(), KdenliveSettings::snaptopoints());
1260         xpos = qMax(xpos, 0);
1261         newPos.setX(xpos);
1262         int newTrack = newPos.y() / KdenliveSettings::trackheight();
1263         newTrack = qMin(newTrack, projectScene()->tracksCount() - 1);
1264         newTrack = qMax(newTrack, 0);
1265         newPos.setY((int)(newTrack  * KdenliveSettings::trackheight() + 1));
1266         // Only one clip is moving
1267         QRectF sceneShape = rect();
1268         sceneShape.translate(newPos);
1269         QList<QGraphicsItem*> items;
1270         if (projectScene()->editMode() == NORMALEDIT)
1271             items = scene()->items(sceneShape, Qt::IntersectsItemShape);
1272         items.removeAll(this);
1273         bool forwardMove = newPos.x() > pos().x();
1274         int offset = 0;
1275         if (!items.isEmpty()) {
1276             for (int i = 0; i < items.count(); i++) {
1277                 if (!items.at(i)->isEnabled()) continue;
1278                 if (items.at(i)->type() == type()) {
1279                     // Collision!
1280                     QPointF otherPos = items.at(i)->pos();
1281                     if ((int) otherPos.y() != (int) pos().y()) {
1282                         return pos();
1283                     }
1284                     if (forwardMove) {
1285                         offset = qMax(offset, (int)(newPos.x() - (static_cast < AbstractClipItem* >(items.at(i))->startPos() - cropDuration()).frames(m_fps)));
1286                     } else {
1287                         offset = qMax(offset, (int)((static_cast < AbstractClipItem* >(items.at(i))->endPos().frames(m_fps)) - newPos.x()));
1288                     }
1289
1290                     if (offset > 0) {
1291                         if (forwardMove) {
1292                             sceneShape.translate(QPointF(-offset, 0));
1293                             newPos.setX(newPos.x() - offset);
1294                         } else {
1295                             sceneShape.translate(QPointF(offset, 0));
1296                             newPos.setX(newPos.x() + offset);
1297                         }
1298                         QList<QGraphicsItem*> subitems = scene()->items(sceneShape, Qt::IntersectsItemShape);
1299                         subitems.removeAll(this);
1300                         for (int j = 0; j < subitems.count(); j++) {
1301                             if (!subitems.at(j)->isEnabled()) continue;
1302                             if (subitems.at(j)->type() == type()) {
1303                                 // move was not successful, revert to previous pos
1304                                 m_info.startPos = GenTime((int) pos().x(), m_fps);
1305                                 return pos();
1306                             }
1307                         }
1308                     }
1309
1310                     m_info.track = newTrack;
1311                     m_info.startPos = GenTime((int) newPos.x(), m_fps);
1312
1313                     return newPos;
1314                 }
1315             }
1316         }
1317         m_info.track = newTrack;
1318         m_info.startPos = GenTime((int) newPos.x(), m_fps);
1319         //kDebug()<<"// ITEM NEW POS: "<<newPos.x()<<", mapped: "<<mapToScene(newPos.x(), 0).x();
1320         return newPos;
1321     }
1322     return QGraphicsItem::itemChange(change, value);
1323 }
1324
1325 // virtual
1326 /*void ClipItem::mouseMoveEvent(QGraphicsSceneMouseEvent * event) {
1327 }*/
1328
1329 int ClipItem::effectsCounter()
1330 {
1331     return effectsCount() + 1;
1332 }
1333
1334 int ClipItem::effectsCount()
1335 {
1336     return m_effectList.count();
1337 }
1338
1339 int ClipItem::hasEffect(const QString &tag, const QString &id) const
1340 {
1341     return m_effectList.hasEffect(tag, id);
1342 }
1343
1344 QStringList ClipItem::effectNames()
1345 {
1346     return m_effectList.effectNames();
1347 }
1348
1349 QDomElement ClipItem::effectAt(int ix) const
1350 {
1351     if (ix > m_effectList.count() - 1 || ix < 0 || m_effectList.at(ix).isNull()) return QDomElement();
1352     return m_effectList.at(ix).cloneNode().toElement();
1353 }
1354
1355 QDomElement ClipItem::getEffectAt(int ix) const
1356 {
1357     if (ix > m_effectList.count() - 1 || ix < 0 || m_effectList.at(ix).isNull()) return QDomElement();
1358     return m_effectList.at(ix);
1359 }
1360
1361 void ClipItem::setEffectAt(int ix, QDomElement effect)
1362 {
1363     if (ix < 0 || ix > (m_effectList.count() - 1) || effect.isNull()) {
1364         kDebug() << "Invalid effect index: " << ix;
1365         return;
1366     }
1367     //kDebug() << "CHange EFFECT AT: " << ix << ", CURR: " << m_effectList.at(ix).attribute("tag") << ", NEW: " << effect.attribute("tag");
1368     effect.setAttribute("kdenlive_ix", ix + 1);
1369     m_effectList.replace(ix, effect);
1370     m_effectNames = m_effectList.effectNames().join(" / ");
1371     QString id = effect.attribute("id");
1372     if (id == "fadein" || id == "fadeout" || id == "fade_from_black" || id == "fade_to_black")
1373         update();
1374     else {
1375         QRectF r = boundingRect();
1376         r.setHeight(20);
1377         update(r);
1378     }
1379 }
1380
1381 EffectsParameterList ClipItem::addEffect(const QDomElement effect, bool /*animate*/)
1382 {
1383     bool needRepaint = false;
1384     int ix;
1385     if (!effect.hasAttribute("kdenlive_ix")) {
1386         ix = effectsCounter();
1387     } else ix = effect.attribute("kdenlive_ix").toInt();
1388     if (!m_effectList.isEmpty() && ix <= m_effectList.count()) {
1389         needRepaint = true;
1390         m_effectList.insert(ix - 1, effect);
1391         for (int i = ix; i < m_effectList.count(); i++) {
1392             int index = m_effectList.item(i).attribute("kdenlive_ix").toInt();
1393             if (index >= ix) m_effectList.item(i).setAttribute("kdenlive_ix", index + 1);
1394         }
1395     } else m_effectList.append(effect);
1396     EffectsParameterList parameters;
1397     parameters.addParam("tag", effect.attribute("tag"));
1398     parameters.addParam("kdenlive_ix", effect.attribute("kdenlive_ix"));
1399     if (effect.hasAttribute("src")) parameters.addParam("src", effect.attribute("src"));
1400     if (effect.hasAttribute("disable")) parameters.addParam("disable", effect.attribute("disable"));
1401
1402
1403     QString effectId = effect.attribute("id");
1404     if (effectId.isEmpty()) effectId = effect.attribute("tag");
1405     parameters.addParam("id", effectId);
1406
1407     QDomNodeList params = effect.elementsByTagName("parameter");
1408     int fade = 0;
1409     for (int i = 0; i < params.count(); i++) {
1410         QDomElement e = params.item(i).toElement();
1411         if (!e.isNull()) {
1412             if (e.attribute("type") == "simplekeyframe") {
1413                 QStringList values = e.attribute("keyframes").split(";", QString::SkipEmptyParts);
1414                 double factor = e.attribute("factor", "1").toDouble();
1415                 if (factor != 1) {
1416                     for (int j = 0; j < values.count(); j++) {
1417                         QString pos = values.at(j).section(":", 0, 0);
1418                         double val = values.at(j).section(":", 1, 1).toDouble() / factor;
1419                         values[j] = pos + "=" + QString::number(val);
1420                     }
1421                 }
1422                 parameters.addParam(e.attribute("name"), values.join(";"));
1423                 /*parameters.addParam("max", e.attribute("max"));
1424                 parameters.addParam("min", e.attribute("min"));
1425                 parameters.addParam("factor", );*/
1426             } else if (e.attribute("type") == "keyframe") {
1427                 parameters.addParam("keyframes", e.attribute("keyframes"));
1428                 parameters.addParam("max", e.attribute("max"));
1429                 parameters.addParam("min", e.attribute("min"));
1430                 parameters.addParam("factor", e.attribute("factor", "1"));
1431                 parameters.addParam("starttag", e.attribute("starttag", "start"));
1432                 parameters.addParam("endtag", e.attribute("endtag", "end"));
1433             } else if (e.attribute("factor", "1") == "1") {
1434                 parameters.addParam(e.attribute("name"), e.attribute("value"));
1435
1436                 // check if it is a fade effect
1437                 if (effectId == "fadein") {
1438                     needRepaint = true;
1439                     if (m_effectList.hasEffect(QString(), "fade_from_black") == -1) {
1440                         if (e.attribute("name") == "out") fade += e.attribute("value").toInt();
1441                         else if (e.attribute("name") == "in") fade -= e.attribute("value").toInt();
1442                     } else {
1443                         QDomElement fadein = m_effectList.getEffectByTag(QString(), "fade_from_black");
1444                         if (fadein.attribute("name") == "out") fade += fadein.attribute("value").toInt();
1445                         else if (fadein.attribute("name") == "in") fade -= fadein.attribute("value").toInt();
1446                     }
1447                 } else if (effectId == "fade_from_black") {
1448                     needRepaint = true;
1449                     if (m_effectList.hasEffect(QString(), "fadein") == -1) {
1450                         if (e.attribute("name") == "out") fade += e.attribute("value").toInt();
1451                         else if (e.attribute("name") == "in") fade -= e.attribute("value").toInt();
1452                     } else {
1453                         QDomElement fadein = m_effectList.getEffectByTag(QString(), "fadein");
1454                         if (fadein.attribute("name") == "out") fade += fadein.attribute("value").toInt();
1455                         else if (fadein.attribute("name") == "in") fade -= fadein.attribute("value").toInt();
1456                     }
1457                 } else if (effectId == "fadeout") {
1458                     needRepaint = true;
1459                     if (m_effectList.hasEffect(QString(), "fade_to_black") == -1) {
1460                         if (e.attribute("name") == "out") fade -= e.attribute("value").toInt();
1461                         else if (e.attribute("name") == "in") fade += e.attribute("value").toInt();
1462                     } else {
1463                         QDomElement fadeout = m_effectList.getEffectByTag(QString(), "fade_to_black");
1464                         if (fadeout.attribute("name") == "out") fade -= fadeout.attribute("value").toInt();
1465                         else if (fadeout.attribute("name") == "in") fade += fadeout.attribute("value").toInt();
1466                     }
1467                 } else if (effectId == "fade_to_black") {
1468                     needRepaint = true;
1469                     if (m_effectList.hasEffect(QString(), "fadeout") == -1) {
1470                         if (e.attribute("name") == "out") fade -= e.attribute("value").toInt();
1471                         else if (e.attribute("name") == "in") fade += e.attribute("value").toInt();
1472                     } else {
1473                         QDomElement fadeout = m_effectList.getEffectByTag(QString(), "fadeout");
1474                         if (fadeout.attribute("name") == "out") fade -= fadeout.attribute("value").toInt();
1475                         else if (fadeout.attribute("name") == "in") fade += fadeout.attribute("value").toInt();
1476                     }
1477                 }
1478             } else {
1479                 double fact;
1480                 if (e.attribute("factor").startsWith('%')) {
1481                     fact = ProfilesDialog::getStringEval(projectScene()->profile(), e.attribute("factor"));
1482                 } else fact = e.attribute("factor", "1").toDouble();
1483                 parameters.addParam(e.attribute("name"), QString::number(e.attribute("value").toDouble() / fact));
1484             }
1485         }
1486     }
1487     m_effectNames = m_effectList.effectNames().join(" / ");
1488     if (fade > 0) m_startFade = fade;
1489     else if (fade < 0) m_endFade = -fade;
1490
1491     if (m_selectedEffect == -1) {
1492         setSelectedEffect(0);
1493     } else if (m_selectedEffect == ix - 1) setSelectedEffect(m_selectedEffect);
1494     if (needRepaint) update(boundingRect());
1495     /*if (animate) {
1496         flashClip();
1497     } */
1498     else { /*if (!needRepaint) */
1499         QRectF r = boundingRect();
1500         r.setHeight(20);
1501         update(r);
1502     }
1503     return parameters;
1504 }
1505
1506 EffectsParameterList ClipItem::getEffectArgs(const QDomElement effect)
1507 {
1508     EffectsParameterList parameters;
1509     parameters.addParam("tag", effect.attribute("tag"));
1510     parameters.addParam("kdenlive_ix", effect.attribute("kdenlive_ix"));
1511     parameters.addParam("id", effect.attribute("id"));
1512     if (effect.hasAttribute("src")) parameters.addParam("src", effect.attribute("src"));
1513     if (effect.hasAttribute("disable")) parameters.addParam("disable", effect.attribute("disable"));
1514
1515     QDomNodeList params = effect.elementsByTagName("parameter");
1516     for (int i = 0; i < params.count(); i++) {
1517         QDomElement e = params.item(i).toElement();
1518         //kDebug() << "/ / / /SENDING EFFECT PARAM: " << e.attribute("type") << ", NAME_ " << e.attribute("tag");
1519         if (e.attribute("type") == "simplekeyframe") {
1520
1521             QStringList values = e.attribute("keyframes").split(";", QString::SkipEmptyParts);
1522             double factor = e.attribute("factor", "1").toDouble();
1523             for (int j = 0; j < values.count(); j++) {
1524                 QString pos = values.at(j).section(":", 0, 0);
1525                 double val = values.at(j).section(":", 1, 1).toDouble() / factor;
1526                 values[j] = pos + "=" + QString::number(val);
1527             }
1528             // kDebug() << "/ / / /SENDING KEYFR:" << values;
1529             parameters.addParam(e.attribute("name"), values.join(";"));
1530             /*parameters.addParam(e.attribute("name"), e.attribute("keyframes").replace(":", "="));
1531             parameters.addParam("max", e.attribute("max"));
1532             parameters.addParam("min", e.attribute("min"));
1533             parameters.addParam("factor", e.attribute("factor", "1"));*/
1534         } else if (e.attribute("type") == "keyframe") {
1535             kDebug() << "/ / / /SENDING KEYFR EFFECT TYPE";
1536             parameters.addParam("keyframes", e.attribute("keyframes"));
1537             parameters.addParam("max", e.attribute("max"));
1538             parameters.addParam("min", e.attribute("min"));
1539             parameters.addParam("factor", e.attribute("factor", "1"));
1540             parameters.addParam("starttag", e.attribute("starttag", "start"));
1541             parameters.addParam("endtag", e.attribute("endtag", "end"));
1542         } else if (e.attribute("namedesc").contains(';')) {
1543             QString format = e.attribute("format");
1544             QStringList separators = format.split("%d", QString::SkipEmptyParts);
1545             QStringList values = e.attribute("value").split(QRegExp("[,:;x]"));
1546             QString neu;
1547             QTextStream txtNeu(&neu);
1548             if (values.size() > 0)
1549                 txtNeu << (int)values[0].toDouble();
1550             for (int i = 0; i < separators.size() && i + 1 < values.size(); i++) {
1551                 txtNeu << separators[i];
1552                 txtNeu << (int)(values[i+1].toDouble());
1553             }
1554             parameters.addParam("start", neu);
1555         } else {
1556             if (e.attribute("factor", "1") != "1") {
1557                 double fact;
1558                 if (e.attribute("factor").startsWith('%')) {
1559                     fact = ProfilesDialog::getStringEval(projectScene()->profile(), e.attribute("factor"));
1560                 } else fact = e.attribute("factor", "1").toDouble();
1561                 parameters.addParam(e.attribute("name"), QString::number(e.attribute("value").toDouble() / fact));
1562             } else {
1563                 parameters.addParam(e.attribute("name"), e.attribute("value"));
1564             }
1565         }
1566     }
1567     return parameters;
1568 }
1569
1570 void ClipItem::deleteEffect(QString index)
1571 {
1572     bool needRepaint = false;
1573     QString ix;
1574
1575     for (int i = 0; i < m_effectList.count(); ++i) {
1576         ix = m_effectList.at(i).attribute("kdenlive_ix");
1577         if (ix == index) {
1578             QString effectId = m_effectList.at(i).attribute("id");
1579             if ((effectId == "fadein" && hasEffect(QString(), "fade_from_black") == -1) ||
1580                     (effectId == "fade_from_black" && hasEffect(QString(), "fadein") == -1)) {
1581                 m_startFade = 0;
1582                 needRepaint = true;
1583             } else if ((effectId == "fadeout" && hasEffect(QString(), "fade_to_black") == -1) ||
1584                        (effectId == "fade_to_black" && hasEffect(QString(), "fadeout") == -1)) {
1585                 m_endFade = 0;
1586                 needRepaint = true;
1587             } else if (EffectsList::hasKeyFrames(m_effectList.at(i))) needRepaint = true;
1588             m_effectList.removeAt(i);
1589             i--;
1590         } else if (ix.toInt() > index.toInt()) {
1591             m_effectList.item(i).setAttribute("kdenlive_ix", ix.toInt() - 1);
1592         }
1593     }
1594     m_effectNames = m_effectList.effectNames().join(" / ");
1595
1596     if (m_effectList.isEmpty() || m_selectedEffect + 1 == index.toInt()) {
1597         // Current effect was removed
1598         if (index.toInt() > m_effectList.count() - 1) {
1599             setSelectedEffect(m_effectList.count() - 1);
1600         } else setSelectedEffect(index.toInt());
1601     }
1602     if (needRepaint) update(boundingRect());
1603     else {
1604         QRectF r = boundingRect();
1605         r.setHeight(20);
1606         update(r);
1607     }
1608     //if (!m_effectList.isEmpty()) flashClip();
1609 }
1610
1611 double ClipItem::speed() const
1612 {
1613     return m_speed;
1614 }
1615
1616 int ClipItem::strobe() const
1617 {
1618     return m_strobe;
1619 }
1620
1621 void ClipItem::setSpeed(const double speed, const int strobe)
1622 {
1623     m_speed = speed;
1624     if (m_speed <= 0 && m_speed > -1)
1625         m_speed = 1.0;
1626     m_strobe = strobe;
1627     if (m_speed == 1.0) m_clipName = baseClip()->name();
1628     else m_clipName = baseClip()->name() + " - " + QString::number(speed * 100, 'f', 0) + '%';
1629     m_info.cropStart = GenTime((int)(m_speedIndependantInfo.cropStart.frames(m_fps) / qAbs(m_speed) + 0.5), m_fps);
1630     m_info.cropDuration = GenTime((int)(m_speedIndependantInfo.cropDuration.frames(m_fps) / qAbs(m_speed) + 0.5), m_fps);
1631     //update();
1632 }
1633
1634 GenTime ClipItem::maxDuration() const
1635 {
1636     return GenTime((int)(m_maxDuration.frames(m_fps) / qAbs(m_speed) + 0.5), m_fps);
1637 }
1638
1639 GenTime ClipItem::speedIndependantCropStart() const
1640 {
1641     return m_speedIndependantInfo.cropStart;
1642 }
1643
1644 GenTime ClipItem::speedIndependantCropDuration() const
1645 {
1646     return m_speedIndependantInfo.cropDuration;
1647 }
1648
1649
1650 const ItemInfo ClipItem::speedIndependantInfo() const
1651 {
1652     return m_speedIndependantInfo;
1653 }
1654
1655 //virtual
1656 void ClipItem::dropEvent(QGraphicsSceneDragDropEvent * event)
1657 {
1658     const QString effects = QString(event->mimeData()->data("kdenlive/effectslist"));
1659     QDomDocument doc;
1660     doc.setContent(effects, true);
1661     const QDomElement e = doc.documentElement();
1662     if (scene() && !scene()->views().isEmpty()) {
1663         event->accept();
1664         CustomTrackView *view = (CustomTrackView *) scene()->views()[0];
1665         if (view) view->slotAddEffect(e, m_info.startPos, track());
1666     }
1667 }
1668
1669 //virtual
1670 void ClipItem::dragEnterEvent(QGraphicsSceneDragDropEvent *event)
1671 {
1672     if (isItemLocked()) event->setAccepted(false);
1673     else event->setAccepted(event->mimeData()->hasFormat("kdenlive/effectslist"));
1674 }
1675
1676 void ClipItem::dragLeaveEvent(QGraphicsSceneDragDropEvent *event)
1677 {
1678     Q_UNUSED(event);
1679 }
1680
1681 void ClipItem::addTransition(Transition* t)
1682 {
1683     m_transitionsList.append(t);
1684     //CustomTrackView *view = (CustomTrackView *) scene()->views()[0];
1685     QDomDocument doc;
1686     QDomElement e = doc.documentElement();
1687     //if (view) view->slotAddTransition(this, t->toXML() , t->startPos(), track());
1688 }
1689
1690 void ClipItem::setVideoOnly(bool force)
1691 {
1692     m_videoOnly = force;
1693 }
1694
1695 void ClipItem::setAudioOnly(bool force)
1696 {
1697     m_audioOnly = force;
1698     if (m_audioOnly) m_baseColor = QColor(141, 215, 166);
1699     else {
1700         if (m_clipType == COLOR) {
1701             QString colour = m_clip->getProperty("colour");
1702             colour = colour.replace(0, 2, "#");
1703             m_baseColor = QColor(colour.left(7));
1704         } else if (m_clipType == AUDIO) m_baseColor = QColor(141, 215, 166);
1705         else m_baseColor = QColor(141, 166, 215);
1706     }
1707     m_audioThumbCachePic.clear();
1708 }
1709
1710 bool ClipItem::isAudioOnly() const
1711 {
1712     return m_audioOnly;
1713 }
1714
1715 bool ClipItem::isVideoOnly() const
1716 {
1717     return m_videoOnly;
1718 }
1719
1720 void ClipItem::insertKeyframe(QDomElement effect, int pos, int val)
1721 {
1722     if (effect.attribute("disable") == "1") return;
1723     effect.setAttribute("active_keyframe", pos);
1724     m_editedKeyframe = pos;
1725     QDomNodeList params = effect.elementsByTagName("parameter");
1726     for (int i = 0; i < params.count(); i++) {
1727         QDomElement e = params.item(i).toElement();
1728         QString kfr = e.attribute("keyframes");
1729         const QStringList keyframes = kfr.split(';', QString::SkipEmptyParts);
1730         QStringList newkfr;
1731         bool added = false;
1732         foreach(const QString &str, keyframes) {
1733             int kpos = str.section(':', 0, 0).toInt();
1734             double newval = str.section(':', 1, 1).toDouble();
1735             if (kpos < pos) {
1736                 newkfr.append(str);
1737             } else if (!added) {
1738                 if (i == 0) newkfr.append(QString::number(pos) + ":" + QString::number(val));
1739                 else newkfr.append(QString::number(pos) + ":" + QString::number(newval));
1740                 if (kpos > pos) newkfr.append(str);
1741                 added = true;
1742             } else newkfr.append(str);
1743         }
1744         if (!added) newkfr.append(QString::number(pos) + ":" + QString::number(val));
1745         e.setAttribute("keyframes", newkfr.join(";"));
1746     }
1747 }
1748
1749 void ClipItem::movedKeyframe(QDomElement effect, int oldpos, int newpos, double value)
1750 {
1751     if (effect.attribute("disable") == "1") return;
1752     effect.setAttribute("active_keyframe", newpos);
1753     QDomNodeList params = effect.elementsByTagName("parameter");
1754     int start = cropStart().frames(m_fps);
1755     int end = (cropStart() + cropDuration()).frames(m_fps) - 1;
1756     for (int i = 0; i < params.count(); i++) {
1757         QDomElement e = params.item(i).toElement();
1758         QString kfr = e.attribute("keyframes");
1759         const QStringList keyframes = kfr.split(';', QString::SkipEmptyParts);
1760         QStringList newkfr;
1761         foreach(const QString &str, keyframes) {
1762             if (str.section(':', 0, 0).toInt() != oldpos) {
1763                 newkfr.append(str);
1764             } else if (newpos != -1) {
1765                 newpos = qMax(newpos, start);
1766                 newpos = qMin(newpos, end);
1767                 if (i == 0) newkfr.append(QString::number(newpos) + ":" + QString::number(value));
1768                 else newkfr.append(QString::number(newpos) + ":" + str.section(':', 1, 1));
1769             }
1770         }
1771         e.setAttribute("keyframes", newkfr.join(";"));
1772     }
1773
1774     updateKeyframes(effect);
1775     update();
1776 }
1777
1778 void ClipItem::updateKeyframes(QDomElement effect)
1779 {
1780     m_keyframes.clear();
1781     // parse keyframes
1782     QDomNodeList params = effect.elementsByTagName("parameter");
1783     QDomElement e = params.item(0).toElement();
1784     const QStringList keyframes = e.attribute("keyframes").split(';', QString::SkipEmptyParts);
1785     foreach(const QString &str, keyframes) {
1786         int pos = str.section(':', 0, 0).toInt();
1787         double val = str.section(':', 1, 1).toDouble();
1788         m_keyframes[pos] = val;
1789     }
1790     if (!m_keyframes.contains(m_selectedKeyframe)) m_selectedKeyframe = -1;
1791 }
1792
1793 void ClipItem::doGetIntraThumbs(QPainter *painter, const QPointF startPos, int offset, int start, int end)
1794 {
1795     if (!m_clip->thumbProducer() || clipType() == COLOR) return;
1796     if (scene() && scene()->views().isEmpty()) return;
1797     CustomTrackView *view = (CustomTrackView *) scene()->views()[0];
1798     if (view == NULL) return;
1799     const int theight = KdenliveSettings::trackheight();
1800     const int twidth = FRAME_SIZE;
1801
1802     if (clipType() == IMAGE || clipType() == TEXT) {
1803         for (int i = start; i <= end; i++)
1804             painter->drawPixmap(startPos + QPointF(twidth *(i - offset), 0), m_startPix);
1805     }
1806     QPixmap p;
1807     for (int i = start; i <= end; i++) {
1808         if (!view->pixmapCache->find(m_clip->fileURL().path() + "%" + QString::number(i), p)) {
1809             p = m_clip->thumbProducer()->extractImage(i, twidth, theight);
1810             view->pixmapCache->insert(m_clip->fileURL().path() + "%" + QString::number(i), p);
1811         }
1812         painter->drawPixmap(startPos + QPointF(twidth *(i - offset), 0), p);
1813     }
1814 }
1815
1816
1817 #include "clipitem.moc"