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