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